• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/vpx_ext_ratectrl.h"
17 #include "vpx_dsp/psnr.h"
18 #include "vpx_ports/static_assert.h"
19 #include "vpx_ports/system_state.h"
20 #include "vpx_util/vpx_timestamp.h"
21 #include "vpx/internal/vpx_codec_internal.h"
22 #include "./vpx_version.h"
23 #include "vp9/encoder/vp9_encoder.h"
24 #include "vpx/vp8cx.h"
25 #include "vp9/common/vp9_alloccommon.h"
26 #include "vp9/vp9_cx_iface.h"
27 #include "vp9/encoder/vp9_firstpass.h"
28 #include "vp9/encoder/vp9_lookahead.h"
29 #include "vp9/vp9_cx_iface.h"
30 #include "vp9/vp9_iface_common.h"
31 
32 typedef struct vp9_extracfg {
33   int cpu_used;  // available cpu percentage in 1/16
34   unsigned int enable_auto_alt_ref;
35   unsigned int noise_sensitivity;
36   unsigned int sharpness;
37   unsigned int static_thresh;
38   unsigned int tile_columns;
39   unsigned int tile_rows;
40   unsigned int enable_tpl_model;
41   unsigned int arnr_max_frames;
42   unsigned int arnr_strength;
43   unsigned int min_gf_interval;
44   unsigned int max_gf_interval;
45   vp8e_tuning tuning;
46   unsigned int cq_level;  // constrained quality level
47   unsigned int rc_max_intra_bitrate_pct;
48   unsigned int rc_max_inter_bitrate_pct;
49   unsigned int gf_cbr_boost_pct;
50   unsigned int lossless;
51   unsigned int target_level;
52   unsigned int frame_parallel_decoding_mode;
53   AQ_MODE aq_mode;
54   int alt_ref_aq;
55   unsigned int frame_periodic_boost;
56   vpx_bit_depth_t bit_depth;
57   vp9e_tune_content content;
58   vpx_color_space_t color_space;
59   vpx_color_range_t color_range;
60   int render_width;
61   int render_height;
62   unsigned int row_mt;
63   unsigned int motion_vector_unit_test;
64   int delta_q_uv;
65 } vp9_extracfg;
66 
67 static struct vp9_extracfg default_extra_cfg = {
68 #if CONFIG_REALTIME_ONLY
69   5,  // cpu_used
70 #else
71   0,  // cpu_used
72 #endif
73   1,                     // enable_auto_alt_ref
74   0,                     // noise_sensitivity
75   0,                     // sharpness
76   0,                     // static_thresh
77   6,                     // tile_columns
78   0,                     // tile_rows
79   1,                     // enable_tpl_model
80   7,                     // arnr_max_frames
81   5,                     // arnr_strength
82   0,                     // min_gf_interval; 0 -> default decision
83   0,                     // max_gf_interval; 0 -> default decision
84   VP8_TUNE_PSNR,         // tuning
85   10,                    // cq_level
86   0,                     // rc_max_intra_bitrate_pct
87   0,                     // rc_max_inter_bitrate_pct
88   0,                     // gf_cbr_boost_pct
89   0,                     // lossless
90   255,                   // target_level
91   1,                     // frame_parallel_decoding_mode
92   NO_AQ,                 // aq_mode
93   0,                     // alt_ref_aq
94   0,                     // frame_periodic_delta_q
95   VPX_BITS_8,            // Bit depth
96   VP9E_CONTENT_DEFAULT,  // content
97   VPX_CS_UNKNOWN,        // color space
98   0,                     // color range
99   0,                     // render width
100   0,                     // render height
101   0,                     // row_mt
102   0,                     // motion_vector_unit_test
103   0,                     // delta_q_uv
104 };
105 
106 struct vpx_codec_alg_priv {
107   vpx_codec_priv_t base;
108   vpx_codec_enc_cfg_t cfg;
109   struct vp9_extracfg extra_cfg;
110   vpx_rational64_t timestamp_ratio;
111   vpx_codec_pts_t pts_offset;
112   unsigned char pts_offset_initialized;
113   VP9EncoderConfig oxcf;
114   VP9_COMP *cpi;
115   unsigned char *cx_data;
116   size_t cx_data_sz;
117   unsigned char *pending_cx_data;
118   size_t pending_cx_data_sz;
119   int pending_frame_count;
120   size_t pending_frame_sizes[8];
121   size_t pending_frame_magnitude;
122   vpx_image_t preview_img;
123   vpx_enc_frame_flags_t next_frame_flags;
124   vp8_postproc_cfg_t preview_ppcfg;
125   vpx_codec_pkt_list_decl(256) pkt_list;
126   unsigned int fixed_kf_cntr;
127   vpx_codec_priv_output_cx_pkt_cb_pair_t output_cx_pkt_cb;
128   // BufferPool that holds all reference frames.
129   BufferPool *buffer_pool;
130 };
131 
update_error_state(vpx_codec_alg_priv_t * ctx,const struct vpx_internal_error_info * error)132 static vpx_codec_err_t update_error_state(
133     vpx_codec_alg_priv_t *ctx, const struct vpx_internal_error_info *error) {
134   const vpx_codec_err_t res = error->error_code;
135 
136   if (res != VPX_CODEC_OK)
137     ctx->base.err_detail = error->has_detail ? error->detail : NULL;
138 
139   return res;
140 }
141 
142 #undef ERROR
143 #define ERROR(str)                  \
144   do {                              \
145     ctx->base.err_detail = str;     \
146     return VPX_CODEC_INVALID_PARAM; \
147   } while (0)
148 
149 #define RANGE_CHECK(p, memb, lo, hi)                                     \
150   do {                                                                   \
151     if (!(((p)->memb == (lo) || (p)->memb > (lo)) && (p)->memb <= (hi))) \
152       ERROR(#memb " out of range [" #lo ".." #hi "]");                   \
153   } while (0)
154 
155 #define RANGE_CHECK_HI(p, memb, hi)                                     \
156   do {                                                                  \
157     if (!((p)->memb <= (hi))) ERROR(#memb " out of range [.." #hi "]"); \
158   } while (0)
159 
160 #define RANGE_CHECK_LO(p, memb, lo)                                     \
161   do {                                                                  \
162     if (!((p)->memb >= (lo))) ERROR(#memb " out of range [" #lo "..]"); \
163   } while (0)
164 
165 #define RANGE_CHECK_BOOL(p, memb)                                     \
166   do {                                                                \
167     if (!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean"); \
168   } while (0)
169 
validate_config(vpx_codec_alg_priv_t * ctx,const vpx_codec_enc_cfg_t * cfg,const struct vp9_extracfg * extra_cfg)170 static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t *ctx,
171                                        const vpx_codec_enc_cfg_t *cfg,
172                                        const struct vp9_extracfg *extra_cfg) {
173   RANGE_CHECK(cfg, g_w, 1, 65536);  // 16 bits available
174   RANGE_CHECK(cfg, g_h, 1, 65536);  // 16 bits available
175   RANGE_CHECK(cfg, g_timebase.den, 1, 1000000000);
176   RANGE_CHECK(cfg, g_timebase.num, 1, 1000000000);
177   RANGE_CHECK_HI(cfg, g_profile, 3);
178 
179   RANGE_CHECK_HI(cfg, rc_max_quantizer, 63);
180   RANGE_CHECK_HI(cfg, rc_min_quantizer, cfg->rc_max_quantizer);
181   RANGE_CHECK_BOOL(extra_cfg, lossless);
182   RANGE_CHECK_BOOL(extra_cfg, frame_parallel_decoding_mode);
183   RANGE_CHECK(extra_cfg, aq_mode, 0, AQ_MODE_COUNT - 2);
184   RANGE_CHECK(extra_cfg, alt_ref_aq, 0, 1);
185   RANGE_CHECK(extra_cfg, frame_periodic_boost, 0, 1);
186   RANGE_CHECK_HI(cfg, g_threads, 64);
187   RANGE_CHECK_HI(cfg, g_lag_in_frames, MAX_LAG_BUFFERS);
188   RANGE_CHECK(cfg, rc_end_usage, VPX_VBR, VPX_Q);
189   RANGE_CHECK_HI(cfg, rc_undershoot_pct, 100);
190   RANGE_CHECK_HI(cfg, rc_overshoot_pct, 100);
191   RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
192   RANGE_CHECK(cfg, rc_2pass_vbr_corpus_complexity, 0, 10000);
193   RANGE_CHECK(cfg, kf_mode, VPX_KF_DISABLED, VPX_KF_AUTO);
194   RANGE_CHECK_BOOL(cfg, rc_resize_allowed);
195   RANGE_CHECK_HI(cfg, rc_dropframe_thresh, 100);
196   RANGE_CHECK_HI(cfg, rc_resize_up_thresh, 100);
197   RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
198 #if CONFIG_REALTIME_ONLY
199   RANGE_CHECK(cfg, g_pass, VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
200 #else
201   RANGE_CHECK(cfg, g_pass, VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
202 #endif
203   RANGE_CHECK(extra_cfg, min_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
204   RANGE_CHECK(extra_cfg, max_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
205   if (extra_cfg->max_gf_interval > 0) {
206     RANGE_CHECK(extra_cfg, max_gf_interval, 2, (MAX_LAG_BUFFERS - 1));
207   }
208   if (extra_cfg->min_gf_interval > 0 && extra_cfg->max_gf_interval > 0) {
209     RANGE_CHECK(extra_cfg, max_gf_interval, extra_cfg->min_gf_interval,
210                 (MAX_LAG_BUFFERS - 1));
211   }
212 
213   // For formation of valid ARF groups lag_in _frames should be 0 or greater
214   // than the max_gf_interval + 2
215   if (cfg->g_lag_in_frames > 0 && extra_cfg->max_gf_interval > 0 &&
216       cfg->g_lag_in_frames < extra_cfg->max_gf_interval + 2) {
217     ERROR("Set lag in frames to 0 (low delay) or >= (max-gf-interval + 2)");
218   }
219 
220   if (cfg->rc_resize_allowed == 1) {
221     RANGE_CHECK(cfg, rc_scaled_width, 0, cfg->g_w);
222     RANGE_CHECK(cfg, rc_scaled_height, 0, cfg->g_h);
223   }
224 
225   RANGE_CHECK(cfg, ss_number_layers, 1, VPX_SS_MAX_LAYERS);
226   RANGE_CHECK(cfg, ts_number_layers, 1, VPX_TS_MAX_LAYERS);
227 
228   {
229     unsigned int level = extra_cfg->target_level;
230     if (level != LEVEL_1 && level != LEVEL_1_1 && level != LEVEL_2 &&
231         level != LEVEL_2_1 && level != LEVEL_3 && level != LEVEL_3_1 &&
232         level != LEVEL_4 && level != LEVEL_4_1 && level != LEVEL_5 &&
233         level != LEVEL_5_1 && level != LEVEL_5_2 && level != LEVEL_6 &&
234         level != LEVEL_6_1 && level != LEVEL_6_2 && level != LEVEL_UNKNOWN &&
235         level != LEVEL_AUTO && level != LEVEL_MAX)
236       ERROR("target_level is invalid");
237   }
238 
239   if (cfg->ss_number_layers * cfg->ts_number_layers > VPX_MAX_LAYERS)
240     ERROR("ss_number_layers * ts_number_layers is out of range");
241   if (cfg->ts_number_layers > 1) {
242     unsigned int sl, tl;
243     for (sl = 1; sl < cfg->ss_number_layers; ++sl) {
244       for (tl = 1; tl < cfg->ts_number_layers; ++tl) {
245         const int layer = LAYER_IDS_TO_IDX(sl, tl, cfg->ts_number_layers);
246         if (cfg->layer_target_bitrate[layer] <
247             cfg->layer_target_bitrate[layer - 1])
248           ERROR("ts_target_bitrate entries are not increasing");
249       }
250     }
251 
252     RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers - 1], 1, 1);
253     for (tl = cfg->ts_number_layers - 2; tl > 0; --tl)
254       if (cfg->ts_rate_decimator[tl - 1] != 2 * cfg->ts_rate_decimator[tl])
255         ERROR("ts_rate_decimator factors are not powers of 2");
256   }
257 
258   // VP9 does not support a lower bound on the keyframe interval in
259   // automatic keyframe placement mode.
260   if (cfg->kf_mode != VPX_KF_DISABLED && cfg->kf_min_dist != cfg->kf_max_dist &&
261       cfg->kf_min_dist > 0)
262     ERROR(
263         "kf_min_dist not supported in auto mode, use 0 "
264         "or kf_max_dist instead.");
265 
266   RANGE_CHECK(extra_cfg, row_mt, 0, 1);
267   RANGE_CHECK(extra_cfg, motion_vector_unit_test, 0, 2);
268   RANGE_CHECK(extra_cfg, enable_auto_alt_ref, 0, MAX_ARF_LAYERS);
269   RANGE_CHECK(extra_cfg, cpu_used, -9, 9);
270   RANGE_CHECK_HI(extra_cfg, noise_sensitivity, 6);
271   RANGE_CHECK(extra_cfg, tile_columns, 0, 6);
272   RANGE_CHECK(extra_cfg, tile_rows, 0, 2);
273   RANGE_CHECK_HI(extra_cfg, sharpness, 7);
274   RANGE_CHECK(extra_cfg, arnr_max_frames, 0, 15);
275   RANGE_CHECK_HI(extra_cfg, arnr_strength, 6);
276   RANGE_CHECK(extra_cfg, cq_level, 0, 63);
277   RANGE_CHECK(cfg, g_bit_depth, VPX_BITS_8, VPX_BITS_12);
278   RANGE_CHECK(cfg, g_input_bit_depth, 8, 12);
279   RANGE_CHECK(extra_cfg, content, VP9E_CONTENT_DEFAULT,
280               VP9E_CONTENT_INVALID - 1);
281 
282 #if !CONFIG_REALTIME_ONLY
283   if (cfg->g_pass == VPX_RC_LAST_PASS) {
284     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
285     const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
286     const FIRSTPASS_STATS *stats;
287 
288     if (cfg->rc_twopass_stats_in.buf == NULL)
289       ERROR("rc_twopass_stats_in.buf not set.");
290 
291     if (cfg->rc_twopass_stats_in.sz % packet_sz)
292       ERROR("rc_twopass_stats_in.sz indicates truncated packet.");
293 
294     if (cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) {
295       int i;
296       unsigned int n_packets_per_layer[VPX_SS_MAX_LAYERS] = { 0 };
297 
298       stats = cfg->rc_twopass_stats_in.buf;
299       for (i = 0; i < n_packets; ++i) {
300         const int layer_id = (int)stats[i].spatial_layer_id;
301         if (layer_id >= 0 && layer_id < (int)cfg->ss_number_layers) {
302           ++n_packets_per_layer[layer_id];
303         }
304       }
305 
306       for (i = 0; i < (int)cfg->ss_number_layers; ++i) {
307         unsigned int layer_id;
308         if (n_packets_per_layer[i] < 2) {
309           ERROR(
310               "rc_twopass_stats_in requires at least two packets for each "
311               "layer.");
312         }
313 
314         stats = (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf +
315                 n_packets - cfg->ss_number_layers + i;
316         layer_id = (int)stats->spatial_layer_id;
317 
318         if (layer_id >= cfg->ss_number_layers ||
319             (unsigned int)(stats->count + 0.5) !=
320                 n_packets_per_layer[layer_id] - 1)
321           ERROR("rc_twopass_stats_in missing EOS stats packet");
322       }
323     } else {
324       if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
325         ERROR("rc_twopass_stats_in requires at least two packets.");
326 
327       stats =
328           (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf + n_packets - 1;
329 
330       if ((int)(stats->count + 0.5) != n_packets - 1)
331         ERROR("rc_twopass_stats_in missing EOS stats packet");
332     }
333   }
334 #endif  // !CONFIG_REALTIME_ONLY
335 
336 #if !CONFIG_VP9_HIGHBITDEPTH
337   if (cfg->g_profile > (unsigned int)PROFILE_1) {
338     ERROR("Profile > 1 not supported in this build configuration");
339   }
340 #endif
341   if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
342       cfg->g_bit_depth > VPX_BITS_8) {
343     ERROR("Codec high bit-depth not supported in profile < 2");
344   }
345   if (cfg->g_profile <= (unsigned int)PROFILE_1 && cfg->g_input_bit_depth > 8) {
346     ERROR("Source high bit-depth not supported in profile < 2");
347   }
348   if (cfg->g_profile > (unsigned int)PROFILE_1 &&
349       cfg->g_bit_depth == VPX_BITS_8) {
350     ERROR("Codec bit-depth 8 not supported in profile > 1");
351   }
352   RANGE_CHECK(extra_cfg, color_space, VPX_CS_UNKNOWN, VPX_CS_SRGB);
353   RANGE_CHECK(extra_cfg, color_range, VPX_CR_STUDIO_RANGE, VPX_CR_FULL_RANGE);
354 
355   // The range below shall be further tuned.
356   RANGE_CHECK(cfg, use_vizier_rc_params, 0, 1);
357   RANGE_CHECK(cfg, active_wq_factor.den, 1, 1000);
358   RANGE_CHECK(cfg, err_per_mb_factor.den, 1, 1000);
359   RANGE_CHECK(cfg, sr_default_decay_limit.den, 1, 1000);
360   RANGE_CHECK(cfg, sr_diff_factor.den, 1, 1000);
361   RANGE_CHECK(cfg, kf_err_per_mb_factor.den, 1, 1000);
362   RANGE_CHECK(cfg, kf_frame_min_boost_factor.den, 1, 1000);
363   RANGE_CHECK(cfg, kf_frame_max_boost_subs_factor.den, 1, 1000);
364   RANGE_CHECK(cfg, kf_max_total_boost_factor.den, 1, 1000);
365   RANGE_CHECK(cfg, gf_max_total_boost_factor.den, 1, 1000);
366   RANGE_CHECK(cfg, gf_frame_max_boost_factor.den, 1, 1000);
367   RANGE_CHECK(cfg, zm_factor.den, 1, 1000);
368   RANGE_CHECK(cfg, rd_mult_inter_qp_fac.den, 1, 1000);
369   RANGE_CHECK(cfg, rd_mult_arf_qp_fac.den, 1, 1000);
370   RANGE_CHECK(cfg, rd_mult_key_qp_fac.den, 1, 1000);
371 
372   return VPX_CODEC_OK;
373 }
374 
validate_img(vpx_codec_alg_priv_t * ctx,const vpx_image_t * img)375 static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
376                                     const vpx_image_t *img) {
377   switch (img->fmt) {
378     case VPX_IMG_FMT_YV12:
379     case VPX_IMG_FMT_I420:
380     case VPX_IMG_FMT_I42016:
381     case VPX_IMG_FMT_NV12: break;
382     case VPX_IMG_FMT_I422:
383     case VPX_IMG_FMT_I444:
384     case VPX_IMG_FMT_I440:
385       if (ctx->cfg.g_profile != (unsigned int)PROFILE_1) {
386         ERROR(
387             "Invalid image format. I422, I444, I440 images are not supported "
388             "in profile.");
389       }
390       break;
391     case VPX_IMG_FMT_I42216:
392     case VPX_IMG_FMT_I44416:
393     case VPX_IMG_FMT_I44016:
394       if (ctx->cfg.g_profile != (unsigned int)PROFILE_1 &&
395           ctx->cfg.g_profile != (unsigned int)PROFILE_3) {
396         ERROR(
397             "Invalid image format. 16-bit I422, I444, I440 images are "
398             "not supported in profile.");
399       }
400       break;
401     default:
402       ERROR(
403           "Invalid image format. Only YV12, I420, I422, I444, I440, NV12 "
404           "images are supported.");
405       break;
406   }
407 
408   if (img->d_w != ctx->cfg.g_w || img->d_h != ctx->cfg.g_h)
409     ERROR("Image size must match encoder init configuration size");
410 
411   return VPX_CODEC_OK;
412 }
413 
get_image_bps(const vpx_image_t * img)414 static int get_image_bps(const vpx_image_t *img) {
415   switch (img->fmt) {
416     case VPX_IMG_FMT_YV12:
417     case VPX_IMG_FMT_NV12:
418     case VPX_IMG_FMT_I420: return 12;
419     case VPX_IMG_FMT_I422: return 16;
420     case VPX_IMG_FMT_I444: return 24;
421     case VPX_IMG_FMT_I440: return 16;
422     case VPX_IMG_FMT_I42016: return 24;
423     case VPX_IMG_FMT_I42216: return 32;
424     case VPX_IMG_FMT_I44416: return 48;
425     case VPX_IMG_FMT_I44016: return 32;
426     default: assert(0 && "Invalid image format"); break;
427   }
428   return 0;
429 }
430 
431 // Modify the encoder config for the target level.
config_target_level(VP9EncoderConfig * oxcf)432 static void config_target_level(VP9EncoderConfig *oxcf) {
433   double max_average_bitrate;  // in bits per second
434   int max_over_shoot_pct;
435   const int target_level_index = get_level_index(oxcf->target_level);
436 
437   vpx_clear_system_state();
438   assert(target_level_index >= 0);
439   assert(target_level_index < VP9_LEVELS);
440 
441   // Maximum target bit-rate is level_limit * 80%.
442   max_average_bitrate =
443       vp9_level_defs[target_level_index].average_bitrate * 800.0;
444   if ((double)oxcf->target_bandwidth > max_average_bitrate)
445     oxcf->target_bandwidth = (int64_t)(max_average_bitrate);
446   if (oxcf->ss_number_layers == 1 && oxcf->pass != 0)
447     oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;
448 
449   // Adjust max over-shoot percentage.
450   max_over_shoot_pct =
451       (int)((max_average_bitrate * 1.10 - (double)oxcf->target_bandwidth) *
452             100 / (double)(oxcf->target_bandwidth));
453   if (oxcf->over_shoot_pct > max_over_shoot_pct)
454     oxcf->over_shoot_pct = max_over_shoot_pct;
455 
456   // Adjust worst allowed quantizer.
457   oxcf->worst_allowed_q = vp9_quantizer_to_qindex(63);
458 
459   // Adjust minimum art-ref distance.
460   // min_gf_interval should be no less than min_altref_distance + 1,
461   // as the encoder may produce bitstream with alt-ref distance being
462   // min_gf_interval - 1.
463   if (oxcf->min_gf_interval <=
464       (int)vp9_level_defs[target_level_index].min_altref_distance) {
465     oxcf->min_gf_interval =
466         (int)vp9_level_defs[target_level_index].min_altref_distance + 1;
467     // If oxcf->max_gf_interval == 0, it will be assigned with a default value
468     // in vp9_rc_set_gf_interval_range().
469     if (oxcf->max_gf_interval != 0) {
470       oxcf->max_gf_interval =
471           VPXMAX(oxcf->max_gf_interval, oxcf->min_gf_interval);
472     }
473   }
474 
475   // Adjust maximum column tiles.
476   if (vp9_level_defs[target_level_index].max_col_tiles <
477       (1 << oxcf->tile_columns)) {
478     while (oxcf->tile_columns > 0 &&
479            vp9_level_defs[target_level_index].max_col_tiles <
480                (1 << oxcf->tile_columns))
481       --oxcf->tile_columns;
482   }
483 }
484 
get_g_timebase_in_ts(vpx_rational_t g_timebase)485 static vpx_rational64_t get_g_timebase_in_ts(vpx_rational_t g_timebase) {
486   vpx_rational64_t g_timebase_in_ts;
487   g_timebase_in_ts.den = g_timebase.den;
488   g_timebase_in_ts.num = g_timebase.num;
489   g_timebase_in_ts.num *= TICKS_PER_SEC;
490   reduce_ratio(&g_timebase_in_ts);
491   return g_timebase_in_ts;
492 }
493 
set_encoder_config(VP9EncoderConfig * oxcf,vpx_codec_enc_cfg_t * cfg,const struct vp9_extracfg * extra_cfg)494 static vpx_codec_err_t set_encoder_config(
495     VP9EncoderConfig *oxcf, vpx_codec_enc_cfg_t *cfg,
496     const struct vp9_extracfg *extra_cfg) {
497   const int is_vbr = cfg->rc_end_usage == VPX_VBR;
498   int sl, tl;
499   unsigned int raw_target_rate;
500   oxcf->profile = cfg->g_profile;
501   oxcf->max_threads = (int)cfg->g_threads;
502   oxcf->width = cfg->g_w;
503   oxcf->height = cfg->g_h;
504   oxcf->bit_depth = cfg->g_bit_depth;
505   oxcf->input_bit_depth = cfg->g_input_bit_depth;
506   // TODO(angiebird): Figure out if we can just use g_timebase to indicate the
507   // inverse of framerate
508   // guess a frame rate if out of whack, use 30
509   oxcf->init_framerate = (double)cfg->g_timebase.den / cfg->g_timebase.num;
510   if (oxcf->init_framerate > 180) oxcf->init_framerate = 30;
511   oxcf->g_timebase = cfg->g_timebase;
512   oxcf->g_timebase_in_ts = get_g_timebase_in_ts(oxcf->g_timebase);
513 
514   oxcf->mode = GOOD;
515 
516   switch (cfg->g_pass) {
517     case VPX_RC_ONE_PASS: oxcf->pass = 0; break;
518     case VPX_RC_FIRST_PASS: oxcf->pass = 1; break;
519     case VPX_RC_LAST_PASS: oxcf->pass = 2; break;
520   }
521 
522   oxcf->lag_in_frames =
523       cfg->g_pass == VPX_RC_FIRST_PASS ? 0 : cfg->g_lag_in_frames;
524   oxcf->rc_mode = cfg->rc_end_usage;
525 
526   raw_target_rate =
527       (unsigned int)((int64_t)oxcf->width * oxcf->height * oxcf->bit_depth * 3 *
528                      oxcf->init_framerate / 1000);
529   // Cap target bitrate to raw rate or 1000Mbps, whichever is less
530   cfg->rc_target_bitrate =
531       VPXMIN(VPXMIN(raw_target_rate, cfg->rc_target_bitrate), 1000000);
532 
533   // Convert target bandwidth from Kbit/s to Bit/s
534   oxcf->target_bandwidth = 1000 * (int64_t)cfg->rc_target_bitrate;
535   oxcf->rc_max_intra_bitrate_pct = extra_cfg->rc_max_intra_bitrate_pct;
536   oxcf->rc_max_inter_bitrate_pct = extra_cfg->rc_max_inter_bitrate_pct;
537   oxcf->gf_cbr_boost_pct = extra_cfg->gf_cbr_boost_pct;
538 
539   oxcf->best_allowed_q =
540       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_min_quantizer);
541   oxcf->worst_allowed_q =
542       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_max_quantizer);
543   oxcf->cq_level = vp9_quantizer_to_qindex(extra_cfg->cq_level);
544   oxcf->fixed_q = -1;
545 
546   oxcf->under_shoot_pct = cfg->rc_undershoot_pct;
547   oxcf->over_shoot_pct = cfg->rc_overshoot_pct;
548 
549   oxcf->scaled_frame_width = cfg->rc_scaled_width;
550   oxcf->scaled_frame_height = cfg->rc_scaled_height;
551   if (cfg->rc_resize_allowed == 1) {
552     oxcf->resize_mode =
553         (oxcf->scaled_frame_width == 0 || oxcf->scaled_frame_height == 0)
554             ? RESIZE_DYNAMIC
555             : RESIZE_FIXED;
556   } else {
557     oxcf->resize_mode = RESIZE_NONE;
558   }
559 
560   oxcf->maximum_buffer_size_ms = is_vbr ? 240000 : cfg->rc_buf_sz;
561   oxcf->starting_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_initial_sz;
562   oxcf->optimal_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_optimal_sz;
563 
564   oxcf->drop_frames_water_mark = cfg->rc_dropframe_thresh;
565 
566   oxcf->two_pass_vbrbias = cfg->rc_2pass_vbr_bias_pct;
567   oxcf->two_pass_vbrmin_section = cfg->rc_2pass_vbr_minsection_pct;
568   oxcf->two_pass_vbrmax_section = cfg->rc_2pass_vbr_maxsection_pct;
569   oxcf->vbr_corpus_complexity = cfg->rc_2pass_vbr_corpus_complexity;
570 
571   oxcf->auto_key =
572       cfg->kf_mode == VPX_KF_AUTO && cfg->kf_min_dist != cfg->kf_max_dist;
573 
574   oxcf->key_freq = cfg->kf_max_dist;
575 
576   oxcf->speed = abs(extra_cfg->cpu_used);
577   oxcf->encode_breakout = extra_cfg->static_thresh;
578   oxcf->enable_auto_arf = extra_cfg->enable_auto_alt_ref;
579   if (oxcf->bit_depth == VPX_BITS_8) {
580     oxcf->noise_sensitivity = extra_cfg->noise_sensitivity;
581   } else {
582     // Disable denoiser for high bitdepth since vp9_denoiser_filter only works
583     // for 8 bits.
584     oxcf->noise_sensitivity = 0;
585   }
586   oxcf->sharpness = extra_cfg->sharpness;
587 
588   vp9_set_first_pass_stats(oxcf, &cfg->rc_twopass_stats_in);
589 
590   oxcf->color_space = extra_cfg->color_space;
591   oxcf->color_range = extra_cfg->color_range;
592   oxcf->render_width = extra_cfg->render_width;
593   oxcf->render_height = extra_cfg->render_height;
594   oxcf->arnr_max_frames = extra_cfg->arnr_max_frames;
595   oxcf->arnr_strength = extra_cfg->arnr_strength;
596   oxcf->min_gf_interval = extra_cfg->min_gf_interval;
597   oxcf->max_gf_interval = extra_cfg->max_gf_interval;
598 
599   oxcf->tuning = extra_cfg->tuning;
600   oxcf->content = extra_cfg->content;
601 
602   oxcf->tile_columns = extra_cfg->tile_columns;
603 
604   oxcf->enable_tpl_model = extra_cfg->enable_tpl_model;
605 
606   // TODO(yunqing): The dependencies between row tiles cause error in multi-
607   // threaded encoding. For now, tile_rows is forced to be 0 in this case.
608   // The further fix can be done by adding synchronizations after a tile row
609   // is encoded. But this will hurt multi-threaded encoder performance. So,
610   // it is recommended to use tile-rows=0 while encoding with threads > 1.
611   if (oxcf->max_threads > 1 && oxcf->tile_columns > 0)
612     oxcf->tile_rows = 0;
613   else
614     oxcf->tile_rows = extra_cfg->tile_rows;
615 
616   oxcf->error_resilient_mode = cfg->g_error_resilient;
617   oxcf->frame_parallel_decoding_mode = extra_cfg->frame_parallel_decoding_mode;
618 
619   oxcf->aq_mode = extra_cfg->aq_mode;
620   oxcf->alt_ref_aq = extra_cfg->alt_ref_aq;
621 
622   oxcf->frame_periodic_boost = extra_cfg->frame_periodic_boost;
623 
624   oxcf->ss_number_layers = cfg->ss_number_layers;
625   oxcf->ts_number_layers = cfg->ts_number_layers;
626   oxcf->temporal_layering_mode =
627       (enum vp9e_temporal_layering_mode)cfg->temporal_layering_mode;
628 
629   oxcf->target_level = extra_cfg->target_level;
630 
631   oxcf->row_mt = extra_cfg->row_mt;
632   oxcf->motion_vector_unit_test = extra_cfg->motion_vector_unit_test;
633 
634   oxcf->delta_q_uv = extra_cfg->delta_q_uv;
635 
636   for (sl = 0; sl < oxcf->ss_number_layers; ++sl) {
637     for (tl = 0; tl < oxcf->ts_number_layers; ++tl) {
638       oxcf->layer_target_bitrate[sl * oxcf->ts_number_layers + tl] =
639           1000 * cfg->layer_target_bitrate[sl * oxcf->ts_number_layers + tl];
640     }
641   }
642   if (oxcf->ss_number_layers == 1 && oxcf->pass != 0) {
643     oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;
644   }
645   if (oxcf->ts_number_layers > 1) {
646     for (tl = 0; tl < VPX_TS_MAX_LAYERS; ++tl) {
647       oxcf->ts_rate_decimator[tl] =
648           cfg->ts_rate_decimator[tl] ? cfg->ts_rate_decimator[tl] : 1;
649     }
650   } else if (oxcf->ts_number_layers == 1) {
651     oxcf->ts_rate_decimator[0] = 1;
652   }
653 
654   if (get_level_index(oxcf->target_level) >= 0) config_target_level(oxcf);
655   oxcf->use_simple_encode_api = 0;
656   // vp9_dump_encoder_config(oxcf, stderr);
657   return VPX_CODEC_OK;
658 }
659 
set_twopass_params_from_config(const vpx_codec_enc_cfg_t * const cfg,struct VP9_COMP * cpi)660 static vpx_codec_err_t set_twopass_params_from_config(
661     const vpx_codec_enc_cfg_t *const cfg, struct VP9_COMP *cpi) {
662   if (!cfg->use_vizier_rc_params) return VPX_CODEC_OK;
663   if (cpi == NULL) return VPX_CODEC_ERROR;
664 
665   cpi->twopass.use_vizier_rc_params = cfg->use_vizier_rc_params;
666 
667   // The values set here are factors that will be applied to default values
668   // to get the final value used in the two pass code. Hence 1.0 will
669   // match the default behaviour when not using passed in values.
670   // We also apply limits here to prevent the user from applying settings
671   // that make no sense.
672   cpi->twopass.active_wq_factor =
673       (double)cfg->active_wq_factor.num / (double)cfg->active_wq_factor.den;
674   if (cpi->twopass.active_wq_factor < 0.25)
675     cpi->twopass.active_wq_factor = 0.25;
676   else if (cpi->twopass.active_wq_factor > 16.0)
677     cpi->twopass.active_wq_factor = 16.0;
678 
679   cpi->twopass.err_per_mb =
680       (double)cfg->err_per_mb_factor.num / (double)cfg->err_per_mb_factor.den;
681   if (cpi->twopass.err_per_mb < 0.25)
682     cpi->twopass.err_per_mb = 0.25;
683   else if (cpi->twopass.err_per_mb > 4.0)
684     cpi->twopass.err_per_mb = 4.0;
685 
686   cpi->twopass.sr_default_decay_limit =
687       (double)cfg->sr_default_decay_limit.num /
688       (double)cfg->sr_default_decay_limit.den;
689   if (cpi->twopass.sr_default_decay_limit < 0.25)
690     cpi->twopass.sr_default_decay_limit = 0.25;
691   // If the default changes this will need to change.
692   else if (cpi->twopass.sr_default_decay_limit > 1.33)
693     cpi->twopass.sr_default_decay_limit = 1.33;
694 
695   cpi->twopass.sr_diff_factor =
696       (double)cfg->sr_diff_factor.num / (double)cfg->sr_diff_factor.den;
697   if (cpi->twopass.sr_diff_factor < 0.25)
698     cpi->twopass.sr_diff_factor = 0.25;
699   else if (cpi->twopass.sr_diff_factor > 4.0)
700     cpi->twopass.sr_diff_factor = 4.0;
701 
702   cpi->twopass.kf_err_per_mb = (double)cfg->kf_err_per_mb_factor.num /
703                                (double)cfg->kf_err_per_mb_factor.den;
704   if (cpi->twopass.kf_err_per_mb < 0.25)
705     cpi->twopass.kf_err_per_mb = 0.25;
706   else if (cpi->twopass.kf_err_per_mb > 4.0)
707     cpi->twopass.kf_err_per_mb = 4.0;
708 
709   cpi->twopass.kf_frame_min_boost = (double)cfg->kf_frame_min_boost_factor.num /
710                                     (double)cfg->kf_frame_min_boost_factor.den;
711   if (cpi->twopass.kf_frame_min_boost < 0.25)
712     cpi->twopass.kf_frame_min_boost = 0.25;
713   else if (cpi->twopass.kf_frame_min_boost > 4.0)
714     cpi->twopass.kf_frame_min_boost = 4.0;
715 
716   cpi->twopass.kf_frame_max_boost_first =
717       (double)cfg->kf_frame_max_boost_first_factor.num /
718       (double)cfg->kf_frame_max_boost_first_factor.den;
719   if (cpi->twopass.kf_frame_max_boost_first < 0.25)
720     cpi->twopass.kf_frame_max_boost_first = 0.25;
721   else if (cpi->twopass.kf_frame_max_boost_first > 4.0)
722     cpi->twopass.kf_frame_max_boost_first = 4.0;
723 
724   cpi->twopass.kf_frame_max_boost_subs =
725       (double)cfg->kf_frame_max_boost_subs_factor.num /
726       (double)cfg->kf_frame_max_boost_subs_factor.den;
727   if (cpi->twopass.kf_frame_max_boost_subs < 0.25)
728     cpi->twopass.kf_frame_max_boost_subs = 0.25;
729   else if (cpi->twopass.kf_frame_max_boost_subs > 4.0)
730     cpi->twopass.kf_frame_max_boost_subs = 4.0;
731 
732   cpi->twopass.kf_max_total_boost = (double)cfg->kf_max_total_boost_factor.num /
733                                     (double)cfg->kf_max_total_boost_factor.den;
734   if (cpi->twopass.kf_max_total_boost < 0.25)
735     cpi->twopass.kf_max_total_boost = 0.25;
736   else if (cpi->twopass.kf_max_total_boost > 4.0)
737     cpi->twopass.kf_max_total_boost = 4.0;
738 
739   cpi->twopass.gf_max_total_boost = (double)cfg->gf_max_total_boost_factor.num /
740                                     (double)cfg->gf_max_total_boost_factor.den;
741   if (cpi->twopass.gf_max_total_boost < 0.25)
742     cpi->twopass.gf_max_total_boost = 0.25;
743   else if (cpi->twopass.gf_max_total_boost > 4.0)
744     cpi->twopass.gf_max_total_boost = 4.0;
745 
746   cpi->twopass.gf_frame_max_boost = (double)cfg->gf_frame_max_boost_factor.num /
747                                     (double)cfg->gf_frame_max_boost_factor.den;
748   if (cpi->twopass.gf_frame_max_boost < 0.25)
749     cpi->twopass.gf_frame_max_boost = 0.25;
750   else if (cpi->twopass.gf_frame_max_boost > 4.0)
751     cpi->twopass.gf_frame_max_boost = 4.0;
752 
753   cpi->twopass.zm_factor =
754       (double)cfg->zm_factor.num / (double)cfg->zm_factor.den;
755   if (cpi->twopass.zm_factor < 0.25)
756     cpi->twopass.zm_factor = 0.25;
757   else if (cpi->twopass.zm_factor > 2.0)
758     cpi->twopass.zm_factor = 2.0;
759 
760   cpi->rd_ctrl.rd_mult_inter_qp_fac = (double)cfg->rd_mult_inter_qp_fac.num /
761                                       (double)cfg->rd_mult_inter_qp_fac.den;
762   if (cpi->rd_ctrl.rd_mult_inter_qp_fac < 0.25)
763     cpi->rd_ctrl.rd_mult_inter_qp_fac = 0.25;
764   else if (cpi->rd_ctrl.rd_mult_inter_qp_fac > 4.0)
765     cpi->rd_ctrl.rd_mult_inter_qp_fac = 4.0;
766 
767   cpi->rd_ctrl.rd_mult_arf_qp_fac =
768       (double)cfg->rd_mult_arf_qp_fac.num / (double)cfg->rd_mult_arf_qp_fac.den;
769   if (cpi->rd_ctrl.rd_mult_arf_qp_fac < 0.25)
770     cpi->rd_ctrl.rd_mult_arf_qp_fac = 0.25;
771   else if (cpi->rd_ctrl.rd_mult_arf_qp_fac > 4.0)
772     cpi->rd_ctrl.rd_mult_arf_qp_fac = 4.0;
773 
774   cpi->rd_ctrl.rd_mult_key_qp_fac =
775       (double)cfg->rd_mult_key_qp_fac.num / (double)cfg->rd_mult_key_qp_fac.den;
776   if (cpi->rd_ctrl.rd_mult_key_qp_fac < 0.25)
777     cpi->rd_ctrl.rd_mult_key_qp_fac = 0.25;
778   else if (cpi->rd_ctrl.rd_mult_key_qp_fac > 4.0)
779     cpi->rd_ctrl.rd_mult_key_qp_fac = 4.0;
780 
781   return VPX_CODEC_OK;
782 }
783 
encoder_set_config(vpx_codec_alg_priv_t * ctx,const vpx_codec_enc_cfg_t * cfg)784 static vpx_codec_err_t encoder_set_config(vpx_codec_alg_priv_t *ctx,
785                                           const vpx_codec_enc_cfg_t *cfg) {
786   vpx_codec_err_t res;
787   volatile int force_key = 0;
788 
789   if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h) {
790     if (cfg->g_lag_in_frames > 1 || cfg->g_pass != VPX_RC_ONE_PASS)
791       ERROR("Cannot change width or height after initialization");
792     if (!valid_ref_frame_size(ctx->cfg.g_w, ctx->cfg.g_h, cfg->g_w, cfg->g_h) ||
793         (ctx->cpi->initial_width && (int)cfg->g_w > ctx->cpi->initial_width) ||
794         (ctx->cpi->initial_height && (int)cfg->g_h > ctx->cpi->initial_height))
795       force_key = 1;
796   }
797 
798   // Prevent increasing lag_in_frames. This check is stricter than it needs
799   // to be -- the limit is not increasing past the first lag_in_frames
800   // value, but we don't track the initial config, only the last successful
801   // config.
802   if (cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames)
803     ERROR("Cannot increase lag_in_frames");
804 
805   res = validate_config(ctx, cfg, &ctx->extra_cfg);
806   if (res != VPX_CODEC_OK) return res;
807 
808   if (setjmp(ctx->cpi->common.error.jmp)) {
809     const vpx_codec_err_t codec_err =
810         update_error_state(ctx, &ctx->cpi->common.error);
811     ctx->cpi->common.error.setjmp = 0;
812     vpx_clear_system_state();
813     assert(codec_err != VPX_CODEC_OK);
814     return codec_err;
815   }
816 
817   ctx->cfg = *cfg;
818   set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
819   set_twopass_params_from_config(&ctx->cfg, ctx->cpi);
820   // On profile change, request a key frame
821   force_key |= ctx->cpi->common.profile != ctx->oxcf.profile;
822   vp9_change_config(ctx->cpi, &ctx->oxcf);
823 
824   if (force_key) ctx->next_frame_flags |= VPX_EFLAG_FORCE_KF;
825 
826   ctx->cpi->common.error.setjmp = 0;
827   return VPX_CODEC_OK;
828 }
829 
ctrl_get_quantizer(vpx_codec_alg_priv_t * ctx,va_list args)830 static vpx_codec_err_t ctrl_get_quantizer(vpx_codec_alg_priv_t *ctx,
831                                           va_list args) {
832   int *const arg = va_arg(args, int *);
833   if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
834   *arg = vp9_get_quantizer(ctx->cpi);
835   return VPX_CODEC_OK;
836 }
837 
ctrl_get_quantizer64(vpx_codec_alg_priv_t * ctx,va_list args)838 static vpx_codec_err_t ctrl_get_quantizer64(vpx_codec_alg_priv_t *ctx,
839                                             va_list args) {
840   int *const arg = va_arg(args, int *);
841   if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
842   *arg = vp9_qindex_to_quantizer(vp9_get_quantizer(ctx->cpi));
843   return VPX_CODEC_OK;
844 }
845 
ctrl_get_quantizer_svc_layers(vpx_codec_alg_priv_t * ctx,va_list args)846 static vpx_codec_err_t ctrl_get_quantizer_svc_layers(vpx_codec_alg_priv_t *ctx,
847                                                      va_list args) {
848   int *const arg = va_arg(args, int *);
849   int i;
850   if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
851   for (i = 0; i < VPX_SS_MAX_LAYERS; i++) {
852     arg[i] = ctx->cpi->svc.base_qindex[i];
853   }
854   return VPX_CODEC_OK;
855 }
856 
ctrl_get_loopfilter_level(vpx_codec_alg_priv_t * ctx,va_list args)857 static vpx_codec_err_t ctrl_get_loopfilter_level(vpx_codec_alg_priv_t *ctx,
858                                                  va_list args) {
859   int *const arg = va_arg(args, int *);
860   if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
861   *arg = ctx->cpi->common.lf.filter_level;
862   return VPX_CODEC_OK;
863 }
864 
update_extra_cfg(vpx_codec_alg_priv_t * ctx,const struct vp9_extracfg * extra_cfg)865 static vpx_codec_err_t update_extra_cfg(vpx_codec_alg_priv_t *ctx,
866                                         const struct vp9_extracfg *extra_cfg) {
867   const vpx_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg);
868   if (res == VPX_CODEC_OK) {
869     ctx->extra_cfg = *extra_cfg;
870     set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
871     set_twopass_params_from_config(&ctx->cfg, ctx->cpi);
872     vp9_change_config(ctx->cpi, &ctx->oxcf);
873   }
874   return res;
875 }
876 
ctrl_set_cpuused(vpx_codec_alg_priv_t * ctx,va_list args)877 static vpx_codec_err_t ctrl_set_cpuused(vpx_codec_alg_priv_t *ctx,
878                                         va_list args) {
879   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
880   // Use fastest speed setting (speed 9 or -9) if it's set beyond the range.
881   extra_cfg.cpu_used = CAST(VP8E_SET_CPUUSED, args);
882   extra_cfg.cpu_used = VPXMIN(9, extra_cfg.cpu_used);
883   extra_cfg.cpu_used = VPXMAX(-9, extra_cfg.cpu_used);
884 #if CONFIG_REALTIME_ONLY
885   if (extra_cfg.cpu_used > -5 && extra_cfg.cpu_used < 5)
886     extra_cfg.cpu_used = (extra_cfg.cpu_used > 0) ? 5 : -5;
887 #endif
888   return update_extra_cfg(ctx, &extra_cfg);
889 }
890 
ctrl_set_enable_auto_alt_ref(vpx_codec_alg_priv_t * ctx,va_list args)891 static vpx_codec_err_t ctrl_set_enable_auto_alt_ref(vpx_codec_alg_priv_t *ctx,
892                                                     va_list args) {
893   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
894   extra_cfg.enable_auto_alt_ref = CAST(VP8E_SET_ENABLEAUTOALTREF, args);
895   return update_extra_cfg(ctx, &extra_cfg);
896 }
897 
ctrl_set_noise_sensitivity(vpx_codec_alg_priv_t * ctx,va_list args)898 static vpx_codec_err_t ctrl_set_noise_sensitivity(vpx_codec_alg_priv_t *ctx,
899                                                   va_list args) {
900   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
901   extra_cfg.noise_sensitivity = CAST(VP9E_SET_NOISE_SENSITIVITY, args);
902   return update_extra_cfg(ctx, &extra_cfg);
903 }
904 
ctrl_set_sharpness(vpx_codec_alg_priv_t * ctx,va_list args)905 static vpx_codec_err_t ctrl_set_sharpness(vpx_codec_alg_priv_t *ctx,
906                                           va_list args) {
907   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
908   extra_cfg.sharpness = CAST(VP8E_SET_SHARPNESS, args);
909   return update_extra_cfg(ctx, &extra_cfg);
910 }
911 
ctrl_set_static_thresh(vpx_codec_alg_priv_t * ctx,va_list args)912 static vpx_codec_err_t ctrl_set_static_thresh(vpx_codec_alg_priv_t *ctx,
913                                               va_list args) {
914   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
915   extra_cfg.static_thresh = CAST(VP8E_SET_STATIC_THRESHOLD, args);
916   return update_extra_cfg(ctx, &extra_cfg);
917 }
918 
ctrl_set_tile_columns(vpx_codec_alg_priv_t * ctx,va_list args)919 static vpx_codec_err_t ctrl_set_tile_columns(vpx_codec_alg_priv_t *ctx,
920                                              va_list args) {
921   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
922   extra_cfg.tile_columns = CAST(VP9E_SET_TILE_COLUMNS, args);
923   return update_extra_cfg(ctx, &extra_cfg);
924 }
925 
ctrl_set_tile_rows(vpx_codec_alg_priv_t * ctx,va_list args)926 static vpx_codec_err_t ctrl_set_tile_rows(vpx_codec_alg_priv_t *ctx,
927                                           va_list args) {
928   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
929   extra_cfg.tile_rows = CAST(VP9E_SET_TILE_ROWS, args);
930   return update_extra_cfg(ctx, &extra_cfg);
931 }
932 
ctrl_set_tpl_model(vpx_codec_alg_priv_t * ctx,va_list args)933 static vpx_codec_err_t ctrl_set_tpl_model(vpx_codec_alg_priv_t *ctx,
934                                           va_list args) {
935   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
936   extra_cfg.enable_tpl_model = CAST(VP9E_SET_TPL, args);
937   return update_extra_cfg(ctx, &extra_cfg);
938 }
939 
ctrl_set_arnr_max_frames(vpx_codec_alg_priv_t * ctx,va_list args)940 static vpx_codec_err_t ctrl_set_arnr_max_frames(vpx_codec_alg_priv_t *ctx,
941                                                 va_list args) {
942   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
943   extra_cfg.arnr_max_frames = CAST(VP8E_SET_ARNR_MAXFRAMES, args);
944   return update_extra_cfg(ctx, &extra_cfg);
945 }
946 
ctrl_set_arnr_strength(vpx_codec_alg_priv_t * ctx,va_list args)947 static vpx_codec_err_t ctrl_set_arnr_strength(vpx_codec_alg_priv_t *ctx,
948                                               va_list args) {
949   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
950   extra_cfg.arnr_strength = CAST(VP8E_SET_ARNR_STRENGTH, args);
951   return update_extra_cfg(ctx, &extra_cfg);
952 }
953 
ctrl_set_arnr_type(vpx_codec_alg_priv_t * ctx,va_list args)954 static vpx_codec_err_t ctrl_set_arnr_type(vpx_codec_alg_priv_t *ctx,
955                                           va_list args) {
956   (void)ctx;
957   (void)args;
958   return VPX_CODEC_OK;
959 }
960 
ctrl_set_tuning(vpx_codec_alg_priv_t * ctx,va_list args)961 static vpx_codec_err_t ctrl_set_tuning(vpx_codec_alg_priv_t *ctx,
962                                        va_list args) {
963   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
964   extra_cfg.tuning = CAST(VP8E_SET_TUNING, args);
965   return update_extra_cfg(ctx, &extra_cfg);
966 }
967 
ctrl_set_cq_level(vpx_codec_alg_priv_t * ctx,va_list args)968 static vpx_codec_err_t ctrl_set_cq_level(vpx_codec_alg_priv_t *ctx,
969                                          va_list args) {
970   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
971   extra_cfg.cq_level = CAST(VP8E_SET_CQ_LEVEL, args);
972   return update_extra_cfg(ctx, &extra_cfg);
973 }
974 
ctrl_set_rc_max_intra_bitrate_pct(vpx_codec_alg_priv_t * ctx,va_list args)975 static vpx_codec_err_t ctrl_set_rc_max_intra_bitrate_pct(
976     vpx_codec_alg_priv_t *ctx, va_list args) {
977   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
978   extra_cfg.rc_max_intra_bitrate_pct =
979       CAST(VP8E_SET_MAX_INTRA_BITRATE_PCT, args);
980   return update_extra_cfg(ctx, &extra_cfg);
981 }
982 
ctrl_set_rc_max_inter_bitrate_pct(vpx_codec_alg_priv_t * ctx,va_list args)983 static vpx_codec_err_t ctrl_set_rc_max_inter_bitrate_pct(
984     vpx_codec_alg_priv_t *ctx, va_list args) {
985   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
986   extra_cfg.rc_max_inter_bitrate_pct =
987       CAST(VP9E_SET_MAX_INTER_BITRATE_PCT, args);
988   return update_extra_cfg(ctx, &extra_cfg);
989 }
990 
ctrl_set_rc_gf_cbr_boost_pct(vpx_codec_alg_priv_t * ctx,va_list args)991 static vpx_codec_err_t ctrl_set_rc_gf_cbr_boost_pct(vpx_codec_alg_priv_t *ctx,
992                                                     va_list args) {
993   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
994   extra_cfg.gf_cbr_boost_pct = CAST(VP9E_SET_GF_CBR_BOOST_PCT, args);
995   return update_extra_cfg(ctx, &extra_cfg);
996 }
997 
ctrl_set_lossless(vpx_codec_alg_priv_t * ctx,va_list args)998 static vpx_codec_err_t ctrl_set_lossless(vpx_codec_alg_priv_t *ctx,
999                                          va_list args) {
1000   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1001   extra_cfg.lossless = CAST(VP9E_SET_LOSSLESS, args);
1002   return update_extra_cfg(ctx, &extra_cfg);
1003 }
1004 
ctrl_set_frame_parallel_decoding_mode(vpx_codec_alg_priv_t * ctx,va_list args)1005 static vpx_codec_err_t ctrl_set_frame_parallel_decoding_mode(
1006     vpx_codec_alg_priv_t *ctx, va_list args) {
1007   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1008   extra_cfg.frame_parallel_decoding_mode =
1009       CAST(VP9E_SET_FRAME_PARALLEL_DECODING, args);
1010   return update_extra_cfg(ctx, &extra_cfg);
1011 }
1012 
ctrl_set_aq_mode(vpx_codec_alg_priv_t * ctx,va_list args)1013 static vpx_codec_err_t ctrl_set_aq_mode(vpx_codec_alg_priv_t *ctx,
1014                                         va_list args) {
1015   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1016   extra_cfg.aq_mode = CAST(VP9E_SET_AQ_MODE, args);
1017   if (ctx->cpi->fixed_qp_onepass) extra_cfg.aq_mode = 0;
1018   return update_extra_cfg(ctx, &extra_cfg);
1019 }
1020 
ctrl_set_alt_ref_aq(vpx_codec_alg_priv_t * ctx,va_list args)1021 static vpx_codec_err_t ctrl_set_alt_ref_aq(vpx_codec_alg_priv_t *ctx,
1022                                            va_list args) {
1023   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1024   extra_cfg.alt_ref_aq = CAST(VP9E_SET_ALT_REF_AQ, args);
1025   return update_extra_cfg(ctx, &extra_cfg);
1026 }
1027 
ctrl_set_min_gf_interval(vpx_codec_alg_priv_t * ctx,va_list args)1028 static vpx_codec_err_t ctrl_set_min_gf_interval(vpx_codec_alg_priv_t *ctx,
1029                                                 va_list args) {
1030   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1031   extra_cfg.min_gf_interval = CAST(VP9E_SET_MIN_GF_INTERVAL, args);
1032   return update_extra_cfg(ctx, &extra_cfg);
1033 }
1034 
ctrl_set_max_gf_interval(vpx_codec_alg_priv_t * ctx,va_list args)1035 static vpx_codec_err_t ctrl_set_max_gf_interval(vpx_codec_alg_priv_t *ctx,
1036                                                 va_list args) {
1037   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1038   extra_cfg.max_gf_interval = CAST(VP9E_SET_MAX_GF_INTERVAL, args);
1039   return update_extra_cfg(ctx, &extra_cfg);
1040 }
1041 
ctrl_set_frame_periodic_boost(vpx_codec_alg_priv_t * ctx,va_list args)1042 static vpx_codec_err_t ctrl_set_frame_periodic_boost(vpx_codec_alg_priv_t *ctx,
1043                                                      va_list args) {
1044   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1045   extra_cfg.frame_periodic_boost = CAST(VP9E_SET_FRAME_PERIODIC_BOOST, args);
1046   return update_extra_cfg(ctx, &extra_cfg);
1047 }
1048 
ctrl_set_target_level(vpx_codec_alg_priv_t * ctx,va_list args)1049 static vpx_codec_err_t ctrl_set_target_level(vpx_codec_alg_priv_t *ctx,
1050                                              va_list args) {
1051   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1052   extra_cfg.target_level = CAST(VP9E_SET_TARGET_LEVEL, args);
1053   return update_extra_cfg(ctx, &extra_cfg);
1054 }
1055 
ctrl_set_row_mt(vpx_codec_alg_priv_t * ctx,va_list args)1056 static vpx_codec_err_t ctrl_set_row_mt(vpx_codec_alg_priv_t *ctx,
1057                                        va_list args) {
1058   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1059   extra_cfg.row_mt = CAST(VP9E_SET_ROW_MT, args);
1060   return update_extra_cfg(ctx, &extra_cfg);
1061 }
1062 
ctrl_set_rtc_external_ratectrl(vpx_codec_alg_priv_t * ctx,va_list args)1063 static vpx_codec_err_t ctrl_set_rtc_external_ratectrl(vpx_codec_alg_priv_t *ctx,
1064                                                       va_list args) {
1065   VP9_COMP *const cpi = ctx->cpi;
1066   const unsigned int data = va_arg(args, unsigned int);
1067   if (data) {
1068     cpi->compute_frame_low_motion_onepass = 0;
1069     cpi->rc.constrain_gf_key_freq_onepass_vbr = 0;
1070     cpi->cyclic_refresh->content_mode = 0;
1071   }
1072   return VPX_CODEC_OK;
1073 }
1074 
ctrl_enable_motion_vector_unit_test(vpx_codec_alg_priv_t * ctx,va_list args)1075 static vpx_codec_err_t ctrl_enable_motion_vector_unit_test(
1076     vpx_codec_alg_priv_t *ctx, va_list args) {
1077   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1078   extra_cfg.motion_vector_unit_test =
1079       CAST(VP9E_ENABLE_MOTION_VECTOR_UNIT_TEST, args);
1080   return update_extra_cfg(ctx, &extra_cfg);
1081 }
1082 
ctrl_get_level(vpx_codec_alg_priv_t * ctx,va_list args)1083 static vpx_codec_err_t ctrl_get_level(vpx_codec_alg_priv_t *ctx, va_list args) {
1084   int *const arg = va_arg(args, int *);
1085   if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
1086   *arg = (int)vp9_get_level(&ctx->cpi->level_info.level_spec);
1087   return VPX_CODEC_OK;
1088 }
1089 
encoder_init(vpx_codec_ctx_t * ctx,vpx_codec_priv_enc_mr_cfg_t * data)1090 static vpx_codec_err_t encoder_init(vpx_codec_ctx_t *ctx,
1091                                     vpx_codec_priv_enc_mr_cfg_t *data) {
1092   vpx_codec_err_t res = VPX_CODEC_OK;
1093   (void)data;
1094 
1095   if (ctx->priv == NULL) {
1096     vpx_codec_alg_priv_t *const priv = vpx_calloc(1, sizeof(*priv));
1097     if (priv == NULL) return VPX_CODEC_MEM_ERROR;
1098 
1099     ctx->priv = (vpx_codec_priv_t *)priv;
1100     ctx->priv->init_flags = ctx->init_flags;
1101     ctx->priv->enc.total_encoders = 1;
1102     priv->buffer_pool = (BufferPool *)vpx_calloc(1, sizeof(BufferPool));
1103     if (priv->buffer_pool == NULL) return VPX_CODEC_MEM_ERROR;
1104 
1105     if (ctx->config.enc) {
1106       // Update the reference to the config structure to an internal copy.
1107       priv->cfg = *ctx->config.enc;
1108       ctx->config.enc = &priv->cfg;
1109     }
1110 
1111     priv->extra_cfg = default_extra_cfg;
1112     vp9_initialize_enc();
1113 
1114     res = validate_config(priv, &priv->cfg, &priv->extra_cfg);
1115 
1116     if (res == VPX_CODEC_OK) {
1117       priv->pts_offset_initialized = 0;
1118       // TODO(angiebird): Replace priv->timestamp_ratio by
1119       // oxcf->g_timebase_in_ts
1120       priv->timestamp_ratio = get_g_timebase_in_ts(priv->cfg.g_timebase);
1121 
1122       set_encoder_config(&priv->oxcf, &priv->cfg, &priv->extra_cfg);
1123 #if CONFIG_VP9_HIGHBITDEPTH
1124       priv->oxcf.use_highbitdepth =
1125           (ctx->init_flags & VPX_CODEC_USE_HIGHBITDEPTH) ? 1 : 0;
1126 #endif
1127       priv->cpi = vp9_create_compressor(&priv->oxcf, priv->buffer_pool);
1128       if (priv->cpi == NULL) res = VPX_CODEC_MEM_ERROR;
1129       set_twopass_params_from_config(&priv->cfg, priv->cpi);
1130     }
1131   }
1132 
1133   return res;
1134 }
1135 
encoder_destroy(vpx_codec_alg_priv_t * ctx)1136 static vpx_codec_err_t encoder_destroy(vpx_codec_alg_priv_t *ctx) {
1137   free(ctx->cx_data);
1138   vp9_remove_compressor(ctx->cpi);
1139   vpx_free(ctx->buffer_pool);
1140   vpx_free(ctx);
1141   return VPX_CODEC_OK;
1142 }
1143 
pick_quickcompress_mode(vpx_codec_alg_priv_t * ctx,unsigned long duration,unsigned long deadline)1144 static void pick_quickcompress_mode(vpx_codec_alg_priv_t *ctx,
1145                                     unsigned long duration,
1146                                     unsigned long deadline) {
1147   MODE new_mode = BEST;
1148 
1149 #if CONFIG_REALTIME_ONLY
1150   (void)duration;
1151   deadline = VPX_DL_REALTIME;
1152 #else
1153   switch (ctx->cfg.g_pass) {
1154     case VPX_RC_ONE_PASS:
1155       if (deadline > 0) {
1156         // Convert duration parameter from stream timebase to microseconds.
1157         uint64_t duration_us;
1158 
1159         VPX_STATIC_ASSERT(TICKS_PER_SEC > 1000000 &&
1160                           (TICKS_PER_SEC % 1000000) == 0);
1161 
1162         duration_us = duration * (uint64_t)ctx->timestamp_ratio.num /
1163                       (ctx->timestamp_ratio.den * (TICKS_PER_SEC / 1000000));
1164 
1165         // If the deadline is more that the duration this frame is to be shown,
1166         // use good quality mode. Otherwise use realtime mode.
1167         new_mode = (deadline > duration_us) ? GOOD : REALTIME;
1168       } else {
1169         new_mode = BEST;
1170       }
1171       break;
1172     case VPX_RC_FIRST_PASS: break;
1173     case VPX_RC_LAST_PASS: new_mode = deadline > 0 ? GOOD : BEST; break;
1174   }
1175 #endif  // CONFIG_REALTIME_ONLY
1176 
1177   if (deadline == VPX_DL_REALTIME) {
1178     ctx->oxcf.pass = 0;
1179     new_mode = REALTIME;
1180   }
1181 
1182   if (ctx->oxcf.mode != new_mode) {
1183     ctx->oxcf.mode = new_mode;
1184     vp9_change_config(ctx->cpi, &ctx->oxcf);
1185   }
1186 }
1187 
1188 // Turn on to test if supplemental superframe data breaks decoding
1189 // #define TEST_SUPPLEMENTAL_SUPERFRAME_DATA
write_superframe_index(vpx_codec_alg_priv_t * ctx)1190 static int write_superframe_index(vpx_codec_alg_priv_t *ctx) {
1191   uint8_t marker = 0xc0;
1192   unsigned int mask;
1193   int mag, index_sz;
1194 
1195   assert(ctx->pending_frame_count);
1196   assert(ctx->pending_frame_count <= 8);
1197 
1198   // Add the number of frames to the marker byte
1199   marker |= ctx->pending_frame_count - 1;
1200 
1201   // Choose the magnitude
1202   for (mag = 0, mask = 0xff; mag < 4; mag++) {
1203     if (ctx->pending_frame_magnitude < mask) break;
1204     mask <<= 8;
1205     mask |= 0xff;
1206   }
1207   marker |= mag << 3;
1208 
1209   // Write the index
1210   index_sz = 2 + (mag + 1) * ctx->pending_frame_count;
1211   if (ctx->pending_cx_data_sz + index_sz < ctx->cx_data_sz) {
1212     uint8_t *x = ctx->pending_cx_data + ctx->pending_cx_data_sz;
1213     int i, j;
1214 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
1215     uint8_t marker_test = 0xc0;
1216     int mag_test = 2;     // 1 - 4
1217     int frames_test = 4;  // 1 - 8
1218     int index_sz_test = 2 + mag_test * frames_test;
1219     marker_test |= frames_test - 1;
1220     marker_test |= (mag_test - 1) << 3;
1221     *x++ = marker_test;
1222     for (i = 0; i < mag_test * frames_test; ++i)
1223       *x++ = 0;  // fill up with arbitrary data
1224     *x++ = marker_test;
1225     ctx->pending_cx_data_sz += index_sz_test;
1226     printf("Added supplemental superframe data\n");
1227 #endif
1228 
1229     *x++ = marker;
1230     for (i = 0; i < ctx->pending_frame_count; i++) {
1231       unsigned int this_sz = (unsigned int)ctx->pending_frame_sizes[i];
1232 
1233       for (j = 0; j <= mag; j++) {
1234         *x++ = this_sz & 0xff;
1235         this_sz >>= 8;
1236       }
1237     }
1238     *x++ = marker;
1239     ctx->pending_cx_data_sz += index_sz;
1240 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
1241     index_sz += index_sz_test;
1242 #endif
1243   }
1244   return index_sz;
1245 }
1246 
get_frame_pkt_flags(const VP9_COMP * cpi,unsigned int lib_flags)1247 static vpx_codec_frame_flags_t get_frame_pkt_flags(const VP9_COMP *cpi,
1248                                                    unsigned int lib_flags) {
1249   vpx_codec_frame_flags_t flags = lib_flags << 16;
1250 
1251   if (lib_flags & FRAMEFLAGS_KEY ||
1252       (cpi->use_svc && cpi->svc
1253                            .layer_context[cpi->svc.spatial_layer_id *
1254                                               cpi->svc.number_temporal_layers +
1255                                           cpi->svc.temporal_layer_id]
1256                            .is_key_frame))
1257     flags |= VPX_FRAME_IS_KEY;
1258 
1259   if (cpi->droppable) flags |= VPX_FRAME_IS_DROPPABLE;
1260 
1261   return flags;
1262 }
1263 
get_psnr_pkt(const PSNR_STATS * psnr)1264 static INLINE vpx_codec_cx_pkt_t get_psnr_pkt(const PSNR_STATS *psnr) {
1265   vpx_codec_cx_pkt_t pkt;
1266   pkt.kind = VPX_CODEC_PSNR_PKT;
1267   pkt.data.psnr = *psnr;
1268   return pkt;
1269 }
1270 
1271 #if !CONFIG_REALTIME_ONLY
1272 static INLINE vpx_codec_cx_pkt_t
get_first_pass_stats_pkt(FIRSTPASS_STATS * stats)1273 get_first_pass_stats_pkt(FIRSTPASS_STATS *stats) {
1274   // WARNNING: This function assumes that stats will
1275   // exist and not be changed until the packet is processed
1276   // TODO(angiebird): Refactor the code to avoid using the assumption.
1277   vpx_codec_cx_pkt_t pkt;
1278   pkt.kind = VPX_CODEC_STATS_PKT;
1279   pkt.data.twopass_stats.buf = stats;
1280   pkt.data.twopass_stats.sz = sizeof(*stats);
1281   return pkt;
1282 }
1283 #endif
1284 
1285 const size_t kMinCompressedSize = 8192;
encoder_encode(vpx_codec_alg_priv_t * ctx,const vpx_image_t * img,vpx_codec_pts_t pts_val,unsigned long duration,vpx_enc_frame_flags_t enc_flags,unsigned long deadline)1286 static vpx_codec_err_t encoder_encode(vpx_codec_alg_priv_t *ctx,
1287                                       const vpx_image_t *img,
1288                                       vpx_codec_pts_t pts_val,
1289                                       unsigned long duration,
1290                                       vpx_enc_frame_flags_t enc_flags,
1291                                       unsigned long deadline) {
1292   volatile vpx_codec_err_t res = VPX_CODEC_OK;
1293   volatile vpx_enc_frame_flags_t flags = enc_flags;
1294   volatile vpx_codec_pts_t pts = pts_val;
1295   VP9_COMP *const cpi = ctx->cpi;
1296   const vpx_rational64_t *const timestamp_ratio = &ctx->timestamp_ratio;
1297   size_t data_sz;
1298   vpx_codec_cx_pkt_t pkt;
1299   memset(&pkt, 0, sizeof(pkt));
1300 
1301   if (cpi == NULL) return VPX_CODEC_INVALID_PARAM;
1302 
1303   if (img != NULL) {
1304     res = validate_img(ctx, img);
1305     if (res == VPX_CODEC_OK) {
1306       // There's no codec control for multiple alt-refs so check the encoder
1307       // instance for its status to determine the compressed data size.
1308       data_sz = ctx->cfg.g_w * ctx->cfg.g_h * get_image_bps(img) / 8 *
1309                 (cpi->multi_layer_arf ? 8 : 2);
1310       if (data_sz < kMinCompressedSize) data_sz = kMinCompressedSize;
1311       if (ctx->cx_data == NULL || ctx->cx_data_sz < data_sz) {
1312         ctx->cx_data_sz = data_sz;
1313         free(ctx->cx_data);
1314         ctx->cx_data = (unsigned char *)malloc(ctx->cx_data_sz);
1315         if (ctx->cx_data == NULL) {
1316           return VPX_CODEC_MEM_ERROR;
1317         }
1318       }
1319     }
1320   }
1321 
1322   if (!ctx->pts_offset_initialized) {
1323     ctx->pts_offset = pts;
1324     ctx->pts_offset_initialized = 1;
1325   }
1326   pts -= ctx->pts_offset;
1327 
1328   pick_quickcompress_mode(ctx, duration, deadline);
1329   vpx_codec_pkt_list_init(&ctx->pkt_list);
1330 
1331   // Handle Flags
1332   if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF)) ||
1333       ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF))) {
1334     ctx->base.err_detail = "Conflicting flags.";
1335     return VPX_CODEC_INVALID_PARAM;
1336   }
1337 
1338   if (setjmp(cpi->common.error.jmp)) {
1339     cpi->common.error.setjmp = 0;
1340     res = update_error_state(ctx, &cpi->common.error);
1341     vpx_clear_system_state();
1342     return res;
1343   }
1344   cpi->common.error.setjmp = 1;
1345 
1346   if (res == VPX_CODEC_OK) vp9_apply_encoding_flags(cpi, flags);
1347 
1348   // Handle fixed keyframe intervals
1349   if (ctx->cfg.kf_mode == VPX_KF_AUTO &&
1350       ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
1351     if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
1352       flags |= VPX_EFLAG_FORCE_KF;
1353       ctx->fixed_kf_cntr = 1;
1354     }
1355   }
1356 
1357   if (res == VPX_CODEC_OK) {
1358     unsigned int lib_flags = 0;
1359     YV12_BUFFER_CONFIG sd;
1360     int64_t dst_time_stamp = timebase_units_to_ticks(timestamp_ratio, pts);
1361     size_t size, cx_data_sz;
1362     unsigned char *cx_data;
1363 
1364     cpi->svc.timebase_fac = timebase_units_to_ticks(timestamp_ratio, 1);
1365     cpi->svc.time_stamp_superframe = dst_time_stamp;
1366 
1367     // Set up internal flags
1368     if (ctx->base.init_flags & VPX_CODEC_USE_PSNR) cpi->b_calculate_psnr = 1;
1369 
1370     if (img != NULL) {
1371       const int64_t dst_end_time_stamp =
1372           timebase_units_to_ticks(timestamp_ratio, pts + duration);
1373       res = image2yuvconfig(img, &sd);
1374 
1375       // Store the original flags in to the frame buffer. Will extract the
1376       // key frame flag when we actually encode this frame.
1377       if (vp9_receive_raw_frame(cpi, flags | ctx->next_frame_flags, &sd,
1378                                 dst_time_stamp, dst_end_time_stamp)) {
1379         res = update_error_state(ctx, &cpi->common.error);
1380       }
1381       ctx->next_frame_flags = 0;
1382     }
1383 
1384     cx_data = ctx->cx_data;
1385     cx_data_sz = ctx->cx_data_sz;
1386 
1387     /* Any pending invisible frames? */
1388     if (ctx->pending_cx_data) {
1389       memmove(cx_data, ctx->pending_cx_data, ctx->pending_cx_data_sz);
1390       ctx->pending_cx_data = cx_data;
1391       cx_data += ctx->pending_cx_data_sz;
1392       cx_data_sz -= ctx->pending_cx_data_sz;
1393 
1394       /* TODO: this is a minimal check, the underlying codec doesn't respect
1395        * the buffer size anyway.
1396        */
1397       if (cx_data_sz < ctx->cx_data_sz / 2) {
1398         vpx_internal_error(&cpi->common.error, VPX_CODEC_ERROR,
1399                            "Compressed data buffer too small");
1400         return VPX_CODEC_ERROR;
1401       }
1402     }
1403 
1404     if (cpi->oxcf.pass == 1 && !cpi->use_svc) {
1405 #if !CONFIG_REALTIME_ONLY
1406       // compute first pass stats
1407       if (img) {
1408         int ret;
1409         int64_t dst_end_time_stamp;
1410         vpx_codec_cx_pkt_t fps_pkt;
1411         ENCODE_FRAME_RESULT encode_frame_result;
1412         vp9_init_encode_frame_result(&encode_frame_result);
1413         // TODO(angiebird): Call vp9_first_pass directly
1414         ret = vp9_get_compressed_data(cpi, &lib_flags, &size, cx_data,
1415                                       &dst_time_stamp, &dst_end_time_stamp,
1416                                       !img, &encode_frame_result);
1417         assert(size == 0);  // There is no compressed data in the first pass
1418         (void)ret;
1419         assert(ret == 0);
1420         fps_pkt = get_first_pass_stats_pkt(&cpi->twopass.this_frame_stats);
1421         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &fps_pkt);
1422       } else {
1423         if (!cpi->twopass.first_pass_done) {
1424           vpx_codec_cx_pkt_t fps_pkt;
1425           vp9_end_first_pass(cpi);
1426           fps_pkt = get_first_pass_stats_pkt(&cpi->twopass.total_stats);
1427           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &fps_pkt);
1428         }
1429       }
1430 #else   // !CONFIG_REALTIME_ONLY
1431       assert(0);
1432 #endif  // !CONFIG_REALTIME_ONLY
1433     } else {
1434       ENCODE_FRAME_RESULT encode_frame_result;
1435       int64_t dst_end_time_stamp;
1436       vp9_init_encode_frame_result(&encode_frame_result);
1437       while (cx_data_sz >= ctx->cx_data_sz / 2 &&
1438              -1 != vp9_get_compressed_data(cpi, &lib_flags, &size, cx_data,
1439                                            &dst_time_stamp, &dst_end_time_stamp,
1440                                            !img, &encode_frame_result)) {
1441         // Pack psnr pkt
1442         if (size > 0 && !cpi->use_svc) {
1443           // TODO(angiebird): Figure out while we don't need psnr pkt when
1444           // use_svc is on
1445           PSNR_STATS psnr;
1446           if (vp9_get_psnr(cpi, &psnr)) {
1447             vpx_codec_cx_pkt_t psnr_pkt = get_psnr_pkt(&psnr);
1448             vpx_codec_pkt_list_add(&ctx->pkt_list.head, &psnr_pkt);
1449           }
1450         }
1451 
1452         if (size || (cpi->use_svc && cpi->svc.skip_enhancement_layer)) {
1453           // Pack invisible frames with the next visible frame
1454           if (!cpi->common.show_frame ||
1455               (cpi->use_svc && cpi->svc.spatial_layer_id <
1456                                    cpi->svc.number_spatial_layers - 1)) {
1457             if (ctx->pending_cx_data == 0) ctx->pending_cx_data = cx_data;
1458             ctx->pending_cx_data_sz += size;
1459             if (size)
1460               ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
1461             ctx->pending_frame_magnitude |= size;
1462             cx_data += size;
1463             cx_data_sz -= size;
1464             pkt.data.frame.width[cpi->svc.spatial_layer_id] = cpi->common.width;
1465             pkt.data.frame.height[cpi->svc.spatial_layer_id] =
1466                 cpi->common.height;
1467             pkt.data.frame.spatial_layer_encoded[cpi->svc.spatial_layer_id] =
1468                 1 - cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id];
1469 
1470             if (ctx->output_cx_pkt_cb.output_cx_pkt) {
1471               pkt.kind = VPX_CODEC_CX_FRAME_PKT;
1472               pkt.data.frame.pts =
1473                   ticks_to_timebase_units(timestamp_ratio, dst_time_stamp) +
1474                   ctx->pts_offset;
1475               pkt.data.frame.duration = (unsigned long)ticks_to_timebase_units(
1476                   timestamp_ratio, dst_end_time_stamp - dst_time_stamp);
1477               pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
1478               pkt.data.frame.buf = ctx->pending_cx_data;
1479               pkt.data.frame.sz = size;
1480               ctx->pending_cx_data = NULL;
1481               ctx->pending_cx_data_sz = 0;
1482               ctx->pending_frame_count = 0;
1483               ctx->pending_frame_magnitude = 0;
1484               ctx->output_cx_pkt_cb.output_cx_pkt(
1485                   &pkt, ctx->output_cx_pkt_cb.user_priv);
1486             }
1487             continue;
1488           }
1489 
1490           // Add the frame packet to the list of returned packets.
1491           pkt.kind = VPX_CODEC_CX_FRAME_PKT;
1492           pkt.data.frame.pts =
1493               ticks_to_timebase_units(timestamp_ratio, dst_time_stamp) +
1494               ctx->pts_offset;
1495           pkt.data.frame.duration = (unsigned long)ticks_to_timebase_units(
1496               timestamp_ratio, dst_end_time_stamp - dst_time_stamp);
1497           pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
1498           pkt.data.frame.width[cpi->svc.spatial_layer_id] = cpi->common.width;
1499           pkt.data.frame.height[cpi->svc.spatial_layer_id] = cpi->common.height;
1500           pkt.data.frame.spatial_layer_encoded[cpi->svc.spatial_layer_id] =
1501               1 - cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id];
1502 
1503           if (ctx->pending_cx_data) {
1504             if (size)
1505               ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
1506             ctx->pending_frame_magnitude |= size;
1507             ctx->pending_cx_data_sz += size;
1508             // write the superframe only for the case when
1509             if (!ctx->output_cx_pkt_cb.output_cx_pkt)
1510               size += write_superframe_index(ctx);
1511             pkt.data.frame.buf = ctx->pending_cx_data;
1512             pkt.data.frame.sz = ctx->pending_cx_data_sz;
1513             ctx->pending_cx_data = NULL;
1514             ctx->pending_cx_data_sz = 0;
1515             ctx->pending_frame_count = 0;
1516             ctx->pending_frame_magnitude = 0;
1517           } else {
1518             pkt.data.frame.buf = cx_data;
1519             pkt.data.frame.sz = size;
1520           }
1521           pkt.data.frame.partition_id = -1;
1522 
1523           if (ctx->output_cx_pkt_cb.output_cx_pkt)
1524             ctx->output_cx_pkt_cb.output_cx_pkt(
1525                 &pkt, ctx->output_cx_pkt_cb.user_priv);
1526           else
1527             vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1528 
1529           cx_data += size;
1530           cx_data_sz -= size;
1531           if (is_one_pass_svc(cpi) && (cpi->svc.spatial_layer_id ==
1532                                        cpi->svc.number_spatial_layers - 1)) {
1533             // Encoded all spatial layers; exit loop.
1534             break;
1535           }
1536         }
1537       }
1538     }
1539   }
1540 
1541   cpi->common.error.setjmp = 0;
1542   return res;
1543 }
1544 
encoder_get_cxdata(vpx_codec_alg_priv_t * ctx,vpx_codec_iter_t * iter)1545 static const vpx_codec_cx_pkt_t *encoder_get_cxdata(vpx_codec_alg_priv_t *ctx,
1546                                                     vpx_codec_iter_t *iter) {
1547   return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
1548 }
1549 
ctrl_set_reference(vpx_codec_alg_priv_t * ctx,va_list args)1550 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
1551                                           va_list args) {
1552   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1553 
1554   if (frame != NULL) {
1555     YV12_BUFFER_CONFIG sd;
1556 
1557     image2yuvconfig(&frame->img, &sd);
1558     vp9_set_reference_enc(ctx->cpi, ref_frame_to_vp9_reframe(frame->frame_type),
1559                           &sd);
1560     return VPX_CODEC_OK;
1561   }
1562   return VPX_CODEC_INVALID_PARAM;
1563 }
1564 
ctrl_copy_reference(vpx_codec_alg_priv_t * ctx,va_list args)1565 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
1566                                            va_list args) {
1567   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
1568 
1569   if (frame != NULL) {
1570     YV12_BUFFER_CONFIG sd;
1571 
1572     image2yuvconfig(&frame->img, &sd);
1573     vp9_copy_reference_enc(ctx->cpi,
1574                            ref_frame_to_vp9_reframe(frame->frame_type), &sd);
1575     return VPX_CODEC_OK;
1576   }
1577   return VPX_CODEC_INVALID_PARAM;
1578 }
1579 
ctrl_get_reference(vpx_codec_alg_priv_t * ctx,va_list args)1580 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
1581                                           va_list args) {
1582   vp9_ref_frame_t *const frame = va_arg(args, vp9_ref_frame_t *);
1583 
1584   if (frame != NULL) {
1585     const int fb_idx = ctx->cpi->common.cur_show_frame_fb_idx;
1586     YV12_BUFFER_CONFIG *fb = get_buf_frame(&ctx->cpi->common, fb_idx);
1587     if (fb == NULL) return VPX_CODEC_ERROR;
1588     yuvconfig2image(&frame->img, fb, NULL);
1589     return VPX_CODEC_OK;
1590   }
1591   return VPX_CODEC_INVALID_PARAM;
1592 }
1593 
ctrl_set_previewpp(vpx_codec_alg_priv_t * ctx,va_list args)1594 static vpx_codec_err_t ctrl_set_previewpp(vpx_codec_alg_priv_t *ctx,
1595                                           va_list args) {
1596 #if CONFIG_VP9_POSTPROC
1597   vp8_postproc_cfg_t *config = va_arg(args, vp8_postproc_cfg_t *);
1598   if (config != NULL) {
1599     ctx->preview_ppcfg = *config;
1600     return VPX_CODEC_OK;
1601   }
1602   return VPX_CODEC_INVALID_PARAM;
1603 #else
1604   (void)ctx;
1605   (void)args;
1606   return VPX_CODEC_INCAPABLE;
1607 #endif
1608 }
1609 
encoder_get_preview(vpx_codec_alg_priv_t * ctx)1610 static vpx_image_t *encoder_get_preview(vpx_codec_alg_priv_t *ctx) {
1611   YV12_BUFFER_CONFIG sd;
1612   vp9_ppflags_t flags;
1613   vp9_zero(flags);
1614 
1615   if (ctx->preview_ppcfg.post_proc_flag) {
1616     flags.post_proc_flag = ctx->preview_ppcfg.post_proc_flag;
1617     flags.deblocking_level = ctx->preview_ppcfg.deblocking_level;
1618     flags.noise_level = ctx->preview_ppcfg.noise_level;
1619   }
1620 
1621   if (vp9_get_preview_raw_frame(ctx->cpi, &sd, &flags) == 0) {
1622     yuvconfig2image(&ctx->preview_img, &sd, NULL);
1623     return &ctx->preview_img;
1624   }
1625   return NULL;
1626 }
1627 
ctrl_set_roi_map(vpx_codec_alg_priv_t * ctx,va_list args)1628 static vpx_codec_err_t ctrl_set_roi_map(vpx_codec_alg_priv_t *ctx,
1629                                         va_list args) {
1630   vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
1631 
1632   if (data) {
1633     vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
1634 
1635     if (!vp9_set_roi_map(ctx->cpi, roi->roi_map, roi->rows, roi->cols,
1636                          roi->delta_q, roi->delta_lf, roi->skip,
1637                          roi->ref_frame)) {
1638       return VPX_CODEC_OK;
1639     }
1640     return VPX_CODEC_INVALID_PARAM;
1641   }
1642   return VPX_CODEC_INVALID_PARAM;
1643 }
1644 
ctrl_set_active_map(vpx_codec_alg_priv_t * ctx,va_list args)1645 static vpx_codec_err_t ctrl_set_active_map(vpx_codec_alg_priv_t *ctx,
1646                                            va_list args) {
1647   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
1648 
1649   if (map) {
1650     if (!vp9_set_active_map(ctx->cpi, map->active_map, (int)map->rows,
1651                             (int)map->cols))
1652       return VPX_CODEC_OK;
1653 
1654     return VPX_CODEC_INVALID_PARAM;
1655   }
1656   return VPX_CODEC_INVALID_PARAM;
1657 }
1658 
ctrl_get_active_map(vpx_codec_alg_priv_t * ctx,va_list args)1659 static vpx_codec_err_t ctrl_get_active_map(vpx_codec_alg_priv_t *ctx,
1660                                            va_list args) {
1661   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
1662 
1663   if (map) {
1664     if (!vp9_get_active_map(ctx->cpi, map->active_map, (int)map->rows,
1665                             (int)map->cols))
1666       return VPX_CODEC_OK;
1667 
1668     return VPX_CODEC_INVALID_PARAM;
1669   }
1670   return VPX_CODEC_INVALID_PARAM;
1671 }
1672 
ctrl_set_scale_mode(vpx_codec_alg_priv_t * ctx,va_list args)1673 static vpx_codec_err_t ctrl_set_scale_mode(vpx_codec_alg_priv_t *ctx,
1674                                            va_list args) {
1675   vpx_scaling_mode_t *const mode = va_arg(args, vpx_scaling_mode_t *);
1676 
1677   if (mode) {
1678     const int res =
1679         vp9_set_internal_size(ctx->cpi, (VPX_SCALING)mode->h_scaling_mode,
1680                               (VPX_SCALING)mode->v_scaling_mode);
1681     return (res == 0) ? VPX_CODEC_OK : VPX_CODEC_INVALID_PARAM;
1682   }
1683   return VPX_CODEC_INVALID_PARAM;
1684 }
1685 
ctrl_set_svc(vpx_codec_alg_priv_t * ctx,va_list args)1686 static vpx_codec_err_t ctrl_set_svc(vpx_codec_alg_priv_t *ctx, va_list args) {
1687   int data = va_arg(args, int);
1688   const vpx_codec_enc_cfg_t *cfg = &ctx->cfg;
1689   // Both one-pass and two-pass RC are supported now.
1690   // User setting this has to make sure of the following.
1691   // In two-pass setting: either (but not both)
1692   //      cfg->ss_number_layers > 1, or cfg->ts_number_layers > 1
1693   // In one-pass setting:
1694   //      either or both cfg->ss_number_layers > 1, or cfg->ts_number_layers > 1
1695 
1696   vp9_set_svc(ctx->cpi, data);
1697 
1698   if (data == 1 &&
1699       (cfg->g_pass == VPX_RC_FIRST_PASS || cfg->g_pass == VPX_RC_LAST_PASS) &&
1700       cfg->ss_number_layers > 1 && cfg->ts_number_layers > 1) {
1701     return VPX_CODEC_INVALID_PARAM;
1702   }
1703 
1704   vp9_set_row_mt(ctx->cpi);
1705 
1706   return VPX_CODEC_OK;
1707 }
1708 
ctrl_set_svc_layer_id(vpx_codec_alg_priv_t * ctx,va_list args)1709 static vpx_codec_err_t ctrl_set_svc_layer_id(vpx_codec_alg_priv_t *ctx,
1710                                              va_list args) {
1711   vpx_svc_layer_id_t *const data = va_arg(args, vpx_svc_layer_id_t *);
1712   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
1713   SVC *const svc = &cpi->svc;
1714   int sl;
1715 
1716   svc->spatial_layer_to_encode = data->spatial_layer_id;
1717   svc->first_spatial_layer_to_encode = data->spatial_layer_id;
1718   // TODO(jianj): Deprecated to be removed.
1719   svc->temporal_layer_id = data->temporal_layer_id;
1720   // Allow for setting temporal layer per spatial layer for superframe.
1721   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1722     svc->temporal_layer_id_per_spatial[sl] =
1723         data->temporal_layer_id_per_spatial[sl];
1724   }
1725   // Checks on valid layer_id input.
1726   if (svc->temporal_layer_id < 0 ||
1727       svc->temporal_layer_id >= (int)ctx->cfg.ts_number_layers) {
1728     return VPX_CODEC_INVALID_PARAM;
1729   }
1730 
1731   return VPX_CODEC_OK;
1732 }
1733 
ctrl_get_svc_layer_id(vpx_codec_alg_priv_t * ctx,va_list args)1734 static vpx_codec_err_t ctrl_get_svc_layer_id(vpx_codec_alg_priv_t *ctx,
1735                                              va_list args) {
1736   vpx_svc_layer_id_t *data = va_arg(args, vpx_svc_layer_id_t *);
1737   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
1738   SVC *const svc = &cpi->svc;
1739 
1740   data->spatial_layer_id = svc->spatial_layer_id;
1741   data->temporal_layer_id = svc->temporal_layer_id;
1742 
1743   return VPX_CODEC_OK;
1744 }
1745 
ctrl_set_svc_parameters(vpx_codec_alg_priv_t * ctx,va_list args)1746 static vpx_codec_err_t ctrl_set_svc_parameters(vpx_codec_alg_priv_t *ctx,
1747                                                va_list args) {
1748   VP9_COMP *const cpi = ctx->cpi;
1749   vpx_svc_extra_cfg_t *const params = va_arg(args, vpx_svc_extra_cfg_t *);
1750   int sl, tl;
1751 
1752   // Number of temporal layers and number of spatial layers have to be set
1753   // properly before calling this control function.
1754   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1755     for (tl = 0; tl < cpi->svc.number_temporal_layers; ++tl) {
1756       const int layer =
1757           LAYER_IDS_TO_IDX(sl, tl, cpi->svc.number_temporal_layers);
1758       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1759       lc->max_q = params->max_quantizers[layer];
1760       lc->min_q = params->min_quantizers[layer];
1761       lc->scaling_factor_num = params->scaling_factor_num[sl];
1762       lc->scaling_factor_den = params->scaling_factor_den[sl];
1763       lc->speed = params->speed_per_layer[sl];
1764       lc->loopfilter_ctrl = params->loopfilter_ctrl[sl];
1765     }
1766   }
1767 
1768   return VPX_CODEC_OK;
1769 }
1770 
ctrl_get_svc_ref_frame_config(vpx_codec_alg_priv_t * ctx,va_list args)1771 static vpx_codec_err_t ctrl_get_svc_ref_frame_config(vpx_codec_alg_priv_t *ctx,
1772                                                      va_list args) {
1773   VP9_COMP *const cpi = ctx->cpi;
1774   vpx_svc_ref_frame_config_t *data = va_arg(args, vpx_svc_ref_frame_config_t *);
1775   int sl;
1776   for (sl = 0; sl <= cpi->svc.spatial_layer_id; sl++) {
1777     data->update_buffer_slot[sl] = cpi->svc.update_buffer_slot[sl];
1778     data->reference_last[sl] = cpi->svc.reference_last[sl];
1779     data->reference_golden[sl] = cpi->svc.reference_golden[sl];
1780     data->reference_alt_ref[sl] = cpi->svc.reference_altref[sl];
1781     data->lst_fb_idx[sl] = cpi->svc.lst_fb_idx[sl];
1782     data->gld_fb_idx[sl] = cpi->svc.gld_fb_idx[sl];
1783     data->alt_fb_idx[sl] = cpi->svc.alt_fb_idx[sl];
1784     // TODO(jianj): Remove these 3, deprecated.
1785     data->update_last[sl] = cpi->svc.update_last[sl];
1786     data->update_golden[sl] = cpi->svc.update_golden[sl];
1787     data->update_alt_ref[sl] = cpi->svc.update_altref[sl];
1788   }
1789   return VPX_CODEC_OK;
1790 }
1791 
ctrl_set_svc_ref_frame_config(vpx_codec_alg_priv_t * ctx,va_list args)1792 static vpx_codec_err_t ctrl_set_svc_ref_frame_config(vpx_codec_alg_priv_t *ctx,
1793                                                      va_list args) {
1794   VP9_COMP *const cpi = ctx->cpi;
1795   vpx_svc_ref_frame_config_t *data = va_arg(args, vpx_svc_ref_frame_config_t *);
1796   int sl;
1797   cpi->svc.use_set_ref_frame_config = 1;
1798   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1799     cpi->svc.update_buffer_slot[sl] = data->update_buffer_slot[sl];
1800     cpi->svc.reference_last[sl] = data->reference_last[sl];
1801     cpi->svc.reference_golden[sl] = data->reference_golden[sl];
1802     cpi->svc.reference_altref[sl] = data->reference_alt_ref[sl];
1803     cpi->svc.lst_fb_idx[sl] = data->lst_fb_idx[sl];
1804     cpi->svc.gld_fb_idx[sl] = data->gld_fb_idx[sl];
1805     cpi->svc.alt_fb_idx[sl] = data->alt_fb_idx[sl];
1806     cpi->svc.duration[sl] = data->duration[sl];
1807   }
1808   return VPX_CODEC_OK;
1809 }
1810 
ctrl_set_svc_inter_layer_pred(vpx_codec_alg_priv_t * ctx,va_list args)1811 static vpx_codec_err_t ctrl_set_svc_inter_layer_pred(vpx_codec_alg_priv_t *ctx,
1812                                                      va_list args) {
1813   const int data = va_arg(args, int);
1814   VP9_COMP *const cpi = ctx->cpi;
1815   cpi->svc.disable_inter_layer_pred = data;
1816   return VPX_CODEC_OK;
1817 }
1818 
ctrl_set_svc_frame_drop_layer(vpx_codec_alg_priv_t * ctx,va_list args)1819 static vpx_codec_err_t ctrl_set_svc_frame_drop_layer(vpx_codec_alg_priv_t *ctx,
1820                                                      va_list args) {
1821   VP9_COMP *const cpi = ctx->cpi;
1822   vpx_svc_frame_drop_t *data = va_arg(args, vpx_svc_frame_drop_t *);
1823   int sl;
1824   cpi->svc.framedrop_mode = data->framedrop_mode;
1825   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl)
1826     cpi->svc.framedrop_thresh[sl] = data->framedrop_thresh[sl];
1827   // Don't allow max_consec_drop values below 1.
1828   cpi->svc.max_consec_drop = VPXMAX(1, data->max_consec_drop);
1829   return VPX_CODEC_OK;
1830 }
1831 
ctrl_set_svc_gf_temporal_ref(vpx_codec_alg_priv_t * ctx,va_list args)1832 static vpx_codec_err_t ctrl_set_svc_gf_temporal_ref(vpx_codec_alg_priv_t *ctx,
1833                                                     va_list args) {
1834   VP9_COMP *const cpi = ctx->cpi;
1835   const unsigned int data = va_arg(args, unsigned int);
1836   cpi->svc.use_gf_temporal_ref = data;
1837   return VPX_CODEC_OK;
1838 }
1839 
ctrl_set_svc_spatial_layer_sync(vpx_codec_alg_priv_t * ctx,va_list args)1840 static vpx_codec_err_t ctrl_set_svc_spatial_layer_sync(
1841     vpx_codec_alg_priv_t *ctx, va_list args) {
1842   VP9_COMP *const cpi = ctx->cpi;
1843   vpx_svc_spatial_layer_sync_t *data =
1844       va_arg(args, vpx_svc_spatial_layer_sync_t *);
1845   int sl;
1846   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl)
1847     cpi->svc.spatial_layer_sync[sl] = data->spatial_layer_sync[sl];
1848   cpi->svc.set_intra_only_frame = data->base_layer_intra_only;
1849   return VPX_CODEC_OK;
1850 }
1851 
ctrl_set_delta_q_uv(vpx_codec_alg_priv_t * ctx,va_list args)1852 static vpx_codec_err_t ctrl_set_delta_q_uv(vpx_codec_alg_priv_t *ctx,
1853                                            va_list args) {
1854   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1855   int data = va_arg(args, int);
1856   data = VPXMIN(VPXMAX(data, -15), 15);
1857   extra_cfg.delta_q_uv = data;
1858   return update_extra_cfg(ctx, &extra_cfg);
1859 }
1860 
ctrl_register_cx_callback(vpx_codec_alg_priv_t * ctx,va_list args)1861 static vpx_codec_err_t ctrl_register_cx_callback(vpx_codec_alg_priv_t *ctx,
1862                                                  va_list args) {
1863   vpx_codec_priv_output_cx_pkt_cb_pair_t *cbp =
1864       (vpx_codec_priv_output_cx_pkt_cb_pair_t *)va_arg(args, void *);
1865   ctx->output_cx_pkt_cb.output_cx_pkt = cbp->output_cx_pkt;
1866   ctx->output_cx_pkt_cb.user_priv = cbp->user_priv;
1867 
1868   return VPX_CODEC_OK;
1869 }
1870 
ctrl_set_tune_content(vpx_codec_alg_priv_t * ctx,va_list args)1871 static vpx_codec_err_t ctrl_set_tune_content(vpx_codec_alg_priv_t *ctx,
1872                                              va_list args) {
1873   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1874   extra_cfg.content = CAST(VP9E_SET_TUNE_CONTENT, args);
1875   return update_extra_cfg(ctx, &extra_cfg);
1876 }
1877 
ctrl_set_color_space(vpx_codec_alg_priv_t * ctx,va_list args)1878 static vpx_codec_err_t ctrl_set_color_space(vpx_codec_alg_priv_t *ctx,
1879                                             va_list args) {
1880   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1881   extra_cfg.color_space = CAST(VP9E_SET_COLOR_SPACE, args);
1882   return update_extra_cfg(ctx, &extra_cfg);
1883 }
1884 
ctrl_set_color_range(vpx_codec_alg_priv_t * ctx,va_list args)1885 static vpx_codec_err_t ctrl_set_color_range(vpx_codec_alg_priv_t *ctx,
1886                                             va_list args) {
1887   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1888   extra_cfg.color_range = CAST(VP9E_SET_COLOR_RANGE, args);
1889   return update_extra_cfg(ctx, &extra_cfg);
1890 }
1891 
ctrl_set_render_size(vpx_codec_alg_priv_t * ctx,va_list args)1892 static vpx_codec_err_t ctrl_set_render_size(vpx_codec_alg_priv_t *ctx,
1893                                             va_list args) {
1894   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1895   int *const render_size = va_arg(args, int *);
1896   extra_cfg.render_width = render_size[0];
1897   extra_cfg.render_height = render_size[1];
1898   return update_extra_cfg(ctx, &extra_cfg);
1899 }
1900 
ctrl_set_postencode_drop(vpx_codec_alg_priv_t * ctx,va_list args)1901 static vpx_codec_err_t ctrl_set_postencode_drop(vpx_codec_alg_priv_t *ctx,
1902                                                 va_list args) {
1903   VP9_COMP *const cpi = ctx->cpi;
1904   const unsigned int data = va_arg(args, unsigned int);
1905   cpi->rc.ext_use_post_encode_drop = data;
1906   return VPX_CODEC_OK;
1907 }
1908 
ctrl_set_disable_overshoot_maxq_cbr(vpx_codec_alg_priv_t * ctx,va_list args)1909 static vpx_codec_err_t ctrl_set_disable_overshoot_maxq_cbr(
1910     vpx_codec_alg_priv_t *ctx, va_list args) {
1911   VP9_COMP *const cpi = ctx->cpi;
1912   const unsigned int data = va_arg(args, unsigned int);
1913   cpi->rc.disable_overshoot_maxq_cbr = data;
1914   return VPX_CODEC_OK;
1915 }
1916 
ctrl_set_disable_loopfilter(vpx_codec_alg_priv_t * ctx,va_list args)1917 static vpx_codec_err_t ctrl_set_disable_loopfilter(vpx_codec_alg_priv_t *ctx,
1918                                                    va_list args) {
1919   VP9_COMP *const cpi = ctx->cpi;
1920   const unsigned int data = va_arg(args, unsigned int);
1921   cpi->loopfilter_ctrl = data;
1922   return VPX_CODEC_OK;
1923 }
1924 
ctrl_set_external_rate_control(vpx_codec_alg_priv_t * ctx,va_list args)1925 static vpx_codec_err_t ctrl_set_external_rate_control(vpx_codec_alg_priv_t *ctx,
1926                                                       va_list args) {
1927   vpx_rc_funcs_t funcs = *CAST(VP9E_SET_EXTERNAL_RATE_CONTROL, args);
1928   VP9_COMP *cpi = ctx->cpi;
1929   EXT_RATECTRL *ext_ratectrl = &cpi->ext_ratectrl;
1930   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1931   // TODO(angiebird): Check the possibility of this flag being set at pass == 1
1932   if (oxcf->pass == 2) {
1933     const FRAME_INFO *frame_info = &cpi->frame_info;
1934     vpx_rc_config_t ratectrl_config;
1935     vpx_codec_err_t codec_status;
1936 
1937     ratectrl_config.frame_width = frame_info->frame_width;
1938     ratectrl_config.frame_height = frame_info->frame_height;
1939     ratectrl_config.show_frame_count = cpi->twopass.first_pass_info.num_frames;
1940 
1941     // TODO(angiebird): Double check whether this is the proper way to set up
1942     // target_bitrate and frame_rate.
1943     ratectrl_config.target_bitrate_kbps = (int)(oxcf->target_bandwidth / 1000);
1944     ratectrl_config.frame_rate_num = oxcf->g_timebase.den;
1945     ratectrl_config.frame_rate_den = oxcf->g_timebase.num;
1946 
1947     codec_status = vp9_extrc_create(funcs, ratectrl_config, ext_ratectrl);
1948     if (codec_status != VPX_CODEC_OK) {
1949       return codec_status;
1950     }
1951   }
1952   return VPX_CODEC_OK;
1953 }
1954 
ctrl_set_quantizer_one_pass(vpx_codec_alg_priv_t * ctx,va_list args)1955 static vpx_codec_err_t ctrl_set_quantizer_one_pass(vpx_codec_alg_priv_t *ctx,
1956                                                    va_list args) {
1957   VP9_COMP *const cpi = ctx->cpi;
1958   const int qp = va_arg(args, int);
1959   vpx_codec_enc_cfg_t *cfg = &ctx->cfg;
1960   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
1961   vpx_codec_err_t res;
1962 
1963   if (qp < 0 || qp > 63) return VPX_CODEC_INVALID_PARAM;
1964 
1965   cfg->rc_min_quantizer = cfg->rc_max_quantizer = qp;
1966   extra_cfg.aq_mode = 0;
1967   cpi->fixed_qp_onepass = 1;
1968 
1969   res = update_extra_cfg(ctx, &extra_cfg);
1970   return res;
1971 }
1972 
1973 static vpx_codec_ctrl_fn_map_t encoder_ctrl_maps[] = {
1974   { VP8_COPY_REFERENCE, ctrl_copy_reference },
1975 
1976   // Setters
1977   { VP8_SET_REFERENCE, ctrl_set_reference },
1978   { VP8_SET_POSTPROC, ctrl_set_previewpp },
1979   { VP9E_SET_ROI_MAP, ctrl_set_roi_map },
1980   { VP8E_SET_ACTIVEMAP, ctrl_set_active_map },
1981   { VP8E_SET_SCALEMODE, ctrl_set_scale_mode },
1982   { VP8E_SET_CPUUSED, ctrl_set_cpuused },
1983   { VP8E_SET_ENABLEAUTOALTREF, ctrl_set_enable_auto_alt_ref },
1984   { VP8E_SET_SHARPNESS, ctrl_set_sharpness },
1985   { VP8E_SET_STATIC_THRESHOLD, ctrl_set_static_thresh },
1986   { VP9E_SET_TILE_COLUMNS, ctrl_set_tile_columns },
1987   { VP9E_SET_TILE_ROWS, ctrl_set_tile_rows },
1988   { VP9E_SET_TPL, ctrl_set_tpl_model },
1989   { VP8E_SET_ARNR_MAXFRAMES, ctrl_set_arnr_max_frames },
1990   { VP8E_SET_ARNR_STRENGTH, ctrl_set_arnr_strength },
1991   { VP8E_SET_ARNR_TYPE, ctrl_set_arnr_type },
1992   { VP8E_SET_TUNING, ctrl_set_tuning },
1993   { VP8E_SET_CQ_LEVEL, ctrl_set_cq_level },
1994   { VP8E_SET_MAX_INTRA_BITRATE_PCT, ctrl_set_rc_max_intra_bitrate_pct },
1995   { VP9E_SET_MAX_INTER_BITRATE_PCT, ctrl_set_rc_max_inter_bitrate_pct },
1996   { VP9E_SET_GF_CBR_BOOST_PCT, ctrl_set_rc_gf_cbr_boost_pct },
1997   { VP9E_SET_LOSSLESS, ctrl_set_lossless },
1998   { VP9E_SET_FRAME_PARALLEL_DECODING, ctrl_set_frame_parallel_decoding_mode },
1999   { VP9E_SET_AQ_MODE, ctrl_set_aq_mode },
2000   { VP9E_SET_ALT_REF_AQ, ctrl_set_alt_ref_aq },
2001   { VP9E_SET_FRAME_PERIODIC_BOOST, ctrl_set_frame_periodic_boost },
2002   { VP9E_SET_SVC, ctrl_set_svc },
2003   { VP9E_SET_SVC_PARAMETERS, ctrl_set_svc_parameters },
2004   { VP9E_REGISTER_CX_CALLBACK, ctrl_register_cx_callback },
2005   { VP9E_SET_SVC_LAYER_ID, ctrl_set_svc_layer_id },
2006   { VP9E_SET_TUNE_CONTENT, ctrl_set_tune_content },
2007   { VP9E_SET_COLOR_SPACE, ctrl_set_color_space },
2008   { VP9E_SET_COLOR_RANGE, ctrl_set_color_range },
2009   { VP9E_SET_NOISE_SENSITIVITY, ctrl_set_noise_sensitivity },
2010   { VP9E_SET_MIN_GF_INTERVAL, ctrl_set_min_gf_interval },
2011   { VP9E_SET_MAX_GF_INTERVAL, ctrl_set_max_gf_interval },
2012   { VP9E_SET_SVC_REF_FRAME_CONFIG, ctrl_set_svc_ref_frame_config },
2013   { VP9E_SET_RENDER_SIZE, ctrl_set_render_size },
2014   { VP9E_SET_TARGET_LEVEL, ctrl_set_target_level },
2015   { VP9E_SET_ROW_MT, ctrl_set_row_mt },
2016   { VP9E_SET_POSTENCODE_DROP, ctrl_set_postencode_drop },
2017   { VP9E_SET_DISABLE_OVERSHOOT_MAXQ_CBR, ctrl_set_disable_overshoot_maxq_cbr },
2018   { VP9E_ENABLE_MOTION_VECTOR_UNIT_TEST, ctrl_enable_motion_vector_unit_test },
2019   { VP9E_SET_SVC_INTER_LAYER_PRED, ctrl_set_svc_inter_layer_pred },
2020   { VP9E_SET_SVC_FRAME_DROP_LAYER, ctrl_set_svc_frame_drop_layer },
2021   { VP9E_SET_SVC_GF_TEMPORAL_REF, ctrl_set_svc_gf_temporal_ref },
2022   { VP9E_SET_SVC_SPATIAL_LAYER_SYNC, ctrl_set_svc_spatial_layer_sync },
2023   { VP9E_SET_DELTA_Q_UV, ctrl_set_delta_q_uv },
2024   { VP9E_SET_DISABLE_LOOPFILTER, ctrl_set_disable_loopfilter },
2025   { VP9E_SET_RTC_EXTERNAL_RATECTRL, ctrl_set_rtc_external_ratectrl },
2026   { VP9E_SET_EXTERNAL_RATE_CONTROL, ctrl_set_external_rate_control },
2027   { VP9E_SET_QUANTIZER_ONE_PASS, ctrl_set_quantizer_one_pass },
2028 
2029   // Getters
2030   { VP8E_GET_LAST_QUANTIZER, ctrl_get_quantizer },
2031   { VP8E_GET_LAST_QUANTIZER_64, ctrl_get_quantizer64 },
2032   { VP9E_GET_LAST_QUANTIZER_SVC_LAYERS, ctrl_get_quantizer_svc_layers },
2033   { VP9E_GET_LOOPFILTER_LEVEL, ctrl_get_loopfilter_level },
2034   { VP9_GET_REFERENCE, ctrl_get_reference },
2035   { VP9E_GET_SVC_LAYER_ID, ctrl_get_svc_layer_id },
2036   { VP9E_GET_ACTIVEMAP, ctrl_get_active_map },
2037   { VP9E_GET_LEVEL, ctrl_get_level },
2038   { VP9E_GET_SVC_REF_FRAME_CONFIG, ctrl_get_svc_ref_frame_config },
2039 
2040   { -1, NULL },
2041 };
2042 
2043 static vpx_codec_enc_cfg_map_t encoder_usage_cfg_map[] = {
2044   { 0,
2045     {
2046         // NOLINT
2047         0,  // g_usage (unused)
2048         8,  // g_threads
2049         0,  // g_profile
2050 
2051         320,         // g_width
2052         240,         // g_height
2053         VPX_BITS_8,  // g_bit_depth
2054         8,           // g_input_bit_depth
2055 
2056         { 1, 30 },  // g_timebase
2057 
2058         0,  // g_error_resilient
2059 
2060         VPX_RC_ONE_PASS,  // g_pass
2061 
2062         25,  // g_lag_in_frames
2063 
2064         0,   // rc_dropframe_thresh
2065         0,   // rc_resize_allowed
2066         0,   // rc_scaled_width
2067         0,   // rc_scaled_height
2068         60,  // rc_resize_down_thresold
2069         30,  // rc_resize_up_thresold
2070 
2071         VPX_VBR,      // rc_end_usage
2072         { NULL, 0 },  // rc_twopass_stats_in
2073         { NULL, 0 },  // rc_firstpass_mb_stats_in
2074         256,          // rc_target_bitrate
2075         0,            // rc_min_quantizer
2076         63,           // rc_max_quantizer
2077         25,           // rc_undershoot_pct
2078         25,           // rc_overshoot_pct
2079 
2080         6000,  // rc_max_buffer_size
2081         4000,  // rc_buffer_initial_size
2082         5000,  // rc_buffer_optimal_size
2083 
2084         50,    // rc_two_pass_vbrbias
2085         0,     // rc_two_pass_vbrmin_section
2086         2000,  // rc_two_pass_vbrmax_section
2087         0,     // rc_2pass_vbr_corpus_complexity (non 0 for corpus vbr)
2088 
2089         // keyframing settings (kf)
2090         VPX_KF_AUTO,  // g_kfmode
2091         0,            // kf_min_dist
2092         128,          // kf_max_dist
2093 
2094         VPX_SS_DEFAULT_LAYERS,  // ss_number_layers
2095         { 0 },
2096         { 0 },     // ss_target_bitrate
2097         1,         // ts_number_layers
2098         { 0 },     // ts_target_bitrate
2099         { 0 },     // ts_rate_decimator
2100         0,         // ts_periodicity
2101         { 0 },     // ts_layer_id
2102         { 0 },     // layer_taget_bitrate
2103         0,         // temporal_layering_mode
2104         0,         // use_vizier_rc_params
2105         { 1, 1 },  // active_wq_factor
2106         { 1, 1 },  // err_per_mb_factor
2107         { 1, 1 },  // sr_default_decay_limit
2108         { 1, 1 },  // sr_diff_factor
2109         { 1, 1 },  // kf_err_per_mb_factor
2110         { 1, 1 },  // kf_frame_min_boost_factor
2111         { 1, 1 },  // kf_frame_max_boost_first_factor
2112         { 1, 1 },  // kf_frame_max_boost_subs_factor
2113         { 1, 1 },  // kf_max_total_boost_factor
2114         { 1, 1 },  // gf_max_total_boost_factor
2115         { 1, 1 },  // gf_frame_max_boost_factor
2116         { 1, 1 },  // zm_factor
2117         { 1, 1 },  // rd_mult_inter_qp_fac
2118         { 1, 1 },  // rd_mult_arf_qp_fac
2119         { 1, 1 },  // rd_mult_key_qp_fac
2120     } },
2121 };
2122 
2123 #ifndef VERSION_STRING
2124 #define VERSION_STRING
2125 #endif
2126 CODEC_INTERFACE(vpx_codec_vp9_cx) = {
2127   "WebM Project VP9 Encoder" VERSION_STRING,
2128   VPX_CODEC_INTERNAL_ABI_VERSION,
2129 #if CONFIG_VP9_HIGHBITDEPTH
2130   VPX_CODEC_CAP_HIGHBITDEPTH |
2131 #endif
2132       VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR,  // vpx_codec_caps_t
2133   encoder_init,                                    // vpx_codec_init_fn_t
2134   encoder_destroy,                                 // vpx_codec_destroy_fn_t
2135   encoder_ctrl_maps,                               // vpx_codec_ctrl_fn_map_t
2136   {
2137       // NOLINT
2138       NULL,  // vpx_codec_peek_si_fn_t
2139       NULL,  // vpx_codec_get_si_fn_t
2140       NULL,  // vpx_codec_decode_fn_t
2141       NULL,  // vpx_codec_frame_get_fn_t
2142       NULL   // vpx_codec_set_fb_fn_t
2143   },
2144   {
2145       // NOLINT
2146       1,                      // 1 cfg map
2147       encoder_usage_cfg_map,  // vpx_codec_enc_cfg_map_t
2148       encoder_encode,         // vpx_codec_encode_fn_t
2149       encoder_get_cxdata,     // vpx_codec_get_cx_data_fn_t
2150       encoder_set_config,     // vpx_codec_enc_config_set_fn_t
2151       NULL,                   // vpx_codec_get_global_headers_fn_t
2152       encoder_get_preview,    // vpx_codec_get_preview_frame_fn_t
2153       NULL                    // vpx_codec_enc_mr_get_mem_loc_fn_t
2154   }
2155 };
2156 
get_enc_cfg(int frame_width,int frame_height,vpx_rational_t frame_rate,int target_bitrate,vpx_enc_pass enc_pass)2157 static vpx_codec_enc_cfg_t get_enc_cfg(int frame_width, int frame_height,
2158                                        vpx_rational_t frame_rate,
2159                                        int target_bitrate,
2160                                        vpx_enc_pass enc_pass) {
2161   vpx_codec_enc_cfg_t enc_cfg = encoder_usage_cfg_map[0].cfg;
2162   enc_cfg.g_w = frame_width;
2163   enc_cfg.g_h = frame_height;
2164   enc_cfg.rc_target_bitrate = target_bitrate;
2165   enc_cfg.g_pass = enc_pass;
2166   // g_timebase is the inverse of frame_rate
2167   enc_cfg.g_timebase.num = frame_rate.den;
2168   enc_cfg.g_timebase.den = frame_rate.num;
2169   return enc_cfg;
2170 }
2171 
get_extra_cfg()2172 static vp9_extracfg get_extra_cfg() {
2173   vp9_extracfg extra_cfg = default_extra_cfg;
2174   return extra_cfg;
2175 }
2176 
vp9_get_encoder_config(int frame_width,int frame_height,vpx_rational_t frame_rate,int target_bitrate,int encode_speed,int target_level,vpx_enc_pass enc_pass)2177 VP9EncoderConfig vp9_get_encoder_config(int frame_width, int frame_height,
2178                                         vpx_rational_t frame_rate,
2179                                         int target_bitrate, int encode_speed,
2180                                         int target_level,
2181                                         vpx_enc_pass enc_pass) {
2182   /* This function will generate the same VP9EncoderConfig used by the
2183    * vpxenc command given below.
2184    * The configs in the vpxenc command corresponds to parameters of
2185    * vp9_get_encoder_config() as follows.
2186    *
2187    * WIDTH:   frame_width
2188    * HEIGHT:  frame_height
2189    * FPS:     frame_rate
2190    * BITRATE: target_bitrate
2191    * CPU_USED:encode_speed
2192    * TARGET_LEVEL: target_level
2193    *
2194    * INPUT, OUTPUT, LIMIT will not affect VP9EncoderConfig
2195    *
2196    * vpxenc command:
2197    * INPUT=bus_cif.y4m
2198    * OUTPUT=output.webm
2199    * WIDTH=352
2200    * HEIGHT=288
2201    * BITRATE=600
2202    * FPS=30/1
2203    * LIMIT=150
2204    * CPU_USED=0
2205    * TARGET_LEVEL=0
2206    * ./vpxenc --limit=$LIMIT --width=$WIDTH --height=$HEIGHT --fps=$FPS
2207    * --lag-in-frames=25 \
2208    *  --codec=vp9 --good --cpu-used=CPU_USED --threads=0 --profile=0 \
2209    *  --min-q=0 --max-q=63 --auto-alt-ref=1 --passes=2 --kf-max-dist=150 \
2210    *  --kf-min-dist=0 --drop-frame=0 --static-thresh=0 --bias-pct=50 \
2211    *  --minsection-pct=0 --maxsection-pct=150 --arnr-maxframes=7 --psnr \
2212    *  --arnr-strength=5 --sharpness=0 --undershoot-pct=100 --overshoot-pct=100 \
2213    *  --frame-parallel=0 --tile-columns=0 --cpu-used=0 --end-usage=vbr \
2214    *  --target-bitrate=$BITRATE --target-level=0 -o $OUTPUT $INPUT
2215    */
2216 
2217   VP9EncoderConfig oxcf;
2218   vp9_extracfg extra_cfg = get_extra_cfg();
2219   vpx_codec_enc_cfg_t enc_cfg = get_enc_cfg(
2220       frame_width, frame_height, frame_rate, target_bitrate, enc_pass);
2221   set_encoder_config(&oxcf, &enc_cfg, &extra_cfg);
2222 
2223   // These settings are made to match the settings of the vpxenc command.
2224   oxcf.key_freq = 150;
2225   oxcf.under_shoot_pct = 100;
2226   oxcf.over_shoot_pct = 100;
2227   oxcf.max_threads = 0;
2228   oxcf.tile_columns = 0;
2229   oxcf.frame_parallel_decoding_mode = 0;
2230   oxcf.two_pass_vbrmax_section = 150;
2231   oxcf.speed = abs(encode_speed);
2232   oxcf.target_level = target_level;
2233   return oxcf;
2234 }
2235 
2236 #define DUMP_STRUCT_VALUE(fp, structure, value) \
2237   fprintf(fp, #value " %" PRId64 "\n", (int64_t)(structure)->value)
2238 
vp9_dump_encoder_config(const VP9EncoderConfig * oxcf,FILE * fp)2239 void vp9_dump_encoder_config(const VP9EncoderConfig *oxcf, FILE *fp) {
2240   DUMP_STRUCT_VALUE(fp, oxcf, profile);
2241   DUMP_STRUCT_VALUE(fp, oxcf, bit_depth);
2242   DUMP_STRUCT_VALUE(fp, oxcf, width);
2243   DUMP_STRUCT_VALUE(fp, oxcf, height);
2244   DUMP_STRUCT_VALUE(fp, oxcf, input_bit_depth);
2245   DUMP_STRUCT_VALUE(fp, oxcf, init_framerate);
2246   // TODO(angiebird): dump g_timebase
2247   // TODO(angiebird): dump g_timebase_in_ts
2248 
2249   DUMP_STRUCT_VALUE(fp, oxcf, target_bandwidth);
2250 
2251   DUMP_STRUCT_VALUE(fp, oxcf, noise_sensitivity);
2252   DUMP_STRUCT_VALUE(fp, oxcf, sharpness);
2253   DUMP_STRUCT_VALUE(fp, oxcf, speed);
2254   DUMP_STRUCT_VALUE(fp, oxcf, rc_max_intra_bitrate_pct);
2255   DUMP_STRUCT_VALUE(fp, oxcf, rc_max_inter_bitrate_pct);
2256   DUMP_STRUCT_VALUE(fp, oxcf, gf_cbr_boost_pct);
2257 
2258   DUMP_STRUCT_VALUE(fp, oxcf, mode);
2259   DUMP_STRUCT_VALUE(fp, oxcf, pass);
2260 
2261   // Key Framing Operations
2262   DUMP_STRUCT_VALUE(fp, oxcf, auto_key);
2263   DUMP_STRUCT_VALUE(fp, oxcf, key_freq);
2264 
2265   DUMP_STRUCT_VALUE(fp, oxcf, lag_in_frames);
2266 
2267   // ----------------------------------------------------------------
2268   // DATARATE CONTROL OPTIONS
2269 
2270   // vbr, cbr, constrained quality or constant quality
2271   DUMP_STRUCT_VALUE(fp, oxcf, rc_mode);
2272 
2273   // buffer targeting aggressiveness
2274   DUMP_STRUCT_VALUE(fp, oxcf, under_shoot_pct);
2275   DUMP_STRUCT_VALUE(fp, oxcf, over_shoot_pct);
2276 
2277   // buffering parameters
2278   // TODO(angiebird): dump tarting_buffer_level_ms
2279   // TODO(angiebird): dump ptimal_buffer_level_ms
2280   // TODO(angiebird): dump maximum_buffer_size_ms
2281 
2282   // Frame drop threshold.
2283   DUMP_STRUCT_VALUE(fp, oxcf, drop_frames_water_mark);
2284 
2285   // controlling quality
2286   DUMP_STRUCT_VALUE(fp, oxcf, fixed_q);
2287   DUMP_STRUCT_VALUE(fp, oxcf, worst_allowed_q);
2288   DUMP_STRUCT_VALUE(fp, oxcf, best_allowed_q);
2289   DUMP_STRUCT_VALUE(fp, oxcf, cq_level);
2290   DUMP_STRUCT_VALUE(fp, oxcf, aq_mode);
2291 
2292   // Special handling of Adaptive Quantization for AltRef frames
2293   DUMP_STRUCT_VALUE(fp, oxcf, alt_ref_aq);
2294 
2295   // Internal frame size scaling.
2296   DUMP_STRUCT_VALUE(fp, oxcf, resize_mode);
2297   DUMP_STRUCT_VALUE(fp, oxcf, scaled_frame_width);
2298   DUMP_STRUCT_VALUE(fp, oxcf, scaled_frame_height);
2299 
2300   // Enable feature to reduce the frame quantization every x frames.
2301   DUMP_STRUCT_VALUE(fp, oxcf, frame_periodic_boost);
2302 
2303   // two pass datarate control
2304   DUMP_STRUCT_VALUE(fp, oxcf, two_pass_vbrbias);
2305   DUMP_STRUCT_VALUE(fp, oxcf, two_pass_vbrmin_section);
2306   DUMP_STRUCT_VALUE(fp, oxcf, two_pass_vbrmax_section);
2307   DUMP_STRUCT_VALUE(fp, oxcf, vbr_corpus_complexity);
2308   // END DATARATE CONTROL OPTIONS
2309   // ----------------------------------------------------------------
2310 
2311   // Spatial and temporal scalability.
2312   DUMP_STRUCT_VALUE(fp, oxcf, ss_number_layers);
2313   DUMP_STRUCT_VALUE(fp, oxcf, ts_number_layers);
2314 
2315   // Bitrate allocation for spatial layers.
2316   // TODO(angiebird): dump layer_target_bitrate[VPX_MAX_LAYERS]
2317   // TODO(angiebird): dump ss_target_bitrate[VPX_SS_MAX_LAYERS]
2318   // TODO(angiebird): dump ss_enable_auto_arf[VPX_SS_MAX_LAYERS]
2319   // TODO(angiebird): dump ts_rate_decimator[VPX_TS_MAX_LAYERS]
2320 
2321   DUMP_STRUCT_VALUE(fp, oxcf, enable_auto_arf);
2322   DUMP_STRUCT_VALUE(fp, oxcf, encode_breakout);
2323   DUMP_STRUCT_VALUE(fp, oxcf, error_resilient_mode);
2324   DUMP_STRUCT_VALUE(fp, oxcf, frame_parallel_decoding_mode);
2325 
2326   DUMP_STRUCT_VALUE(fp, oxcf, arnr_max_frames);
2327   DUMP_STRUCT_VALUE(fp, oxcf, arnr_strength);
2328 
2329   DUMP_STRUCT_VALUE(fp, oxcf, min_gf_interval);
2330   DUMP_STRUCT_VALUE(fp, oxcf, max_gf_interval);
2331 
2332   DUMP_STRUCT_VALUE(fp, oxcf, tile_columns);
2333   DUMP_STRUCT_VALUE(fp, oxcf, tile_rows);
2334 
2335   DUMP_STRUCT_VALUE(fp, oxcf, enable_tpl_model);
2336 
2337   DUMP_STRUCT_VALUE(fp, oxcf, max_threads);
2338 
2339   DUMP_STRUCT_VALUE(fp, oxcf, target_level);
2340 
2341   // TODO(angiebird): dump two_pass_stats_in
2342   DUMP_STRUCT_VALUE(fp, oxcf, tuning);
2343   DUMP_STRUCT_VALUE(fp, oxcf, content);
2344 #if CONFIG_VP9_HIGHBITDEPTH
2345   DUMP_STRUCT_VALUE(fp, oxcf, use_highbitdepth);
2346 #endif
2347   DUMP_STRUCT_VALUE(fp, oxcf, color_space);
2348   DUMP_STRUCT_VALUE(fp, oxcf, color_range);
2349   DUMP_STRUCT_VALUE(fp, oxcf, render_width);
2350   DUMP_STRUCT_VALUE(fp, oxcf, render_height);
2351   DUMP_STRUCT_VALUE(fp, oxcf, temporal_layering_mode);
2352 
2353   DUMP_STRUCT_VALUE(fp, oxcf, row_mt);
2354   DUMP_STRUCT_VALUE(fp, oxcf, motion_vector_unit_test);
2355   DUMP_STRUCT_VALUE(fp, oxcf, delta_q_uv);
2356   DUMP_STRUCT_VALUE(fp, oxcf, use_simple_encode_api);
2357 }
2358 
vp9_get_frame_info(const VP9EncoderConfig * oxcf)2359 FRAME_INFO vp9_get_frame_info(const VP9EncoderConfig *oxcf) {
2360   FRAME_INFO frame_info;
2361   int dummy;
2362   frame_info.frame_width = oxcf->width;
2363   frame_info.frame_height = oxcf->height;
2364   frame_info.render_frame_width = oxcf->width;
2365   frame_info.render_frame_height = oxcf->height;
2366   frame_info.bit_depth = oxcf->bit_depth;
2367   vp9_set_mi_size(&frame_info.mi_rows, &frame_info.mi_cols, &dummy,
2368                   frame_info.frame_width, frame_info.frame_height);
2369   vp9_set_mb_size(&frame_info.mb_rows, &frame_info.mb_cols, &frame_info.num_mbs,
2370                   frame_info.mi_rows, frame_info.mi_cols);
2371   // TODO(angiebird): Figure out how to get subsampling_x/y here
2372   return frame_info;
2373 }
2374 
vp9_set_first_pass_stats(VP9EncoderConfig * oxcf,const vpx_fixed_buf_t * stats)2375 void vp9_set_first_pass_stats(VP9EncoderConfig *oxcf,
2376                               const vpx_fixed_buf_t *stats) {
2377   oxcf->two_pass_stats_in = *stats;
2378 }
2379