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