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