Merge "Fix external resize memory issues."
[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(VP9E_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   size_t data_sz;
928
929   if (img != NULL) {
930     res = validate_img(ctx, img);
931     // TODO(jzern) the checks related to cpi's validity should be treated as a
932     // failure condition, encoder setup is done fully in init() currently.
933     if (res == VPX_CODEC_OK && cpi != NULL) {
934       // There's no codec control for multiple alt-refs so check the encoder
935       // instance for its status to determine the compressed data size.
936       data_sz = ctx->cfg.g_w * ctx->cfg.g_h * get_image_bps(img) / 8 *
937                 (cpi->multi_arf_allowed ? 8 : 2);
938       if (data_sz < 4096)
939         data_sz = 4096;
940       if (ctx->cx_data == NULL || ctx->cx_data_sz < data_sz) {
941         ctx->cx_data_sz = data_sz;
942         free(ctx->cx_data);
943         ctx->cx_data = (unsigned char*)malloc(ctx->cx_data_sz);
944         if (ctx->cx_data == NULL) {
945           return VPX_CODEC_MEM_ERROR;
946         }
947       }
948     }
949   }
950
951   pick_quickcompress_mode(ctx, duration, deadline);
952   vpx_codec_pkt_list_init(&ctx->pkt_list);
953
954   // Handle Flags
955   if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF)) ||
956        ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF))) {
957     ctx->base.err_detail = "Conflicting flags.";
958     return VPX_CODEC_INVALID_PARAM;
959   }
960
961   vp9_apply_encoding_flags(cpi, flags);
962
963   // Handle fixed keyframe intervals
964   if (ctx->cfg.kf_mode == VPX_KF_AUTO &&
965       ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
966     if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
967       flags |= VPX_EFLAG_FORCE_KF;
968       ctx->fixed_kf_cntr = 1;
969     }
970   }
971
972   // Initialize the encoder instance on the first frame.
973   if (res == VPX_CODEC_OK && cpi != NULL) {
974     unsigned int lib_flags = 0;
975     YV12_BUFFER_CONFIG sd;
976     int64_t dst_time_stamp = timebase_units_to_ticks(timebase, pts);
977     int64_t dst_end_time_stamp =
978         timebase_units_to_ticks(timebase, pts + duration);
979     size_t size, cx_data_sz;
980     unsigned char *cx_data;
981
982     // Set up internal flags
983     if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
984       cpi->b_calculate_psnr = 1;
985
986     if (img != NULL) {
987       res = image2yuvconfig(img, &sd);
988
989       // Store the original flags in to the frame buffer. Will extract the
990       // key frame flag when we actually encode this frame.
991       if (vp9_receive_raw_frame(cpi, flags | ctx->next_frame_flags,
992                                 &sd, dst_time_stamp, dst_end_time_stamp)) {
993         res = update_error_state(ctx, &cpi->common.error);
994       }
995       ctx->next_frame_flags = 0;
996     }
997
998     cx_data = ctx->cx_data;
999     cx_data_sz = ctx->cx_data_sz;
1000
1001     /* Any pending invisible frames? */
1002     if (ctx->pending_cx_data) {
1003       memmove(cx_data, ctx->pending_cx_data, ctx->pending_cx_data_sz);
1004       ctx->pending_cx_data = cx_data;
1005       cx_data += ctx->pending_cx_data_sz;
1006       cx_data_sz -= ctx->pending_cx_data_sz;
1007
1008       /* TODO: this is a minimal check, the underlying codec doesn't respect
1009        * the buffer size anyway.
1010        */
1011       if (cx_data_sz < ctx->cx_data_sz / 2) {
1012         ctx->base.err_detail = "Compressed data buffer too small";
1013         return VPX_CODEC_ERROR;
1014       }
1015     }
1016
1017     while (cx_data_sz >= ctx->cx_data_sz / 2 &&
1018            -1 != vp9_get_compressed_data(cpi, &lib_flags, &size,
1019                                          cx_data, &dst_time_stamp,
1020                                          &dst_end_time_stamp, !img)) {
1021       if (size) {
1022         vpx_codec_cx_pkt_t pkt;
1023
1024 #if CONFIG_SPATIAL_SVC
1025         if (is_two_pass_svc(cpi))
1026           cpi->svc.layer_context[cpi->svc.spatial_layer_id].layer_size += size;
1027 #endif
1028
1029         // Pack invisible frames with the next visible frame
1030         if (!cpi->common.show_frame
1031 #if CONFIG_SPATIAL_SVC
1032             || (is_two_pass_svc(cpi) &&
1033                 cpi->svc.spatial_layer_id < cpi->svc.number_spatial_layers - 1)
1034 #endif
1035             ) {
1036           if (ctx->pending_cx_data == 0)
1037             ctx->pending_cx_data = cx_data;
1038           ctx->pending_cx_data_sz += size;
1039           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
1040           ctx->pending_frame_magnitude |= size;
1041           cx_data += size;
1042           cx_data_sz -= size;
1043
1044           if (ctx->output_cx_pkt_cb.output_cx_pkt) {
1045             pkt.kind = VPX_CODEC_CX_FRAME_PKT;
1046             pkt.data.frame.pts = ticks_to_timebase_units(timebase,
1047                                                          dst_time_stamp);
1048             pkt.data.frame.duration =
1049                (unsigned long)ticks_to_timebase_units(timebase,
1050                    dst_end_time_stamp - dst_time_stamp);
1051             pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
1052             pkt.data.frame.buf = ctx->pending_cx_data;
1053             pkt.data.frame.sz  = size;
1054             ctx->pending_cx_data = NULL;
1055             ctx->pending_cx_data_sz = 0;
1056             ctx->pending_frame_count = 0;
1057             ctx->pending_frame_magnitude = 0;
1058             ctx->output_cx_pkt_cb.output_cx_pkt(
1059                 &pkt, ctx->output_cx_pkt_cb.user_priv);
1060           }
1061           continue;
1062         }
1063
1064         // Add the frame packet to the list of returned packets.
1065         pkt.kind = VPX_CODEC_CX_FRAME_PKT;
1066         pkt.data.frame.pts = ticks_to_timebase_units(timebase, dst_time_stamp);
1067         pkt.data.frame.duration =
1068            (unsigned long)ticks_to_timebase_units(timebase,
1069                dst_end_time_stamp - dst_time_stamp);
1070         pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
1071
1072         if (ctx->pending_cx_data) {
1073           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
1074           ctx->pending_frame_magnitude |= size;
1075           ctx->pending_cx_data_sz += size;
1076           // write the superframe only for the case when
1077           if (!ctx->output_cx_pkt_cb.output_cx_pkt)
1078             size += write_superframe_index(ctx);
1079           pkt.data.frame.buf = ctx->pending_cx_data;
1080           pkt.data.frame.sz  = ctx->pending_cx_data_sz;
1081           ctx->pending_cx_data = NULL;
1082           ctx->pending_cx_data_sz = 0;
1083           ctx->pending_frame_count = 0;
1084           ctx->pending_frame_magnitude = 0;
1085         } else {
1086           pkt.data.frame.buf = cx_data;
1087           pkt.data.frame.sz  = size;
1088         }
1089         pkt.data.frame.partition_id = -1;
1090
1091         if(ctx->output_cx_pkt_cb.output_cx_pkt)
1092           ctx->output_cx_pkt_cb.output_cx_pkt(&pkt, ctx->output_cx_pkt_cb.user_priv);
1093         else
1094           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1095
1096         cx_data += size;
1097         cx_data_sz -= size;
1098 #if CONFIG_SPATIAL_SVC
1099         if (is_two_pass_svc(cpi) && !ctx->output_cx_pkt_cb.output_cx_pkt) {
1100           vpx_codec_cx_pkt_t pkt_sizes, pkt_psnr;
1101           int i;
1102           vp9_zero(pkt_sizes);
1103           vp9_zero(pkt_psnr);
1104           pkt_sizes.kind = VPX_CODEC_SPATIAL_SVC_LAYER_SIZES;
1105           pkt_psnr.kind = VPX_CODEC_SPATIAL_SVC_LAYER_PSNR;
1106           for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
1107             LAYER_CONTEXT *lc = &cpi->svc.layer_context[i];
1108             pkt_sizes.data.layer_sizes[i] = lc->layer_size;
1109             pkt_psnr.data.layer_psnr[i] = lc->psnr_pkt;
1110             lc->layer_size = 0;
1111           }
1112
1113           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt_sizes);
1114
1115           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt_psnr);
1116         }
1117 #endif
1118       }
1119     }
1120   }
1121
1122   return res;
1123 }
1124
1125 static const vpx_codec_cx_pkt_t *encoder_get_cxdata(vpx_codec_alg_priv_t *ctx,
1126                                                     vpx_codec_iter_t *iter) {
1127   return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
1128 }
1129
1130 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
1131                                           va_list args) {
1132   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1133
1134   if (frame != NULL) {
1135     YV12_BUFFER_CONFIG sd;
1136
1137     image2yuvconfig(&frame->img, &sd);
1138     vp9_set_reference_enc(ctx->cpi, ref_frame_to_vp9_reframe(frame->frame_type),
1139                           &sd);
1140     return VPX_CODEC_OK;
1141   } else {
1142     return VPX_CODEC_INVALID_PARAM;
1143   }
1144 }
1145
1146 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
1147                                            va_list args) {
1148   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1149
1150   if (frame != NULL) {
1151     YV12_BUFFER_CONFIG sd;
1152
1153     image2yuvconfig(&frame->img, &sd);
1154     vp9_copy_reference_enc(ctx->cpi,
1155                            ref_frame_to_vp9_reframe(frame->frame_type), &sd);
1156     return VPX_CODEC_OK;
1157   } else {
1158     return VPX_CODEC_INVALID_PARAM;
1159   }
1160 }
1161
1162 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
1163                                           va_list args) {
1164   vp9_ref_frame_t *const frame = va_arg(args, vp9_ref_frame_t *);
1165
1166   if (frame != NULL) {
1167     YV12_BUFFER_CONFIG *fb = get_ref_frame(&ctx->cpi->common, frame->idx);
1168     if (fb == NULL) return VPX_CODEC_ERROR;
1169
1170     yuvconfig2image(&frame->img, fb, NULL);
1171     return VPX_CODEC_OK;
1172   } else {
1173     return VPX_CODEC_INVALID_PARAM;
1174   }
1175 }
1176
1177 static vpx_codec_err_t ctrl_set_previewpp(vpx_codec_alg_priv_t *ctx,
1178                                           va_list args) {
1179 #if CONFIG_VP9_POSTPROC
1180   vp8_postproc_cfg_t *config = va_arg(args, vp8_postproc_cfg_t *);
1181   if (config != NULL) {
1182     ctx->preview_ppcfg = *config;
1183     return VPX_CODEC_OK;
1184   } else {
1185     return VPX_CODEC_INVALID_PARAM;
1186   }
1187 #else
1188   (void)ctx;
1189   (void)args;
1190   return VPX_CODEC_INCAPABLE;
1191 #endif
1192 }
1193
1194
1195 static vpx_image_t *encoder_get_preview(vpx_codec_alg_priv_t *ctx) {
1196   YV12_BUFFER_CONFIG sd;
1197   vp9_ppflags_t flags;
1198   vp9_zero(flags);
1199
1200   if (ctx->preview_ppcfg.post_proc_flag) {
1201     flags.post_proc_flag   = ctx->preview_ppcfg.post_proc_flag;
1202     flags.deblocking_level = ctx->preview_ppcfg.deblocking_level;
1203     flags.noise_level      = ctx->preview_ppcfg.noise_level;
1204   }
1205
1206   if (vp9_get_preview_raw_frame(ctx->cpi, &sd, &flags) == 0) {
1207     yuvconfig2image(&ctx->preview_img, &sd, NULL);
1208     return &ctx->preview_img;
1209   } else {
1210     return NULL;
1211   }
1212 }
1213
1214 static vpx_codec_err_t ctrl_update_entropy(vpx_codec_alg_priv_t *ctx,
1215                                            va_list args) {
1216   const int update = va_arg(args, int);
1217
1218   vp9_update_entropy(ctx->cpi, update);
1219   return VPX_CODEC_OK;
1220 }
1221
1222 static vpx_codec_err_t ctrl_update_reference(vpx_codec_alg_priv_t *ctx,
1223                                              va_list args) {
1224   const int ref_frame_flags = va_arg(args, int);
1225
1226   vp9_update_reference(ctx->cpi, ref_frame_flags);
1227   return VPX_CODEC_OK;
1228 }
1229
1230 static vpx_codec_err_t ctrl_use_reference(vpx_codec_alg_priv_t *ctx,
1231                                           va_list args) {
1232   const int reference_flag = va_arg(args, int);
1233
1234   vp9_use_as_reference(ctx->cpi, reference_flag);
1235   return VPX_CODEC_OK;
1236 }
1237
1238 static vpx_codec_err_t ctrl_set_roi_map(vpx_codec_alg_priv_t *ctx,
1239                                         va_list args) {
1240   (void)ctx;
1241   (void)args;
1242
1243   // TODO(yaowu): Need to re-implement and test for VP9.
1244   return VPX_CODEC_INVALID_PARAM;
1245 }
1246
1247
1248 static vpx_codec_err_t ctrl_set_active_map(vpx_codec_alg_priv_t *ctx,
1249                                            va_list args) {
1250   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
1251
1252   if (map) {
1253     if (!vp9_set_active_map(ctx->cpi, map->active_map,
1254                             (int)map->rows, (int)map->cols))
1255       return VPX_CODEC_OK;
1256     else
1257       return VPX_CODEC_INVALID_PARAM;
1258   } else {
1259     return VPX_CODEC_INVALID_PARAM;
1260   }
1261 }
1262
1263 static vpx_codec_err_t ctrl_set_scale_mode(vpx_codec_alg_priv_t *ctx,
1264                                            va_list args) {
1265   vpx_scaling_mode_t *const mode = va_arg(args, vpx_scaling_mode_t *);
1266
1267   if (mode) {
1268     const int res = vp9_set_internal_size(ctx->cpi,
1269                                           (VPX_SCALING)mode->h_scaling_mode,
1270                                           (VPX_SCALING)mode->v_scaling_mode);
1271     return (res == 0) ? VPX_CODEC_OK : VPX_CODEC_INVALID_PARAM;
1272   } else {
1273     return VPX_CODEC_INVALID_PARAM;
1274   }
1275 }
1276
1277 static vpx_codec_err_t ctrl_set_svc(vpx_codec_alg_priv_t *ctx, va_list args) {
1278   int data = va_arg(args, int);
1279   const vpx_codec_enc_cfg_t *cfg = &ctx->cfg;
1280
1281   vp9_set_svc(ctx->cpi, data);
1282   // CBR or two pass mode for SVC with both temporal and spatial layers
1283   // not yet supported.
1284   if (data == 1 &&
1285       (cfg->rc_end_usage == VPX_CBR ||
1286        cfg->g_pass == VPX_RC_FIRST_PASS ||
1287        cfg->g_pass == VPX_RC_LAST_PASS) &&
1288       cfg->ss_number_layers > 1 &&
1289       cfg->ts_number_layers > 1) {
1290     return VPX_CODEC_INVALID_PARAM;
1291   }
1292   return VPX_CODEC_OK;
1293 }
1294
1295 static vpx_codec_err_t ctrl_set_svc_layer_id(vpx_codec_alg_priv_t *ctx,
1296                                              va_list args) {
1297   vpx_svc_layer_id_t *const data = va_arg(args, vpx_svc_layer_id_t *);
1298   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
1299   SVC *const svc = &cpi->svc;
1300
1301   svc->spatial_layer_id = data->spatial_layer_id;
1302   svc->temporal_layer_id = data->temporal_layer_id;
1303   // Checks on valid layer_id input.
1304   if (svc->temporal_layer_id < 0 ||
1305       svc->temporal_layer_id >= (int)ctx->cfg.ts_number_layers) {
1306     return VPX_CODEC_INVALID_PARAM;
1307   }
1308   if (svc->spatial_layer_id < 0 ||
1309       svc->spatial_layer_id >= (int)ctx->cfg.ss_number_layers) {
1310     return VPX_CODEC_INVALID_PARAM;
1311   }
1312   return VPX_CODEC_OK;
1313 }
1314
1315 static vpx_codec_err_t ctrl_get_svc_layer_id(vpx_codec_alg_priv_t *ctx,
1316                                              va_list args) {
1317   vpx_svc_layer_id_t *data = va_arg(args, vpx_svc_layer_id_t *);
1318   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
1319   SVC *const svc = &cpi->svc;
1320
1321   data->spatial_layer_id = svc->spatial_layer_id;
1322   data->temporal_layer_id = svc->temporal_layer_id;
1323
1324   return VPX_CODEC_OK;
1325 }
1326
1327 static vpx_codec_err_t ctrl_set_svc_parameters(vpx_codec_alg_priv_t *ctx,
1328                                                va_list args) {
1329   VP9_COMP *const cpi = ctx->cpi;
1330   vpx_svc_extra_cfg_t *const params = va_arg(args, vpx_svc_extra_cfg_t *);
1331   int i;
1332
1333   for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
1334     LAYER_CONTEXT *lc = &cpi->svc.layer_context[i];
1335
1336     lc->max_q = params->max_quantizers[i];
1337     lc->min_q = params->min_quantizers[i];
1338     lc->scaling_factor_num = params->scaling_factor_num[i];
1339     lc->scaling_factor_den = params->scaling_factor_den[i];
1340   }
1341
1342   return VPX_CODEC_OK;
1343 }
1344
1345 static vpx_codec_err_t ctrl_register_cx_callback(vpx_codec_alg_priv_t *ctx,
1346                                                  va_list args) {
1347   vpx_codec_priv_output_cx_pkt_cb_pair_t *cbp =
1348       (vpx_codec_priv_output_cx_pkt_cb_pair_t *)va_arg(args, void *);
1349   ctx->output_cx_pkt_cb.output_cx_pkt = cbp->output_cx_pkt;
1350   ctx->output_cx_pkt_cb.user_priv = cbp->user_priv;
1351
1352   return VPX_CODEC_OK;
1353 }
1354
1355 static vpx_codec_err_t ctrl_set_tune_content(vpx_codec_alg_priv_t *ctx,
1356                                              va_list args) {
1357   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1358   extra_cfg.content = CAST(VP9E_SET_TUNE_CONTENT, args);
1359   return update_extra_cfg(ctx, &extra_cfg);
1360 }
1361
1362 static vpx_codec_err_t ctrl_set_color_space(vpx_codec_alg_priv_t *ctx,
1363                                             va_list args) {
1364   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1365   extra_cfg.color_space = CAST(VP9E_SET_COLOR_SPACE, args);
1366   return update_extra_cfg(ctx, &extra_cfg);
1367 }
1368
1369 static vpx_codec_ctrl_fn_map_t encoder_ctrl_maps[] = {
1370   {VP8_COPY_REFERENCE,                ctrl_copy_reference},
1371   {VP8E_UPD_ENTROPY,                  ctrl_update_entropy},
1372   {VP8E_UPD_REFERENCE,                ctrl_update_reference},
1373   {VP8E_USE_REFERENCE,                ctrl_use_reference},
1374
1375   // Setters
1376   {VP8_SET_REFERENCE,                 ctrl_set_reference},
1377   {VP8_SET_POSTPROC,                  ctrl_set_previewpp},
1378   {VP8E_SET_ROI_MAP,                  ctrl_set_roi_map},
1379   {VP8E_SET_ACTIVEMAP,                ctrl_set_active_map},
1380   {VP8E_SET_SCALEMODE,                ctrl_set_scale_mode},
1381   {VP8E_SET_CPUUSED,                  ctrl_set_cpuused},
1382   {VP8E_SET_ENABLEAUTOALTREF,         ctrl_set_enable_auto_alt_ref},
1383   {VP8E_SET_SHARPNESS,                ctrl_set_sharpness},
1384   {VP8E_SET_STATIC_THRESHOLD,         ctrl_set_static_thresh},
1385   {VP9E_SET_TILE_COLUMNS,             ctrl_set_tile_columns},
1386   {VP9E_SET_TILE_ROWS,                ctrl_set_tile_rows},
1387   {VP8E_SET_ARNR_MAXFRAMES,           ctrl_set_arnr_max_frames},
1388   {VP8E_SET_ARNR_STRENGTH,            ctrl_set_arnr_strength},
1389   {VP8E_SET_ARNR_TYPE,                ctrl_set_arnr_type},
1390   {VP8E_SET_TUNING,                   ctrl_set_tuning},
1391   {VP8E_SET_CQ_LEVEL,                 ctrl_set_cq_level},
1392   {VP8E_SET_MAX_INTRA_BITRATE_PCT,    ctrl_set_rc_max_intra_bitrate_pct},
1393   {VP9E_SET_MAX_INTER_BITRATE_PCT,    ctrl_set_rc_max_inter_bitrate_pct},
1394   {VP9E_SET_GF_CBR_BOOST_PCT,         ctrl_set_rc_gf_cbr_boost_pct},
1395   {VP9E_SET_LOSSLESS,                 ctrl_set_lossless},
1396   {VP9E_SET_FRAME_PARALLEL_DECODING,  ctrl_set_frame_parallel_decoding_mode},
1397   {VP9E_SET_AQ_MODE,                  ctrl_set_aq_mode},
1398   {VP9E_SET_FRAME_PERIODIC_BOOST,     ctrl_set_frame_periodic_boost},
1399   {VP9E_SET_SVC,                      ctrl_set_svc},
1400   {VP9E_SET_SVC_PARAMETERS,           ctrl_set_svc_parameters},
1401   {VP9E_REGISTER_CX_CALLBACK,         ctrl_register_cx_callback},
1402   {VP9E_SET_SVC_LAYER_ID,             ctrl_set_svc_layer_id},
1403   {VP9E_SET_TUNE_CONTENT,             ctrl_set_tune_content},
1404   {VP9E_SET_COLOR_SPACE,              ctrl_set_color_space},
1405   {VP9E_SET_NOISE_SENSITIVITY,        ctrl_set_noise_sensitivity},
1406
1407   // Getters
1408   {VP8E_GET_LAST_QUANTIZER,           ctrl_get_quantizer},
1409   {VP8E_GET_LAST_QUANTIZER_64,        ctrl_get_quantizer64},
1410   {VP9_GET_REFERENCE,                 ctrl_get_reference},
1411   {VP9E_GET_SVC_LAYER_ID,             ctrl_get_svc_layer_id},
1412
1413   { -1, NULL},
1414 };
1415
1416 static vpx_codec_enc_cfg_map_t encoder_usage_cfg_map[] = {
1417   {
1418     0,
1419     {  // NOLINT
1420       0,                  // g_usage
1421       8,                  // g_threads
1422       0,                  // g_profile
1423
1424       320,                // g_width
1425       240,                // g_height
1426       VPX_BITS_8,         // g_bit_depth
1427       8,                  // g_input_bit_depth
1428
1429       {1, 30},            // g_timebase
1430
1431       0,                  // g_error_resilient
1432
1433       VPX_RC_ONE_PASS,    // g_pass
1434
1435       25,                 // g_lag_in_frames
1436
1437       0,                  // rc_dropframe_thresh
1438       0,                  // rc_resize_allowed
1439       0,                  // rc_scaled_width
1440       0,                  // rc_scaled_height
1441       60,                 // rc_resize_down_thresold
1442       30,                 // rc_resize_up_thresold
1443
1444       VPX_VBR,            // rc_end_usage
1445 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1446       {NULL, 0},          // rc_twopass_stats_in
1447       {NULL, 0},          // rc_firstpass_mb_stats_in
1448 #endif
1449       256,                // rc_target_bandwidth
1450       0,                  // rc_min_quantizer
1451       63,                 // rc_max_quantizer
1452       25,                 // rc_undershoot_pct
1453       25,                 // rc_overshoot_pct
1454
1455       6000,               // rc_max_buffer_size
1456       4000,               // rc_buffer_initial_size
1457       5000,               // rc_buffer_optimal_size
1458
1459       50,                 // rc_two_pass_vbrbias
1460       0,                  // rc_two_pass_vbrmin_section
1461       2000,               // rc_two_pass_vbrmax_section
1462
1463       // keyframing settings (kf)
1464       VPX_KF_AUTO,        // g_kfmode
1465       0,                  // kf_min_dist
1466       9999,               // kf_max_dist
1467
1468       VPX_SS_DEFAULT_LAYERS,  // ss_number_layers
1469       {0},
1470       {0},                    // ss_target_bitrate
1471       1,                      // ts_number_layers
1472       {0},                    // ts_target_bitrate
1473       {0},                    // ts_rate_decimator
1474       0,                      // ts_periodicity
1475       {0},                    // ts_layer_id
1476 #if VPX_ENCODER_ABI_VERSION == (1 + VPX_CODEC_ABI_VERSION)
1477       "vp8.fpf"           // first pass filename
1478 #endif
1479     }
1480   },
1481 };
1482
1483 #ifndef VERSION_STRING
1484 #define VERSION_STRING
1485 #endif
1486 CODEC_INTERFACE(vpx_codec_vp9_cx) = {
1487   "WebM Project VP9 Encoder" VERSION_STRING,
1488   VPX_CODEC_INTERNAL_ABI_VERSION,
1489 #if CONFIG_VP9_HIGHBITDEPTH
1490   VPX_CODEC_CAP_HIGHBITDEPTH |
1491 #endif
1492   VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR,  // vpx_codec_caps_t
1493   encoder_init,       // vpx_codec_init_fn_t
1494   encoder_destroy,    // vpx_codec_destroy_fn_t
1495   encoder_ctrl_maps,  // vpx_codec_ctrl_fn_map_t
1496   {  // NOLINT
1497     NULL,  // vpx_codec_peek_si_fn_t
1498     NULL,  // vpx_codec_get_si_fn_t
1499     NULL,  // vpx_codec_decode_fn_t
1500     NULL,  // vpx_codec_frame_get_fn_t
1501     NULL   // vpx_codec_set_fb_fn_t
1502   },
1503   {  // NOLINT
1504     1,                      // 1 cfg map
1505     encoder_usage_cfg_map,  // vpx_codec_enc_cfg_map_t
1506     encoder_encode,         // vpx_codec_encode_fn_t
1507     encoder_get_cxdata,     // vpx_codec_get_cx_data_fn_t
1508     encoder_set_config,     // vpx_codec_enc_config_set_fn_t
1509     NULL,        // vpx_codec_get_global_headers_fn_t
1510     encoder_get_preview,    // vpx_codec_get_preview_frame_fn_t
1511     NULL         // vpx_codec_enc_mr_get_mem_loc_fn_t
1512   }
1513 };