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