]> granicus.if.org Git - libvpx/blob - vp9/vp9_cx_iface.c
0f0b7a5abbdecfa0c2475a84d9a7b22cfc6b67bf
[libvpx] / vp9 / vp9_cx_iface.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "./vpx_config.h"
15 #include "vpx/vpx_codec.h"
16 #include "vpx/internal/vpx_codec_internal.h"
17 #include "./vpx_version.h"
18 #include "vp9/encoder/vp9_encoder.h"
19 #include "vpx/vp8cx.h"
20 #include "vp9/encoder/vp9_firstpass.h"
21 #include "vp9/vp9_iface_common.h"
22
23 struct vp9_extracfg {
24   int                         cpu_used;  // available cpu percentage in 1/16
25   unsigned int                enable_auto_alt_ref;
26   unsigned int                noise_sensitivity;
27   unsigned int                sharpness;
28   unsigned int                static_thresh;
29   unsigned int                tile_columns;
30   unsigned int                tile_rows;
31   unsigned int                arnr_max_frames;
32   unsigned int                arnr_strength;
33   vp8e_tuning                 tuning;
34   unsigned int                cq_level;  // constrained quality level
35   unsigned int                rc_max_intra_bitrate_pct;
36   unsigned int                lossless;
37   unsigned int                frame_parallel_decoding_mode;
38   AQ_MODE                     aq_mode;
39   unsigned int                frame_periodic_boost;
40   vpx_bit_depth_t             bit_depth;
41   vp9e_tune_content           content;
42 };
43
44 static struct vp9_extracfg default_extra_cfg = {
45   0,                          // cpu_used
46   1,                          // enable_auto_alt_ref
47   0,                          // noise_sensitivity
48   0,                          // sharpness
49   0,                          // static_thresh
50   0,                          // tile_columns
51   0,                          // tile_rows
52   7,                          // arnr_max_frames
53   5,                          // arnr_strength
54   VP8_TUNE_PSNR,              // tuning
55   10,                         // cq_level
56   0,                          // rc_max_intra_bitrate_pct
57   0,                          // lossless
58   0,                          // frame_parallel_decoding_mode
59   NO_AQ,                      // aq_mode
60   0,                          // frame_periodic_delta_q
61   VPX_BITS_8,                 // Bit depth
62   VP9E_CONTENT_DEFAULT        // content
63 };
64
65 struct vpx_codec_alg_priv {
66   vpx_codec_priv_t        base;
67   vpx_codec_enc_cfg_t     cfg;
68   struct vp9_extracfg     extra_cfg;
69   VP9EncoderConfig        oxcf;
70   VP9_COMP               *cpi;
71   unsigned char          *cx_data;
72   size_t                  cx_data_sz;
73   unsigned char          *pending_cx_data;
74   size_t                  pending_cx_data_sz;
75   int                     pending_frame_count;
76   size_t                  pending_frame_sizes[8];
77   size_t                  pending_frame_magnitude;
78   vpx_image_t             preview_img;
79   vp8_postproc_cfg_t      preview_ppcfg;
80   vpx_codec_pkt_list_decl(256) pkt_list;
81   unsigned int                 fixed_kf_cntr;
82 };
83
84 static VP9_REFFRAME ref_frame_to_vp9_reframe(vpx_ref_frame_type_t frame) {
85   switch (frame) {
86     case VP8_LAST_FRAME:
87       return VP9_LAST_FLAG;
88     case VP8_GOLD_FRAME:
89       return VP9_GOLD_FLAG;
90     case VP8_ALTR_FRAME:
91       return VP9_ALT_FLAG;
92   }
93   assert(0 && "Invalid Reference Frame");
94   return VP9_LAST_FLAG;
95 }
96
97 static vpx_codec_err_t update_error_state(vpx_codec_alg_priv_t *ctx,
98     const struct vpx_internal_error_info *error) {
99   const vpx_codec_err_t res = error->error_code;
100
101   if (res != VPX_CODEC_OK)
102     ctx->base.err_detail = error->has_detail ? error->detail : NULL;
103
104   return res;
105 }
106
107
108 #undef ERROR
109 #define ERROR(str) do {\
110     ctx->base.err_detail = str;\
111     return VPX_CODEC_INVALID_PARAM;\
112   } while (0)
113
114 #define RANGE_CHECK(p, memb, lo, hi) do {\
115     if (!(((p)->memb == lo || (p)->memb > (lo)) && (p)->memb <= hi)) \
116       ERROR(#memb " out of range ["#lo".."#hi"]");\
117   } while (0)
118
119 #define RANGE_CHECK_HI(p, memb, hi) do {\
120     if (!((p)->memb <= (hi))) \
121       ERROR(#memb " out of range [.."#hi"]");\
122   } while (0)
123
124 #define RANGE_CHECK_LO(p, memb, lo) do {\
125     if (!((p)->memb >= (lo))) \
126       ERROR(#memb " out of range ["#lo"..]");\
127   } while (0)
128
129 #define RANGE_CHECK_BOOL(p, memb) do {\
130     if (!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean");\
131   } while (0)
132
133 static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t *ctx,
134                                        const vpx_codec_enc_cfg_t *cfg,
135                                        const struct vp9_extracfg *extra_cfg) {
136   RANGE_CHECK(cfg, g_w,                   1, 65535);  // 16 bits available
137   RANGE_CHECK(cfg, g_h,                   1, 65535);  // 16 bits available
138   RANGE_CHECK(cfg, g_timebase.den,        1, 1000000000);
139   RANGE_CHECK(cfg, g_timebase.num,        1, cfg->g_timebase.den);
140   RANGE_CHECK_HI(cfg, g_profile,          3);
141
142   RANGE_CHECK_HI(cfg, rc_max_quantizer,   63);
143   RANGE_CHECK_HI(cfg, rc_min_quantizer,   cfg->rc_max_quantizer);
144   RANGE_CHECK_BOOL(extra_cfg, lossless);
145   RANGE_CHECK(extra_cfg, aq_mode,           0, AQ_MODE_COUNT - 1);
146   RANGE_CHECK(extra_cfg, frame_periodic_boost, 0, 1);
147   RANGE_CHECK_HI(cfg, g_threads,          64);
148   RANGE_CHECK_HI(cfg, g_lag_in_frames,    MAX_LAG_BUFFERS);
149   RANGE_CHECK(cfg, rc_end_usage,          VPX_VBR, VPX_Q);
150   RANGE_CHECK_HI(cfg, rc_undershoot_pct,  1000);
151   RANGE_CHECK_HI(cfg, rc_overshoot_pct,   1000);
152   RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
153   RANGE_CHECK(cfg, kf_mode,               VPX_KF_DISABLED, VPX_KF_AUTO);
154   RANGE_CHECK_BOOL(cfg,                   rc_resize_allowed);
155   RANGE_CHECK_HI(cfg, rc_dropframe_thresh,   100);
156   RANGE_CHECK_HI(cfg, rc_resize_up_thresh,   100);
157   RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
158   RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
159
160   if (cfg->rc_resize_allowed == 1) {
161     RANGE_CHECK(cfg, rc_scaled_width, 1, cfg->g_w);
162     RANGE_CHECK(cfg, rc_scaled_height, 1, cfg->g_h);
163   }
164
165   RANGE_CHECK(cfg, ss_number_layers, 1, VPX_SS_MAX_LAYERS);
166   RANGE_CHECK(cfg, ts_number_layers, 1, VPX_TS_MAX_LAYERS);
167
168   if (cfg->ts_number_layers > 1) {
169     unsigned int i;
170     for (i = 1; i < cfg->ts_number_layers; ++i)
171       if (cfg->ts_target_bitrate[i] < cfg->ts_target_bitrate[i - 1])
172         ERROR("ts_target_bitrate entries are not increasing");
173
174     RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers - 1], 1, 1);
175     for (i = cfg->ts_number_layers - 2; i > 0; --i)
176       if (cfg->ts_rate_decimator[i - 1] != 2 * cfg->ts_rate_decimator[i])
177         ERROR("ts_rate_decimator factors are not powers of 2");
178   }
179
180 #if CONFIG_SPATIAL_SVC
181   if (cfg->ss_number_layers * cfg->ts_number_layers > REF_FRAMES)
182     ERROR("Too many layers. Maximum 8 layers could be set");
183
184   if ((cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) &&
185       cfg->g_pass == VPX_RC_LAST_PASS) {
186     unsigned int i, alt_ref_sum = 0;
187     for (i = 0; i < cfg->ss_number_layers; ++i) {
188       if (cfg->ss_enable_auto_alt_ref[i])
189         ++alt_ref_sum;
190     }
191     if (alt_ref_sum >
192         REF_FRAMES - cfg->ss_number_layers * cfg->ts_number_layers)
193       ERROR("Not enough ref buffers for svc alt ref frames");
194     if ((cfg->ss_number_layers > 3 ||
195          cfg->ss_number_layers * cfg->ts_number_layers > 4) &&
196         cfg->g_error_resilient == 0)
197     ERROR("Multiple frame context are not supported for more than 3 spatial "
198           "layers or more than 4 spatial x temporal layers");
199   }
200 #endif
201
202   // VP9 does not support a lower bound on the keyframe interval in
203   // automatic keyframe placement mode.
204   if (cfg->kf_mode != VPX_KF_DISABLED &&
205       cfg->kf_min_dist != cfg->kf_max_dist &&
206       cfg->kf_min_dist > 0)
207     ERROR("kf_min_dist not supported in auto mode, use 0 "
208           "or kf_max_dist instead.");
209
210   RANGE_CHECK_BOOL(extra_cfg,  enable_auto_alt_ref);
211   RANGE_CHECK(extra_cfg, cpu_used, -16, 16);
212   RANGE_CHECK_HI(extra_cfg, noise_sensitivity, 6);
213   RANGE_CHECK(extra_cfg, tile_columns, 0, 6);
214   RANGE_CHECK(extra_cfg, tile_rows, 0, 2);
215   RANGE_CHECK_HI(extra_cfg, sharpness, 7);
216   RANGE_CHECK(extra_cfg, arnr_max_frames, 0, 15);
217   RANGE_CHECK_HI(extra_cfg, arnr_strength, 6);
218   RANGE_CHECK(extra_cfg, cq_level, 0, 63);
219   RANGE_CHECK(cfg, g_bit_depth, VPX_BITS_8, VPX_BITS_12);
220   RANGE_CHECK(cfg, g_input_bit_depth, 8, 12);
221   RANGE_CHECK(extra_cfg, content,
222               VP9E_CONTENT_DEFAULT, VP9E_CONTENT_INVALID - 1);
223
224   // TODO(yaowu): remove this when ssim tuning is implemented for vp9
225   if (extra_cfg->tuning == VP8_TUNE_SSIM)
226       ERROR("Option --tune=ssim is not currently supported in VP9.");
227
228   if (cfg->g_pass == VPX_RC_LAST_PASS) {
229     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
230     const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
231     const FIRSTPASS_STATS *stats;
232
233     if (cfg->rc_twopass_stats_in.buf == NULL)
234       ERROR("rc_twopass_stats_in.buf not set.");
235
236     if (cfg->rc_twopass_stats_in.sz % packet_sz)
237       ERROR("rc_twopass_stats_in.sz indicates truncated packet.");
238
239     if (cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) {
240       int i;
241       unsigned int n_packets_per_layer[VPX_SS_MAX_LAYERS] = {0};
242
243       stats = cfg->rc_twopass_stats_in.buf;
244       for (i = 0; i < n_packets; ++i) {
245         const int layer_id = (int)stats[i].spatial_layer_id;
246         if (layer_id >= 0 && layer_id < (int)cfg->ss_number_layers) {
247           ++n_packets_per_layer[layer_id];
248         }
249       }
250
251       for (i = 0; i < (int)cfg->ss_number_layers; ++i) {
252         unsigned int layer_id;
253         if (n_packets_per_layer[i] < 2) {
254           ERROR("rc_twopass_stats_in requires at least two packets for each "
255                 "layer.");
256         }
257
258         stats = (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf +
259                 n_packets - cfg->ss_number_layers + i;
260         layer_id = (int)stats->spatial_layer_id;
261
262         if (layer_id >= cfg->ss_number_layers
263             ||(unsigned int)(stats->count + 0.5) !=
264                n_packets_per_layer[layer_id] - 1)
265           ERROR("rc_twopass_stats_in missing EOS stats packet");
266       }
267     } else {
268       if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
269         ERROR("rc_twopass_stats_in requires at least two packets.");
270
271       stats =
272           (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf + n_packets - 1;
273
274       if ((int)(stats->count + 0.5) != n_packets - 1)
275         ERROR("rc_twopass_stats_in missing EOS stats packet");
276     }
277   }
278
279 #if !CONFIG_VP9_HIGHBITDEPTH
280   if (cfg->g_profile > (unsigned int)PROFILE_1)
281     ERROR("Profile > 1 not supported in this build configuration");
282 #endif
283   if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
284       extra_cfg->bit_depth > VPX_BITS_8)
285     ERROR("Codec high bit-depth not supported in profile < 2");
286   if (cfg->g_profile > (unsigned int)PROFILE_1 &&
287       extra_cfg->bit_depth == VPX_BITS_8)
288     ERROR("Codec bit-depth 8 not supported in profile > 1");
289
290   return VPX_CODEC_OK;
291 }
292
293
294 static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
295                                     const vpx_image_t *img) {
296   switch (img->fmt) {
297     case VPX_IMG_FMT_YV12:
298     case VPX_IMG_FMT_I420:
299     case VPX_IMG_FMT_I422:
300     case VPX_IMG_FMT_I444:
301       break;
302     default:
303       ERROR("Invalid image format. Only YV12, I420, I422, I444 images are "
304             "supported.");
305       break;
306   }
307
308   if (img->d_w != ctx->cfg.g_w || img->d_h != ctx->cfg.g_h)
309     ERROR("Image size must match encoder init configuration size");
310
311   return VPX_CODEC_OK;
312 }
313
314 static int get_image_bps(const vpx_image_t *img) {
315   switch (img->fmt) {
316     case VPX_IMG_FMT_YV12:
317     case VPX_IMG_FMT_I420: return 12;
318     case VPX_IMG_FMT_I422: return 16;
319     case VPX_IMG_FMT_I444: return 24;
320     case VPX_IMG_FMT_I42016: return 24;
321     case VPX_IMG_FMT_I42216: return 32;
322     case VPX_IMG_FMT_I44416: return 48;
323     default: assert(0 && "Invalid image format"); break;
324   }
325   return 0;
326 }
327
328 static vpx_codec_err_t set_encoder_config(
329     VP9EncoderConfig *oxcf,
330     const vpx_codec_enc_cfg_t *cfg,
331     const struct vp9_extracfg *extra_cfg) {
332   const int is_vbr = cfg->rc_end_usage == VPX_VBR;
333   oxcf->profile = cfg->g_profile;
334   oxcf->width   = cfg->g_w;
335   oxcf->height  = cfg->g_h;
336   oxcf->bit_depth = extra_cfg->bit_depth;
337   oxcf->input_bit_depth = cfg->g_input_bit_depth;
338   // guess a frame rate if out of whack, use 30
339   oxcf->init_framerate = (double)cfg->g_timebase.den / cfg->g_timebase.num;
340   if (oxcf->init_framerate > 180)
341     oxcf->init_framerate = 30;
342
343   oxcf->mode = GOOD;
344
345   switch (cfg->g_pass) {
346     case VPX_RC_ONE_PASS:
347       oxcf->pass = 0;
348       break;
349     case VPX_RC_FIRST_PASS:
350       oxcf->pass = 1;
351       break;
352     case VPX_RC_LAST_PASS:
353       oxcf->pass = 2;
354       break;
355   }
356
357   oxcf->lag_in_frames = cfg->g_pass == VPX_RC_FIRST_PASS ? 0
358                                                          : cfg->g_lag_in_frames;
359   oxcf->rc_mode = cfg->rc_end_usage;
360
361   // Convert target bandwidth from Kbit/s to Bit/s
362   oxcf->target_bandwidth = 1000 * cfg->rc_target_bitrate;
363   oxcf->rc_max_intra_bitrate_pct = extra_cfg->rc_max_intra_bitrate_pct;
364
365   oxcf->best_allowed_q =
366       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_min_quantizer);
367   oxcf->worst_allowed_q =
368       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_max_quantizer);
369   oxcf->cq_level        = vp9_quantizer_to_qindex(extra_cfg->cq_level);
370   oxcf->fixed_q = -1;
371
372   oxcf->under_shoot_pct         = cfg->rc_undershoot_pct;
373   oxcf->over_shoot_pct          = cfg->rc_overshoot_pct;
374
375   oxcf->allow_spatial_resampling = cfg->rc_resize_allowed;
376   oxcf->scaled_frame_width       = cfg->rc_scaled_width;
377   oxcf->scaled_frame_height      = cfg->rc_scaled_height;
378
379   oxcf->maximum_buffer_size_ms   = is_vbr ? 240000 : cfg->rc_buf_sz;
380   oxcf->starting_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_initial_sz;
381   oxcf->optimal_buffer_level_ms  = is_vbr ? 60000 : cfg->rc_buf_optimal_sz;
382
383   oxcf->drop_frames_water_mark   = cfg->rc_dropframe_thresh;
384
385   oxcf->two_pass_vbrbias         = cfg->rc_2pass_vbr_bias_pct;
386   oxcf->two_pass_vbrmin_section  = cfg->rc_2pass_vbr_minsection_pct;
387   oxcf->two_pass_vbrmax_section  = cfg->rc_2pass_vbr_maxsection_pct;
388
389   oxcf->auto_key               = cfg->kf_mode == VPX_KF_AUTO &&
390                                  cfg->kf_min_dist != cfg->kf_max_dist;
391
392   oxcf->key_freq               = cfg->kf_max_dist;
393
394   oxcf->speed                  =  abs(extra_cfg->cpu_used);
395   oxcf->encode_breakout        =  extra_cfg->static_thresh;
396   oxcf->play_alternate         =  extra_cfg->enable_auto_alt_ref;
397   oxcf->noise_sensitivity      =  extra_cfg->noise_sensitivity;
398   oxcf->sharpness              =  extra_cfg->sharpness;
399
400   oxcf->two_pass_stats_in      =  cfg->rc_twopass_stats_in;
401
402 #if CONFIG_FP_MB_STATS
403   oxcf->firstpass_mb_stats_in  = cfg->rc_firstpass_mb_stats_in;
404 #endif
405
406   oxcf->arnr_max_frames = extra_cfg->arnr_max_frames;
407   oxcf->arnr_strength   = extra_cfg->arnr_strength;
408
409   oxcf->tuning = extra_cfg->tuning;
410   oxcf->content = extra_cfg->content;
411
412   oxcf->tile_columns = extra_cfg->tile_columns;
413   oxcf->tile_rows    = extra_cfg->tile_rows;
414
415   oxcf->error_resilient_mode         = cfg->g_error_resilient;
416   oxcf->frame_parallel_decoding_mode = extra_cfg->frame_parallel_decoding_mode;
417
418   oxcf->aq_mode = extra_cfg->aq_mode;
419
420   oxcf->frame_periodic_boost =  extra_cfg->frame_periodic_boost;
421
422   oxcf->ss_number_layers = cfg->ss_number_layers;
423
424   if (oxcf->ss_number_layers > 1) {
425     int i;
426     for (i = 0; i < VPX_SS_MAX_LAYERS; ++i) {
427       oxcf->ss_target_bitrate[i] =  1000 * cfg->ss_target_bitrate[i];
428 #if CONFIG_SPATIAL_SVC
429       oxcf->ss_play_alternate[i] =  cfg->ss_enable_auto_alt_ref[i];
430 #endif
431     }
432   } else if (oxcf->ss_number_layers == 1) {
433     oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;
434 #if CONFIG_SPATIAL_SVC
435     oxcf->ss_play_alternate[0] = extra_cfg->enable_auto_alt_ref;
436 #endif
437   }
438
439   oxcf->ts_number_layers = cfg->ts_number_layers;
440
441   if (oxcf->ts_number_layers > 1) {
442     int i;
443     for (i = 0; i < VPX_TS_MAX_LAYERS; ++i) {
444       oxcf->ts_target_bitrate[i] = 1000 * cfg->ts_target_bitrate[i];
445       oxcf->ts_rate_decimator[i] = cfg->ts_rate_decimator[i];
446     }
447   } else if (oxcf->ts_number_layers == 1) {
448     oxcf->ts_target_bitrate[0] = (int)oxcf->target_bandwidth;
449     oxcf->ts_rate_decimator[0] = 1;
450   }
451
452   /*
453   printf("Current VP9 Settings: \n");
454   printf("target_bandwidth: %d\n", oxcf->target_bandwidth);
455   printf("noise_sensitivity: %d\n", oxcf->noise_sensitivity);
456   printf("sharpness: %d\n",    oxcf->sharpness);
457   printf("cpu_used: %d\n",  oxcf->cpu_used);
458   printf("Mode: %d\n",     oxcf->mode);
459   printf("auto_key: %d\n",  oxcf->auto_key);
460   printf("key_freq: %d\n", oxcf->key_freq);
461   printf("end_usage: %d\n", oxcf->end_usage);
462   printf("under_shoot_pct: %d\n", oxcf->under_shoot_pct);
463   printf("over_shoot_pct: %d\n", oxcf->over_shoot_pct);
464   printf("starting_buffer_level: %d\n", oxcf->starting_buffer_level);
465   printf("optimal_buffer_level: %d\n",  oxcf->optimal_buffer_level);
466   printf("maximum_buffer_size: %d\n", oxcf->maximum_buffer_size);
467   printf("fixed_q: %d\n",  oxcf->fixed_q);
468   printf("worst_allowed_q: %d\n", oxcf->worst_allowed_q);
469   printf("best_allowed_q: %d\n", oxcf->best_allowed_q);
470   printf("allow_spatial_resampling: %d\n", oxcf->allow_spatial_resampling);
471   printf("scaled_frame_width: %d\n", oxcf->scaled_frame_width);
472   printf("scaled_frame_height: %d\n", oxcf->scaled_frame_height);
473   printf("two_pass_vbrbias: %d\n",  oxcf->two_pass_vbrbias);
474   printf("two_pass_vbrmin_section: %d\n", oxcf->two_pass_vbrmin_section);
475   printf("two_pass_vbrmax_section: %d\n", oxcf->two_pass_vbrmax_section);
476   printf("lag_in_frames: %d\n", oxcf->lag_in_frames);
477   printf("play_alternate: %d\n", oxcf->play_alternate);
478   printf("Version: %d\n", oxcf->Version);
479   printf("encode_breakout: %d\n", oxcf->encode_breakout);
480   printf("error resilient: %d\n", oxcf->error_resilient_mode);
481   printf("frame parallel detokenization: %d\n",
482          oxcf->frame_parallel_decoding_mode);
483   */
484   return VPX_CODEC_OK;
485 }
486
487 static vpx_codec_err_t encoder_set_config(vpx_codec_alg_priv_t *ctx,
488                                           const vpx_codec_enc_cfg_t  *cfg) {
489   vpx_codec_err_t res;
490
491   if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h)
492     ERROR("Cannot change width or height after initialization");
493
494   // Prevent increasing lag_in_frames. This check is stricter than it needs
495   // to be -- the limit is not increasing past the first lag_in_frames
496   // value, but we don't track the initial config, only the last successful
497   // config.
498   if (cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames)
499     ERROR("Cannot increase lag_in_frames");
500
501   res = validate_config(ctx, cfg, &ctx->extra_cfg);
502
503   if (res == VPX_CODEC_OK) {
504     ctx->cfg = *cfg;
505     set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
506     vp9_change_config(ctx->cpi, &ctx->oxcf);
507   }
508
509   return res;
510 }
511
512 static vpx_codec_err_t ctrl_get_quantizer(vpx_codec_alg_priv_t *ctx,
513                                           va_list args) {
514   int *const arg = va_arg(args, int *);
515   if (arg == NULL)
516     return VPX_CODEC_INVALID_PARAM;
517   *arg = vp9_get_quantizer(ctx->cpi);
518   return VPX_CODEC_OK;
519 }
520
521 static vpx_codec_err_t ctrl_get_quantizer64(vpx_codec_alg_priv_t *ctx,
522                                             va_list args) {
523   int *const arg = va_arg(args, int *);
524   if (arg == NULL)
525     return VPX_CODEC_INVALID_PARAM;
526   *arg = vp9_qindex_to_quantizer(vp9_get_quantizer(ctx->cpi));
527   return VPX_CODEC_OK;
528 }
529
530 static vpx_codec_err_t update_extra_cfg(vpx_codec_alg_priv_t *ctx,
531                                         const struct vp9_extracfg *extra_cfg) {
532   const vpx_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg);
533   if (res == VPX_CODEC_OK) {
534     ctx->extra_cfg = *extra_cfg;
535     set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
536     vp9_change_config(ctx->cpi, &ctx->oxcf);
537   }
538   return res;
539 }
540
541 static vpx_codec_err_t ctrl_set_cpuused(vpx_codec_alg_priv_t *ctx,
542                                         va_list args) {
543   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
544   extra_cfg.cpu_used = CAST(VP8E_SET_CPUUSED, args);
545   return update_extra_cfg(ctx, &extra_cfg);
546 }
547
548 static vpx_codec_err_t ctrl_set_enable_auto_alt_ref(vpx_codec_alg_priv_t *ctx,
549                                                     va_list args) {
550   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
551   extra_cfg.enable_auto_alt_ref = CAST(VP8E_SET_ENABLEAUTOALTREF, args);
552   return update_extra_cfg(ctx, &extra_cfg);
553 }
554
555 static vpx_codec_err_t ctrl_set_noise_sensitivity(vpx_codec_alg_priv_t *ctx,
556                                                   va_list args) {
557   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
558   extra_cfg.noise_sensitivity = CAST(VP8E_SET_NOISE_SENSITIVITY, args);
559   return update_extra_cfg(ctx, &extra_cfg);
560 }
561
562 static vpx_codec_err_t ctrl_set_sharpness(vpx_codec_alg_priv_t *ctx,
563                                           va_list args) {
564   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
565   extra_cfg.sharpness = CAST(VP8E_SET_SHARPNESS, args);
566   return update_extra_cfg(ctx, &extra_cfg);
567 }
568
569 static vpx_codec_err_t ctrl_set_static_thresh(vpx_codec_alg_priv_t *ctx,
570                                               va_list args) {
571   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
572   extra_cfg.static_thresh = CAST(VP8E_SET_STATIC_THRESHOLD, args);
573   return update_extra_cfg(ctx, &extra_cfg);
574 }
575
576 static vpx_codec_err_t ctrl_set_tile_columns(vpx_codec_alg_priv_t *ctx,
577                                              va_list args) {
578   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
579   extra_cfg.tile_columns = CAST(VP9E_SET_TILE_COLUMNS, args);
580   return update_extra_cfg(ctx, &extra_cfg);
581 }
582
583 static vpx_codec_err_t ctrl_set_tile_rows(vpx_codec_alg_priv_t *ctx,
584                                           va_list args) {
585   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
586   extra_cfg.tile_rows = CAST(VP9E_SET_TILE_ROWS, args);
587   return update_extra_cfg(ctx, &extra_cfg);
588 }
589
590 static vpx_codec_err_t ctrl_set_arnr_max_frames(vpx_codec_alg_priv_t *ctx,
591                                                 va_list args) {
592   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
593   extra_cfg.arnr_max_frames = CAST(VP8E_SET_ARNR_MAXFRAMES, args);
594   return update_extra_cfg(ctx, &extra_cfg);
595 }
596
597 static vpx_codec_err_t ctrl_set_arnr_strength(vpx_codec_alg_priv_t *ctx,
598                                               va_list args) {
599   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
600   extra_cfg.arnr_strength = CAST(VP8E_SET_ARNR_STRENGTH, args);
601   return update_extra_cfg(ctx, &extra_cfg);
602 }
603
604 static vpx_codec_err_t ctrl_set_arnr_type(vpx_codec_alg_priv_t *ctx,
605                                           va_list args) {
606   (void)ctx;
607   (void)args;
608   return VPX_CODEC_OK;
609 }
610
611 static vpx_codec_err_t ctrl_set_tuning(vpx_codec_alg_priv_t *ctx,
612                                        va_list args) {
613   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
614   extra_cfg.tuning = CAST(VP8E_SET_TUNING, args);
615   return update_extra_cfg(ctx, &extra_cfg);
616 }
617
618 static vpx_codec_err_t ctrl_set_cq_level(vpx_codec_alg_priv_t *ctx,
619                                          va_list args) {
620   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
621   extra_cfg.cq_level = CAST(VP8E_SET_CQ_LEVEL, args);
622   return update_extra_cfg(ctx, &extra_cfg);
623 }
624
625 static vpx_codec_err_t ctrl_set_rc_max_intra_bitrate_pct(
626     vpx_codec_alg_priv_t *ctx, va_list args) {
627   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
628   extra_cfg.rc_max_intra_bitrate_pct =
629       CAST(VP8E_SET_MAX_INTRA_BITRATE_PCT, args);
630   return update_extra_cfg(ctx, &extra_cfg);
631 }
632
633 static vpx_codec_err_t ctrl_set_lossless(vpx_codec_alg_priv_t *ctx,
634                                          va_list args) {
635   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
636   extra_cfg.lossless = CAST(VP9E_SET_LOSSLESS, args);
637   return update_extra_cfg(ctx, &extra_cfg);
638 }
639
640 static vpx_codec_err_t ctrl_set_frame_parallel_decoding_mode(
641     vpx_codec_alg_priv_t *ctx, va_list args) {
642   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
643   extra_cfg.frame_parallel_decoding_mode =
644       CAST(VP9E_SET_FRAME_PARALLEL_DECODING, args);
645   return update_extra_cfg(ctx, &extra_cfg);
646 }
647
648 static vpx_codec_err_t ctrl_set_aq_mode(vpx_codec_alg_priv_t *ctx,
649                                         va_list args) {
650   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
651   extra_cfg.aq_mode = CAST(VP9E_SET_AQ_MODE, args);
652   return update_extra_cfg(ctx, &extra_cfg);
653 }
654
655 static vpx_codec_err_t ctrl_set_frame_periodic_boost(vpx_codec_alg_priv_t *ctx,
656                                                      va_list args) {
657   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
658   extra_cfg.frame_periodic_boost = CAST(VP9E_SET_FRAME_PERIODIC_BOOST, args);
659   return update_extra_cfg(ctx, &extra_cfg);
660 }
661
662 static vpx_codec_err_t encoder_init(vpx_codec_ctx_t *ctx,
663                                     vpx_codec_priv_enc_mr_cfg_t *data) {
664   vpx_codec_err_t res = VPX_CODEC_OK;
665   (void)data;
666
667   if (ctx->priv == NULL) {
668     vpx_codec_alg_priv_t *const priv = vpx_calloc(1, sizeof(*priv));
669     if (priv == NULL)
670       return VPX_CODEC_MEM_ERROR;
671
672     ctx->priv = (vpx_codec_priv_t *)priv;
673     ctx->priv->init_flags = ctx->init_flags;
674     ctx->priv->enc.total_encoders = 1;
675
676     if (ctx->config.enc) {
677       // Update the reference to the config structure to an internal copy.
678       priv->cfg = *ctx->config.enc;
679       ctx->config.enc = &priv->cfg;
680     }
681
682     priv->extra_cfg = default_extra_cfg;
683     vp9_initialize_enc();
684
685     res = validate_config(priv, &priv->cfg, &priv->extra_cfg);
686
687     if (res == VPX_CODEC_OK) {
688       set_encoder_config(&priv->oxcf, &priv->cfg, &priv->extra_cfg);
689       priv->cpi = vp9_create_compressor(&priv->oxcf);
690       if (priv->cpi == NULL)
691         res = VPX_CODEC_MEM_ERROR;
692       else
693         priv->cpi->output_pkt_list = &priv->pkt_list.head;
694     }
695   }
696
697   return res;
698 }
699
700 static vpx_codec_err_t encoder_destroy(vpx_codec_alg_priv_t *ctx) {
701   free(ctx->cx_data);
702   vp9_remove_compressor(ctx->cpi);
703   vpx_free(ctx);
704   return VPX_CODEC_OK;
705 }
706
707 static void pick_quickcompress_mode(vpx_codec_alg_priv_t *ctx,
708                                     unsigned long duration,
709                                     unsigned long deadline) {
710   MODE new_mode = BEST;
711
712   switch (ctx->cfg.g_pass) {
713     case VPX_RC_ONE_PASS:
714       if (deadline > 0) {
715         const vpx_codec_enc_cfg_t *const cfg = &ctx->cfg;
716
717         // Convert duration parameter from stream timebase to microseconds.
718         const uint64_t duration_us = (uint64_t)duration * 1000000 *
719            (uint64_t)cfg->g_timebase.num /(uint64_t)cfg->g_timebase.den;
720
721         // If the deadline is more that the duration this frame is to be shown,
722         // use good quality mode. Otherwise use realtime mode.
723         new_mode = (deadline > duration_us) ? GOOD : REALTIME;
724       } else {
725         new_mode = BEST;
726       }
727       break;
728     case VPX_RC_FIRST_PASS:
729       break;
730     case VPX_RC_LAST_PASS:
731       new_mode = deadline > 0 ? GOOD : BEST;
732       break;
733   }
734
735   if (ctx->oxcf.mode != new_mode) {
736     ctx->oxcf.mode = new_mode;
737     vp9_change_config(ctx->cpi, &ctx->oxcf);
738   }
739 }
740
741 // Turn on to test if supplemental superframe data breaks decoding
742 // #define TEST_SUPPLEMENTAL_SUPERFRAME_DATA
743 static int write_superframe_index(vpx_codec_alg_priv_t *ctx) {
744   uint8_t marker = 0xc0;
745   unsigned int mask;
746   int mag, index_sz;
747
748   assert(ctx->pending_frame_count);
749   assert(ctx->pending_frame_count <= 8);
750
751   // Add the number of frames to the marker byte
752   marker |= ctx->pending_frame_count - 1;
753
754   // Choose the magnitude
755   for (mag = 0, mask = 0xff; mag < 4; mag++) {
756     if (ctx->pending_frame_magnitude < mask)
757       break;
758     mask <<= 8;
759     mask |= 0xff;
760   }
761   marker |= mag << 3;
762
763   // Write the index
764   index_sz = 2 + (mag + 1) * ctx->pending_frame_count;
765   if (ctx->pending_cx_data_sz + index_sz < ctx->cx_data_sz) {
766     uint8_t *x = ctx->pending_cx_data + ctx->pending_cx_data_sz;
767     int i, j;
768 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
769     uint8_t marker_test = 0xc0;
770     int mag_test = 2;     // 1 - 4
771     int frames_test = 4;  // 1 - 8
772     int index_sz_test = 2 + mag_test * frames_test;
773     marker_test |= frames_test - 1;
774     marker_test |= (mag_test - 1) << 3;
775     *x++ = marker_test;
776     for (i = 0; i < mag_test * frames_test; ++i)
777       *x++ = 0;  // fill up with arbitrary data
778     *x++ = marker_test;
779     ctx->pending_cx_data_sz += index_sz_test;
780     printf("Added supplemental superframe data\n");
781 #endif
782
783     *x++ = marker;
784     for (i = 0; i < ctx->pending_frame_count; i++) {
785       unsigned int this_sz = (unsigned int)ctx->pending_frame_sizes[i];
786
787       for (j = 0; j <= mag; j++) {
788         *x++ = this_sz & 0xff;
789         this_sz >>= 8;
790       }
791     }
792     *x++ = marker;
793     ctx->pending_cx_data_sz += index_sz;
794 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
795     index_sz += index_sz_test;
796 #endif
797   }
798   return index_sz;
799 }
800
801 // vp9 uses 10,000,000 ticks/second as time stamp
802 #define TICKS_PER_SEC 10000000LL
803
804 static int64_t timebase_units_to_ticks(const vpx_rational_t *timebase,
805                                        int64_t n) {
806   return n * TICKS_PER_SEC * timebase->num / timebase->den;
807 }
808
809 static int64_t ticks_to_timebase_units(const vpx_rational_t *timebase,
810                                        int64_t n) {
811   const int64_t round = TICKS_PER_SEC * timebase->num / 2 - 1;
812   return (n * timebase->den + round) / timebase->num / TICKS_PER_SEC;
813 }
814
815 static vpx_codec_frame_flags_t get_frame_pkt_flags(const VP9_COMP *cpi,
816                                                    unsigned int lib_flags) {
817   vpx_codec_frame_flags_t flags = lib_flags << 16;
818
819   if (lib_flags & FRAMEFLAGS_KEY
820 #if CONFIG_SPATIAL_SVC
821       || (is_two_pass_svc(cpi) && cpi->svc.layer_context[0].is_key_frame)
822 #endif
823         )
824     flags |= VPX_FRAME_IS_KEY;
825
826   if (cpi->droppable)
827     flags |= VPX_FRAME_IS_DROPPABLE;
828
829   return flags;
830 }
831
832 static vpx_codec_err_t encoder_encode(vpx_codec_alg_priv_t  *ctx,
833                                       const vpx_image_t *img,
834                                       vpx_codec_pts_t pts,
835                                       unsigned long duration,
836                                       vpx_enc_frame_flags_t flags,
837                                       unsigned long deadline) {
838   vpx_codec_err_t res = VPX_CODEC_OK;
839   VP9_COMP *const cpi = ctx->cpi;
840   const vpx_rational_t *const timebase = &ctx->cfg.g_timebase;
841
842   if (img != NULL) {
843     res = validate_img(ctx, img);
844     // TODO(jzern) the checks related to cpi's validity should be treated as a
845     // failure condition, encoder setup is done fully in init() currently.
846     if (res == VPX_CODEC_OK && cpi != NULL && ctx->cx_data == NULL) {
847       // There's no codec control for multiple alt-refs so check the encoder
848       // instance for its status to determine the compressed data size.
849       ctx->cx_data_sz = ctx->cfg.g_w * ctx->cfg.g_h *
850                         get_image_bps(img) / 8 *
851                         (cpi->multi_arf_allowed ? 8 : 2);
852       if (ctx->cx_data_sz < 4096) ctx->cx_data_sz = 4096;
853
854       ctx->cx_data = (unsigned char *)malloc(ctx->cx_data_sz);
855       if (ctx->cx_data == NULL) {
856         return VPX_CODEC_MEM_ERROR;
857       }
858     }
859   }
860
861   pick_quickcompress_mode(ctx, duration, deadline);
862   vpx_codec_pkt_list_init(&ctx->pkt_list);
863
864   // Handle Flags
865   if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF)) ||
866        ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF))) {
867     ctx->base.err_detail = "Conflicting flags.";
868     return VPX_CODEC_INVALID_PARAM;
869   }
870
871   vp9_apply_encoding_flags(cpi, flags);
872
873   // Handle fixed keyframe intervals
874   if (ctx->cfg.kf_mode == VPX_KF_AUTO &&
875       ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
876     if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
877       flags |= VPX_EFLAG_FORCE_KF;
878       ctx->fixed_kf_cntr = 1;
879     }
880   }
881
882   // Initialize the encoder instance on the first frame.
883   if (res == VPX_CODEC_OK && cpi != NULL) {
884     unsigned int lib_flags = 0;
885     YV12_BUFFER_CONFIG sd;
886     int64_t dst_time_stamp = timebase_units_to_ticks(timebase, pts);
887     int64_t dst_end_time_stamp =
888         timebase_units_to_ticks(timebase, pts + duration);
889     size_t size, cx_data_sz;
890     unsigned char *cx_data;
891
892     // Set up internal flags
893     if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
894       cpi->b_calculate_psnr = 1;
895
896     if (img != NULL) {
897       res = image2yuvconfig(img, &sd);
898
899       // Store the original flags in to the frame buffer. Will extract the
900       // key frame flag when we actually encode this frame.
901       if (vp9_receive_raw_frame(cpi, flags,
902                                 &sd, dst_time_stamp, dst_end_time_stamp)) {
903         res = update_error_state(ctx, &cpi->common.error);
904       }
905     }
906
907     cx_data = ctx->cx_data;
908     cx_data_sz = ctx->cx_data_sz;
909
910     /* Any pending invisible frames? */
911     if (ctx->pending_cx_data) {
912       memmove(cx_data, ctx->pending_cx_data, ctx->pending_cx_data_sz);
913       ctx->pending_cx_data = cx_data;
914       cx_data += ctx->pending_cx_data_sz;
915       cx_data_sz -= ctx->pending_cx_data_sz;
916
917       /* TODO: this is a minimal check, the underlying codec doesn't respect
918        * the buffer size anyway.
919        */
920       if (cx_data_sz < ctx->cx_data_sz / 2) {
921         ctx->base.err_detail = "Compressed data buffer too small";
922         return VPX_CODEC_ERROR;
923       }
924     }
925
926     while (cx_data_sz >= ctx->cx_data_sz / 2 &&
927            -1 != vp9_get_compressed_data(cpi, &lib_flags, &size,
928                                          cx_data, &dst_time_stamp,
929                                          &dst_end_time_stamp, !img)) {
930       if (size) {
931         vpx_codec_cx_pkt_t pkt;
932
933 #if CONFIG_SPATIAL_SVC
934         if (is_two_pass_svc(cpi))
935           cpi->svc.layer_context[cpi->svc.spatial_layer_id].layer_size += size;
936 #endif
937
938         // Pack invisible frames with the next visible frame
939         if (!cpi->common.show_frame
940 #if CONFIG_SPATIAL_SVC
941             || (is_two_pass_svc(cpi) &&
942                 cpi->svc.spatial_layer_id < cpi->svc.number_spatial_layers - 1)
943 #endif
944             ) {
945           if (ctx->pending_cx_data == 0)
946             ctx->pending_cx_data = cx_data;
947           ctx->pending_cx_data_sz += size;
948           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
949           ctx->pending_frame_magnitude |= size;
950           cx_data += size;
951           cx_data_sz -= size;
952           continue;
953         }
954
955         // Add the frame packet to the list of returned packets.
956         pkt.kind = VPX_CODEC_CX_FRAME_PKT;
957         pkt.data.frame.pts = ticks_to_timebase_units(timebase, dst_time_stamp);
958         pkt.data.frame.duration =
959            (unsigned long)ticks_to_timebase_units(timebase,
960                dst_end_time_stamp - dst_time_stamp);
961         pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
962
963         if (ctx->pending_cx_data) {
964           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
965           ctx->pending_frame_magnitude |= size;
966           ctx->pending_cx_data_sz += size;
967           size += write_superframe_index(ctx);
968           pkt.data.frame.buf = ctx->pending_cx_data;
969           pkt.data.frame.sz  = ctx->pending_cx_data_sz;
970           ctx->pending_cx_data = NULL;
971           ctx->pending_cx_data_sz = 0;
972           ctx->pending_frame_count = 0;
973           ctx->pending_frame_magnitude = 0;
974         } else {
975           pkt.data.frame.buf = cx_data;
976           pkt.data.frame.sz  = size;
977         }
978         pkt.data.frame.partition_id = -1;
979         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
980         cx_data += size;
981         cx_data_sz -= size;
982 #if CONFIG_SPATIAL_SVC
983         if (is_two_pass_svc(cpi)) {
984           vpx_codec_cx_pkt_t pkt;
985           int i;
986           vp9_zero(pkt);
987           pkt.kind = VPX_CODEC_SPATIAL_SVC_LAYER_SIZES;
988           for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
989             pkt.data.layer_sizes[i] = cpi->svc.layer_context[i].layer_size;
990             cpi->svc.layer_context[i].layer_size = 0;
991           }
992           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
993         }
994 #endif
995       }
996     }
997   }
998
999   return res;
1000 }
1001
1002 static const vpx_codec_cx_pkt_t *encoder_get_cxdata(vpx_codec_alg_priv_t *ctx,
1003                                                     vpx_codec_iter_t *iter) {
1004   return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
1005 }
1006
1007 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
1008                                           va_list args) {
1009   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1010
1011   if (frame != NULL) {
1012     YV12_BUFFER_CONFIG sd;
1013
1014     image2yuvconfig(&frame->img, &sd);
1015     vp9_set_reference_enc(ctx->cpi, ref_frame_to_vp9_reframe(frame->frame_type),
1016                           &sd);
1017     return VPX_CODEC_OK;
1018   } else {
1019     return VPX_CODEC_INVALID_PARAM;
1020   }
1021 }
1022
1023 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
1024                                            va_list args) {
1025   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1026
1027   if (frame != NULL) {
1028     YV12_BUFFER_CONFIG sd;
1029
1030     image2yuvconfig(&frame->img, &sd);
1031     vp9_copy_reference_enc(ctx->cpi,
1032                            ref_frame_to_vp9_reframe(frame->frame_type), &sd);
1033     return VPX_CODEC_OK;
1034   } else {
1035     return VPX_CODEC_INVALID_PARAM;
1036   }
1037 }
1038
1039 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
1040                                           va_list args) {
1041   vp9_ref_frame_t *const frame = va_arg(args, vp9_ref_frame_t *);
1042
1043   if (frame != NULL) {
1044     YV12_BUFFER_CONFIG *fb = get_ref_frame(&ctx->cpi->common, frame->idx);
1045     if (fb == NULL) return VPX_CODEC_ERROR;
1046
1047     yuvconfig2image(&frame->img, fb, NULL);
1048     return VPX_CODEC_OK;
1049   } else {
1050     return VPX_CODEC_INVALID_PARAM;
1051   }
1052 }
1053
1054 static vpx_codec_err_t ctrl_set_previewpp(vpx_codec_alg_priv_t *ctx,
1055                                           va_list args) {
1056 #if CONFIG_VP9_POSTPROC
1057   vp8_postproc_cfg_t *config = va_arg(args, vp8_postproc_cfg_t *);
1058   if (config != NULL) {
1059     ctx->preview_ppcfg = *config;
1060     return VPX_CODEC_OK;
1061   } else {
1062     return VPX_CODEC_INVALID_PARAM;
1063   }
1064 #else
1065   (void)ctx;
1066   (void)args;
1067   return VPX_CODEC_INCAPABLE;
1068 #endif
1069 }
1070
1071
1072 static vpx_image_t *encoder_get_preview(vpx_codec_alg_priv_t *ctx) {
1073   YV12_BUFFER_CONFIG sd;
1074   vp9_ppflags_t flags;
1075   vp9_zero(flags);
1076
1077   if (ctx->preview_ppcfg.post_proc_flag) {
1078     flags.post_proc_flag   = ctx->preview_ppcfg.post_proc_flag;
1079     flags.deblocking_level = ctx->preview_ppcfg.deblocking_level;
1080     flags.noise_level      = ctx->preview_ppcfg.noise_level;
1081   }
1082
1083   if (vp9_get_preview_raw_frame(ctx->cpi, &sd, &flags) == 0) {
1084     yuvconfig2image(&ctx->preview_img, &sd, NULL);
1085     return &ctx->preview_img;
1086   } else {
1087     return NULL;
1088   }
1089 }
1090
1091 static vpx_codec_err_t ctrl_update_entropy(vpx_codec_alg_priv_t *ctx,
1092                                            va_list args) {
1093   const int update = va_arg(args, int);
1094
1095   vp9_update_entropy(ctx->cpi, update);
1096   return VPX_CODEC_OK;
1097 }
1098
1099 static vpx_codec_err_t ctrl_update_reference(vpx_codec_alg_priv_t *ctx,
1100                                              va_list args) {
1101   const int ref_frame_flags = va_arg(args, int);
1102
1103   vp9_update_reference(ctx->cpi, ref_frame_flags);
1104   return VPX_CODEC_OK;
1105 }
1106
1107 static vpx_codec_err_t ctrl_use_reference(vpx_codec_alg_priv_t *ctx,
1108                                           va_list args) {
1109   const int reference_flag = va_arg(args, int);
1110
1111   vp9_use_as_reference(ctx->cpi, reference_flag);
1112   return VPX_CODEC_OK;
1113 }
1114
1115 static vpx_codec_err_t ctrl_set_roi_map(vpx_codec_alg_priv_t *ctx,
1116                                         va_list args) {
1117   (void)ctx;
1118   (void)args;
1119
1120   // TODO(yaowu): Need to re-implement and test for VP9.
1121   return VPX_CODEC_INVALID_PARAM;
1122 }
1123
1124
1125 static vpx_codec_err_t ctrl_set_active_map(vpx_codec_alg_priv_t *ctx,
1126                                            va_list args) {
1127   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
1128
1129   if (map) {
1130     if (!vp9_set_active_map(ctx->cpi, map->active_map,
1131                             (int)map->rows, (int)map->cols))
1132       return VPX_CODEC_OK;
1133     else
1134       return VPX_CODEC_INVALID_PARAM;
1135   } else {
1136     return VPX_CODEC_INVALID_PARAM;
1137   }
1138 }
1139
1140 static vpx_codec_err_t ctrl_set_scale_mode(vpx_codec_alg_priv_t *ctx,
1141                                            va_list args) {
1142   vpx_scaling_mode_t *const mode = va_arg(args, vpx_scaling_mode_t *);
1143
1144   if (mode) {
1145     const int res = vp9_set_internal_size(ctx->cpi,
1146                                           (VPX_SCALING)mode->h_scaling_mode,
1147                                           (VPX_SCALING)mode->v_scaling_mode);
1148     return (res == 0) ? VPX_CODEC_OK : VPX_CODEC_INVALID_PARAM;
1149   } else {
1150     return VPX_CODEC_INVALID_PARAM;
1151   }
1152 }
1153
1154 static vpx_codec_err_t ctrl_set_svc(vpx_codec_alg_priv_t *ctx, va_list args) {
1155   int data = va_arg(args, int);
1156   const vpx_codec_enc_cfg_t *cfg = &ctx->cfg;
1157
1158   vp9_set_svc(ctx->cpi, data);
1159   // CBR or two pass mode for SVC with both temporal and spatial layers
1160   // not yet supported.
1161   if (data == 1 &&
1162       (cfg->rc_end_usage == VPX_CBR ||
1163        cfg->g_pass == VPX_RC_FIRST_PASS ||
1164        cfg->g_pass == VPX_RC_LAST_PASS) &&
1165       cfg->ss_number_layers > 1 &&
1166       cfg->ts_number_layers > 1) {
1167     return VPX_CODEC_INVALID_PARAM;
1168   }
1169   return VPX_CODEC_OK;
1170 }
1171
1172 static vpx_codec_err_t ctrl_set_svc_layer_id(vpx_codec_alg_priv_t *ctx,
1173                                              va_list args) {
1174   vpx_svc_layer_id_t *const data = va_arg(args, vpx_svc_layer_id_t *);
1175   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
1176   SVC *const svc = &cpi->svc;
1177
1178   svc->spatial_layer_id = data->spatial_layer_id;
1179   svc->temporal_layer_id = data->temporal_layer_id;
1180   // Checks on valid layer_id input.
1181   if (svc->temporal_layer_id < 0 ||
1182       svc->temporal_layer_id >= (int)ctx->cfg.ts_number_layers) {
1183     return VPX_CODEC_INVALID_PARAM;
1184   }
1185   if (svc->spatial_layer_id < 0 ||
1186       svc->spatial_layer_id >= (int)ctx->cfg.ss_number_layers) {
1187     return VPX_CODEC_INVALID_PARAM;
1188   }
1189   return VPX_CODEC_OK;
1190 }
1191
1192 static vpx_codec_err_t ctrl_set_svc_parameters(vpx_codec_alg_priv_t *ctx,
1193                                                va_list args) {
1194   VP9_COMP *const cpi = ctx->cpi;
1195   vpx_svc_parameters_t *const params = va_arg(args, vpx_svc_parameters_t *);
1196
1197   if (params == NULL || params->spatial_layer < 0 ||
1198       params->spatial_layer >= cpi->svc.number_spatial_layers)
1199     return VPX_CODEC_INVALID_PARAM;
1200
1201   if (params->spatial_layer == 0) {
1202     int i;
1203     for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
1204       cpi->svc.layer_context[i].svc_params_received.spatial_layer = -1;
1205     }
1206   }
1207
1208   cpi->svc.layer_context[params->spatial_layer].svc_params_received =
1209       *params;
1210
1211   return VPX_CODEC_OK;
1212 }
1213
1214 static vpx_codec_err_t ctrl_set_tune_content(vpx_codec_alg_priv_t *ctx,
1215                                              va_list args) {
1216   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1217   extra_cfg.content = CAST(VP9E_SET_TUNE_CONTENT, args);
1218   return update_extra_cfg(ctx, &extra_cfg);
1219 }
1220
1221 static vpx_codec_ctrl_fn_map_t encoder_ctrl_maps[] = {
1222   {VP8_COPY_REFERENCE,                ctrl_copy_reference},
1223   {VP8E_UPD_ENTROPY,                  ctrl_update_entropy},
1224   {VP8E_UPD_REFERENCE,                ctrl_update_reference},
1225   {VP8E_USE_REFERENCE,                ctrl_use_reference},
1226
1227   // Setters
1228   {VP8_SET_REFERENCE,                 ctrl_set_reference},
1229   {VP8_SET_POSTPROC,                  ctrl_set_previewpp},
1230   {VP8E_SET_ROI_MAP,                  ctrl_set_roi_map},
1231   {VP8E_SET_ACTIVEMAP,                ctrl_set_active_map},
1232   {VP8E_SET_SCALEMODE,                ctrl_set_scale_mode},
1233   {VP8E_SET_CPUUSED,                  ctrl_set_cpuused},
1234   {VP8E_SET_NOISE_SENSITIVITY,        ctrl_set_noise_sensitivity},
1235   {VP8E_SET_ENABLEAUTOALTREF,         ctrl_set_enable_auto_alt_ref},
1236   {VP8E_SET_SHARPNESS,                ctrl_set_sharpness},
1237   {VP8E_SET_STATIC_THRESHOLD,         ctrl_set_static_thresh},
1238   {VP9E_SET_TILE_COLUMNS,             ctrl_set_tile_columns},
1239   {VP9E_SET_TILE_ROWS,                ctrl_set_tile_rows},
1240   {VP8E_SET_ARNR_MAXFRAMES,           ctrl_set_arnr_max_frames},
1241   {VP8E_SET_ARNR_STRENGTH,            ctrl_set_arnr_strength},
1242   {VP8E_SET_ARNR_TYPE,                ctrl_set_arnr_type},
1243   {VP8E_SET_TUNING,                   ctrl_set_tuning},
1244   {VP8E_SET_CQ_LEVEL,                 ctrl_set_cq_level},
1245   {VP8E_SET_MAX_INTRA_BITRATE_PCT,    ctrl_set_rc_max_intra_bitrate_pct},
1246   {VP9E_SET_LOSSLESS,                 ctrl_set_lossless},
1247   {VP9E_SET_FRAME_PARALLEL_DECODING,  ctrl_set_frame_parallel_decoding_mode},
1248   {VP9E_SET_AQ_MODE,                  ctrl_set_aq_mode},
1249   {VP9E_SET_FRAME_PERIODIC_BOOST,     ctrl_set_frame_periodic_boost},
1250   {VP9E_SET_SVC,                      ctrl_set_svc},
1251   {VP9E_SET_SVC_PARAMETERS,           ctrl_set_svc_parameters},
1252   {VP9E_SET_SVC_LAYER_ID,             ctrl_set_svc_layer_id},
1253   {VP9E_SET_TUNE_CONTENT,             ctrl_set_tune_content},
1254
1255   // Getters
1256   {VP8E_GET_LAST_QUANTIZER,           ctrl_get_quantizer},
1257   {VP8E_GET_LAST_QUANTIZER_64,        ctrl_get_quantizer64},
1258   {VP9_GET_REFERENCE,                 ctrl_get_reference},
1259
1260   { -1, NULL},
1261 };
1262
1263 static vpx_codec_enc_cfg_map_t encoder_usage_cfg_map[] = {
1264   {
1265     0,
1266     {  // NOLINT
1267       0,                  // g_usage
1268       0,                  // g_threads
1269       0,                  // g_profile
1270
1271       320,                // g_width
1272       240,                // g_height
1273       VPX_BITS_8,         // g_bit_depth
1274       8,                  // g_input_bit_depth
1275
1276       {1, 30},            // g_timebase
1277
1278       0,                  // g_error_resilient
1279
1280       VPX_RC_ONE_PASS,    // g_pass
1281
1282       25,                 // g_lag_in_frames
1283
1284       0,                  // rc_dropframe_thresh
1285       0,                  // rc_resize_allowed
1286       1,                  // rc_scaled_width
1287       1,                  // rc_scaled_height
1288       60,                 // rc_resize_down_thresold
1289       30,                 // rc_resize_up_thresold
1290
1291       VPX_VBR,            // rc_end_usage
1292 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1293       {NULL, 0},          // rc_twopass_stats_in
1294       {NULL, 0},          // rc_firstpass_mb_stats_in
1295 #endif
1296       256,                // rc_target_bandwidth
1297       0,                  // rc_min_quantizer
1298       63,                 // rc_max_quantizer
1299       100,                // rc_undershoot_pct
1300       100,                // rc_overshoot_pct
1301
1302       6000,               // rc_max_buffer_size
1303       4000,               // rc_buffer_initial_size
1304       5000,               // rc_buffer_optimal_size
1305
1306       50,                 // rc_two_pass_vbrbias
1307       0,                  // rc_two_pass_vbrmin_section
1308       2000,               // rc_two_pass_vbrmax_section
1309
1310       // keyframing settings (kf)
1311       VPX_KF_AUTO,        // g_kfmode
1312       0,                  // kf_min_dist
1313       9999,               // kf_max_dist
1314
1315       VPX_SS_DEFAULT_LAYERS,  // ss_number_layers
1316       {0},
1317       {0},                    // ss_target_bitrate
1318       1,                      // ts_number_layers
1319       {0},                    // ts_target_bitrate
1320       {0},                    // ts_rate_decimator
1321       0,                      // ts_periodicity
1322       {0},                    // ts_layer_id
1323 #if VPX_ENCODER_ABI_VERSION == (1 + VPX_CODEC_ABI_VERSION)
1324       "vp8.fpf"           // first pass filename
1325 #endif
1326     }
1327   },
1328 };
1329
1330 #ifndef VERSION_STRING
1331 #define VERSION_STRING
1332 #endif
1333 CODEC_INTERFACE(vpx_codec_vp9_cx) = {
1334   "WebM Project VP9 Encoder" VERSION_STRING,
1335   VPX_CODEC_INTERNAL_ABI_VERSION,
1336   VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR,  // vpx_codec_caps_t
1337   encoder_init,       // vpx_codec_init_fn_t
1338   encoder_destroy,    // vpx_codec_destroy_fn_t
1339   encoder_ctrl_maps,  // vpx_codec_ctrl_fn_map_t
1340   {  // NOLINT
1341     NULL,  // vpx_codec_peek_si_fn_t
1342     NULL,  // vpx_codec_get_si_fn_t
1343     NULL,  // vpx_codec_decode_fn_t
1344     NULL,  // vpx_codec_frame_get_fn_t
1345     NULL   // vpx_codec_set_fb_fn_t
1346   },
1347   {  // NOLINT
1348     1,                      // 1 cfg map
1349     encoder_usage_cfg_map,  // vpx_codec_enc_cfg_map_t
1350     encoder_encode,         // vpx_codec_encode_fn_t
1351     encoder_get_cxdata,     // vpx_codec_get_cx_data_fn_t
1352     encoder_set_config,     // vpx_codec_enc_config_set_fn_t
1353     NULL,        // vpx_codec_get_global_headers_fn_t
1354     encoder_get_preview,    // vpx_codec_get_preview_frame_fn_t
1355     NULL         // vpx_codec_enc_mr_get_mem_loc_fn_t
1356   }
1357 };