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