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 
12 #include "./vpx_config.h"
13 #include "./vp8_rtcd.h"
14 #include "./vpx_dsp_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
16 #include "vpx/vpx_codec.h"
17 #include "vpx/internal/vpx_codec_internal.h"
18 #include "vpx_version.h"
19 #include "vpx_mem/vpx_mem.h"
20 #include "vp8/encoder/onyx_int.h"
21 #include "vpx/vp8cx.h"
22 #include "vp8/encoder/firstpass.h"
23 #include "vp8/common/onyx.h"
24 #include <stdlib.h>
25 #include <string.h>
26 
27 struct vp8_extracfg
28 {
29     struct vpx_codec_pkt_list *pkt_list;
30     int                         cpu_used;                    /** available cpu percentage in 1/16*/
31     unsigned int                enable_auto_alt_ref;           /** if encoder decides to uses alternate reference frame */
32     unsigned int                noise_sensitivity;
33     unsigned int                Sharpness;
34     unsigned int                static_thresh;
35     unsigned int                token_partitions;
36     unsigned int                arnr_max_frames;    /* alt_ref Noise Reduction Max Frame Count */
37     unsigned int                arnr_strength;    /* alt_ref Noise Reduction Strength */
38     unsigned int                arnr_type;        /* alt_ref filter type */
39     vp8e_tuning                 tuning;
40     unsigned int                cq_level;         /* constrained quality level */
41     unsigned int                rc_max_intra_bitrate_pct;
42     unsigned int                screen_content_mode;
43 
44 };
45 
46 static struct vp8_extracfg default_extracfg = {
47   NULL,
48 #if !(CONFIG_REALTIME_ONLY)
49   0,                          /* cpu_used      */
50 #else
51   4,                          /* cpu_used      */
52 #endif
53   0,                          /* enable_auto_alt_ref */
54   0,                          /* noise_sensitivity */
55   0,                          /* Sharpness */
56   0,                          /* static_thresh */
57 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
58   VP8_EIGHT_TOKENPARTITION,
59 #else
60   VP8_ONE_TOKENPARTITION,     /* token_partitions */
61 #endif
62   0,                          /* arnr_max_frames */
63   3,                          /* arnr_strength */
64   3,                          /* arnr_type*/
65   0,                          /* tuning*/
66   10,                         /* cq_level */
67   0,                          /* rc_max_intra_bitrate_pct */
68   0,                          /* screen_content_mode */
69 };
70 
71 struct vpx_codec_alg_priv
72 {
73     vpx_codec_priv_t        base;
74     vpx_codec_enc_cfg_t     cfg;
75     struct vp8_extracfg     vp8_cfg;
76     VP8_CONFIG              oxcf;
77     struct VP8_COMP        *cpi;
78     unsigned char          *cx_data;
79     unsigned int            cx_data_sz;
80     vpx_image_t             preview_img;
81     unsigned int            next_frame_flag;
82     vp8_postproc_cfg_t      preview_ppcfg;
83     /* pkt_list size depends on the maximum number of lagged frames allowed. */
84     vpx_codec_pkt_list_decl(64) pkt_list;
85     unsigned int                fixed_kf_cntr;
86     vpx_enc_frame_flags_t   control_frame_flags;
87 };
88 
89 
90 static vpx_codec_err_t
update_error_state(vpx_codec_alg_priv_t * ctx,const struct vpx_internal_error_info * error)91 update_error_state(vpx_codec_alg_priv_t                 *ctx,
92                    const struct vpx_internal_error_info *error)
93 {
94     vpx_codec_err_t res;
95 
96     if ((res = error->error_code))
97         ctx->base.err_detail = error->has_detail
98                                ? error->detail
99                                : NULL;
100 
101     return res;
102 }
103 
104 
105 #undef ERROR
106 #define ERROR(str) do {\
107         ctx->base.err_detail = str;\
108         return VPX_CODEC_INVALID_PARAM;\
109     } while(0)
110 
111 #define RANGE_CHECK(p,memb,lo,hi) do {\
112         if(!(((p)->memb == lo || (p)->memb > (lo)) && (p)->memb <= hi)) \
113             ERROR(#memb " out of range ["#lo".."#hi"]");\
114     } while(0)
115 
116 #define RANGE_CHECK_HI(p,memb,hi) do {\
117         if(!((p)->memb <= (hi))) \
118             ERROR(#memb " out of range [.."#hi"]");\
119     } while(0)
120 
121 #define RANGE_CHECK_LO(p,memb,lo) do {\
122         if(!((p)->memb >= (lo))) \
123             ERROR(#memb " out of range ["#lo"..]");\
124     } while(0)
125 
126 #define RANGE_CHECK_BOOL(p,memb) do {\
127         if(!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean");\
128     } while(0)
129 
validate_config(vpx_codec_alg_priv_t * ctx,const vpx_codec_enc_cfg_t * cfg,const struct vp8_extracfg * vp8_cfg,int finalize)130 static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t      *ctx,
131                                        const vpx_codec_enc_cfg_t *cfg,
132                                        const struct vp8_extracfg *vp8_cfg,
133                                        int                        finalize)
134 {
135     RANGE_CHECK(cfg, g_w,                   1, 16383); /* 14 bits available */
136     RANGE_CHECK(cfg, g_h,                   1, 16383); /* 14 bits available */
137     RANGE_CHECK(cfg, g_timebase.den,        1, 1000000000);
138     RANGE_CHECK(cfg, g_timebase.num,        1, 1000000000);
139     RANGE_CHECK_HI(cfg, g_profile,          3);
140     RANGE_CHECK_HI(cfg, rc_max_quantizer,   63);
141     RANGE_CHECK_HI(cfg, rc_min_quantizer,   cfg->rc_max_quantizer);
142     RANGE_CHECK_HI(cfg, g_threads,          64);
143 #if CONFIG_REALTIME_ONLY
144     RANGE_CHECK_HI(cfg, g_lag_in_frames,    0);
145 #elif CONFIG_MULTI_RES_ENCODING
146     if (ctx->base.enc.total_encoders > 1)
147         RANGE_CHECK_HI(cfg, g_lag_in_frames,    0);
148 #else
149     RANGE_CHECK_HI(cfg, g_lag_in_frames,    25);
150 #endif
151     RANGE_CHECK(cfg, rc_end_usage,          VPX_VBR, VPX_Q);
152     RANGE_CHECK_HI(cfg, rc_undershoot_pct,  1000);
153     RANGE_CHECK_HI(cfg, rc_overshoot_pct,   1000);
154     RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
155     RANGE_CHECK(cfg, kf_mode,               VPX_KF_DISABLED, VPX_KF_AUTO);
156 
157 /* TODO: add spatial re-sampling support and frame dropping in
158  * multi-res-encoder.*/
159 #if CONFIG_MULTI_RES_ENCODING
160     if (ctx->base.enc.total_encoders > 1)
161         RANGE_CHECK_HI(cfg, rc_resize_allowed,     0);
162 #else
163     RANGE_CHECK_BOOL(cfg, rc_resize_allowed);
164 #endif
165     RANGE_CHECK_HI(cfg, rc_dropframe_thresh,   100);
166     RANGE_CHECK_HI(cfg, rc_resize_up_thresh,   100);
167     RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
168 
169 #if CONFIG_REALTIME_ONLY
170     RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
171 #elif CONFIG_MULTI_RES_ENCODING
172     if (ctx->base.enc.total_encoders > 1)
173         RANGE_CHECK(cfg,    g_pass,         VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
174 #else
175     RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
176 #endif
177 
178     /* VP8 does not support a lower bound on the keyframe interval in
179      * automatic keyframe placement mode.
180      */
181     if (cfg->kf_mode != VPX_KF_DISABLED && cfg->kf_min_dist != cfg->kf_max_dist
182         && cfg->kf_min_dist > 0)
183         ERROR("kf_min_dist not supported in auto mode, use 0 "
184               "or kf_max_dist instead.");
185 
186     RANGE_CHECK_BOOL(vp8_cfg,               enable_auto_alt_ref);
187     RANGE_CHECK(vp8_cfg, cpu_used,           -16, 16);
188 
189 #if CONFIG_REALTIME_ONLY && !CONFIG_TEMPORAL_DENOISING
190     RANGE_CHECK(vp8_cfg, noise_sensitivity,  0, 0);
191 #else
192     RANGE_CHECK_HI(vp8_cfg, noise_sensitivity,  6);
193 #endif
194 
195     RANGE_CHECK(vp8_cfg, token_partitions,   VP8_ONE_TOKENPARTITION,
196                 VP8_EIGHT_TOKENPARTITION);
197     RANGE_CHECK_HI(vp8_cfg, Sharpness,       7);
198     RANGE_CHECK(vp8_cfg, arnr_max_frames, 0, 15);
199     RANGE_CHECK_HI(vp8_cfg, arnr_strength,   6);
200     RANGE_CHECK(vp8_cfg, arnr_type,       1, 3);
201     RANGE_CHECK(vp8_cfg, cq_level, 0, 63);
202     RANGE_CHECK_HI(vp8_cfg, screen_content_mode, 2);
203     if (finalize && (cfg->rc_end_usage == VPX_CQ || cfg->rc_end_usage == VPX_Q))
204         RANGE_CHECK(vp8_cfg, cq_level,
205                     cfg->rc_min_quantizer, cfg->rc_max_quantizer);
206 
207 #if !(CONFIG_REALTIME_ONLY)
208     if (cfg->g_pass == VPX_RC_LAST_PASS)
209     {
210         size_t           packet_sz = sizeof(FIRSTPASS_STATS);
211         int              n_packets = (int)(cfg->rc_twopass_stats_in.sz /
212                                           packet_sz);
213         FIRSTPASS_STATS *stats;
214 
215         if (!cfg->rc_twopass_stats_in.buf)
216             ERROR("rc_twopass_stats_in.buf not set.");
217 
218         if (cfg->rc_twopass_stats_in.sz % packet_sz)
219             ERROR("rc_twopass_stats_in.sz indicates truncated packet.");
220 
221         if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
222             ERROR("rc_twopass_stats_in requires at least two packets.");
223 
224         stats = (void*)((char *)cfg->rc_twopass_stats_in.buf
225                 + (n_packets - 1) * packet_sz);
226 
227         if ((int)(stats->count + 0.5) != n_packets - 1)
228             ERROR("rc_twopass_stats_in missing EOS stats packet");
229     }
230 #endif
231 
232     RANGE_CHECK(cfg, ts_number_layers, 1, 5);
233 
234     if (cfg->ts_number_layers > 1)
235     {
236         unsigned int i;
237         RANGE_CHECK_HI(cfg, ts_periodicity, 16);
238 
239         for (i=1; i<cfg->ts_number_layers; i++)
240             if (cfg->ts_target_bitrate[i] <= cfg->ts_target_bitrate[i-1] &&
241                 cfg->rc_target_bitrate > 0)
242                 ERROR("ts_target_bitrate entries are not strictly increasing");
243 
244         RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers-1], 1, 1);
245         for (i=cfg->ts_number_layers-2; i>0; i--)
246             if (cfg->ts_rate_decimator[i-1] != 2*cfg->ts_rate_decimator[i])
247                 ERROR("ts_rate_decimator factors are not powers of 2");
248 
249         RANGE_CHECK_HI(cfg, ts_layer_id[i], cfg->ts_number_layers-1);
250     }
251 
252 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
253     if(cfg->g_threads > (1 << vp8_cfg->token_partitions))
254         ERROR("g_threads cannot be bigger than number of token partitions");
255 #endif
256 
257     return VPX_CODEC_OK;
258 }
259 
260 
validate_img(vpx_codec_alg_priv_t * ctx,const vpx_image_t * img)261 static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
262                                     const vpx_image_t    *img)
263 {
264     switch (img->fmt)
265     {
266     case VPX_IMG_FMT_YV12:
267     case VPX_IMG_FMT_I420:
268     case VPX_IMG_FMT_VPXI420:
269     case VPX_IMG_FMT_VPXYV12:
270         break;
271     default:
272         ERROR("Invalid image format. Only YV12 and I420 images are supported");
273     }
274 
275     if ((img->d_w != ctx->cfg.g_w) || (img->d_h != ctx->cfg.g_h))
276         ERROR("Image size must match encoder init configuration size");
277 
278     return VPX_CODEC_OK;
279 }
280 
281 
set_vp8e_config(VP8_CONFIG * oxcf,vpx_codec_enc_cfg_t cfg,struct vp8_extracfg vp8_cfg,vpx_codec_priv_enc_mr_cfg_t * mr_cfg)282 static vpx_codec_err_t set_vp8e_config(VP8_CONFIG *oxcf,
283                                        vpx_codec_enc_cfg_t cfg,
284                                        struct vp8_extracfg vp8_cfg,
285                                        vpx_codec_priv_enc_mr_cfg_t *mr_cfg)
286 {
287     oxcf->multi_threaded         = cfg.g_threads;
288     oxcf->Version               = cfg.g_profile;
289 
290     oxcf->Width                 = cfg.g_w;
291     oxcf->Height                = cfg.g_h;
292     oxcf->timebase              = cfg.g_timebase;
293 
294     oxcf->error_resilient_mode = cfg.g_error_resilient;
295 
296     switch (cfg.g_pass)
297     {
298     case VPX_RC_ONE_PASS:
299         oxcf->Mode = MODE_BESTQUALITY;
300         break;
301     case VPX_RC_FIRST_PASS:
302         oxcf->Mode = MODE_FIRSTPASS;
303         break;
304     case VPX_RC_LAST_PASS:
305         oxcf->Mode = MODE_SECONDPASS_BEST;
306         break;
307     }
308 
309     if (cfg.g_pass == VPX_RC_FIRST_PASS || cfg.g_pass == VPX_RC_ONE_PASS)
310     {
311         oxcf->allow_lag     = 0;
312         oxcf->lag_in_frames = 0;
313     }
314     else
315     {
316         oxcf->allow_lag     = (cfg.g_lag_in_frames) > 0;
317         oxcf->lag_in_frames = cfg.g_lag_in_frames;
318     }
319 
320     oxcf->allow_df               = (cfg.rc_dropframe_thresh > 0);
321     oxcf->drop_frames_water_mark   = cfg.rc_dropframe_thresh;
322 
323     oxcf->allow_spatial_resampling = cfg.rc_resize_allowed;
324     oxcf->resample_up_water_mark   = cfg.rc_resize_up_thresh;
325     oxcf->resample_down_water_mark = cfg.rc_resize_down_thresh;
326 
327     if (cfg.rc_end_usage == VPX_VBR) {
328       oxcf->end_usage = USAGE_LOCAL_FILE_PLAYBACK;
329     } else if (cfg.rc_end_usage == VPX_CBR) {
330       oxcf->end_usage = USAGE_STREAM_FROM_SERVER;
331     } else if (cfg.rc_end_usage == VPX_CQ) {
332       oxcf->end_usage = USAGE_CONSTRAINED_QUALITY;
333     } else if (cfg.rc_end_usage == VPX_Q) {
334       oxcf->end_usage = USAGE_CONSTANT_QUALITY;
335     }
336 
337     oxcf->target_bandwidth         = cfg.rc_target_bitrate;
338     oxcf->rc_max_intra_bitrate_pct = vp8_cfg.rc_max_intra_bitrate_pct;
339 
340     oxcf->best_allowed_q           = cfg.rc_min_quantizer;
341     oxcf->worst_allowed_q          = cfg.rc_max_quantizer;
342     oxcf->cq_level                 = vp8_cfg.cq_level;
343     oxcf->fixed_q = -1;
344 
345     oxcf->under_shoot_pct          = cfg.rc_undershoot_pct;
346     oxcf->over_shoot_pct           = cfg.rc_overshoot_pct;
347 
348     oxcf->maximum_buffer_size_in_ms   = cfg.rc_buf_sz;
349     oxcf->starting_buffer_level_in_ms = cfg.rc_buf_initial_sz;
350     oxcf->optimal_buffer_level_in_ms  = cfg.rc_buf_optimal_sz;
351 
352     oxcf->maximum_buffer_size      = cfg.rc_buf_sz;
353     oxcf->starting_buffer_level    = cfg.rc_buf_initial_sz;
354     oxcf->optimal_buffer_level     = cfg.rc_buf_optimal_sz;
355 
356     oxcf->two_pass_vbrbias         = cfg.rc_2pass_vbr_bias_pct;
357     oxcf->two_pass_vbrmin_section  = cfg.rc_2pass_vbr_minsection_pct;
358     oxcf->two_pass_vbrmax_section  = cfg.rc_2pass_vbr_maxsection_pct;
359 
360     oxcf->auto_key                 = cfg.kf_mode == VPX_KF_AUTO
361                                        && cfg.kf_min_dist != cfg.kf_max_dist;
362     oxcf->key_freq                 = cfg.kf_max_dist;
363 
364     oxcf->number_of_layers         = cfg.ts_number_layers;
365     oxcf->periodicity              = cfg.ts_periodicity;
366 
367     if (oxcf->number_of_layers > 1)
368     {
369         memcpy (oxcf->target_bitrate, cfg.ts_target_bitrate,
370                 sizeof(cfg.ts_target_bitrate));
371         memcpy (oxcf->rate_decimator, cfg.ts_rate_decimator,
372                 sizeof(cfg.ts_rate_decimator));
373         memcpy (oxcf->layer_id, cfg.ts_layer_id, sizeof(cfg.ts_layer_id));
374     }
375 
376 #if CONFIG_MULTI_RES_ENCODING
377     /* When mr_cfg is NULL, oxcf->mr_total_resolutions and oxcf->mr_encoder_id
378      * are both memset to 0, which ensures the correct logic under this
379      * situation.
380      */
381     if(mr_cfg)
382     {
383         oxcf->mr_total_resolutions        = mr_cfg->mr_total_resolutions;
384         oxcf->mr_encoder_id               = mr_cfg->mr_encoder_id;
385         oxcf->mr_down_sampling_factor.num = mr_cfg->mr_down_sampling_factor.num;
386         oxcf->mr_down_sampling_factor.den = mr_cfg->mr_down_sampling_factor.den;
387         oxcf->mr_low_res_mode_info        = mr_cfg->mr_low_res_mode_info;
388     }
389 #else
390     (void)mr_cfg;
391 #endif
392 
393     oxcf->cpu_used               = vp8_cfg.cpu_used;
394     oxcf->encode_breakout        = vp8_cfg.static_thresh;
395     oxcf->play_alternate         = vp8_cfg.enable_auto_alt_ref;
396     oxcf->noise_sensitivity      = vp8_cfg.noise_sensitivity;
397     oxcf->Sharpness              = vp8_cfg.Sharpness;
398     oxcf->token_partitions       = vp8_cfg.token_partitions;
399 
400     oxcf->two_pass_stats_in      = cfg.rc_twopass_stats_in;
401     oxcf->output_pkt_list        = vp8_cfg.pkt_list;
402 
403     oxcf->arnr_max_frames        = vp8_cfg.arnr_max_frames;
404     oxcf->arnr_strength          = vp8_cfg.arnr_strength;
405     oxcf->arnr_type              = vp8_cfg.arnr_type;
406 
407     oxcf->tuning                 = vp8_cfg.tuning;
408 
409     oxcf->screen_content_mode    = vp8_cfg.screen_content_mode;
410 
411     /*
412         printf("Current VP8 Settings: \n");
413         printf("target_bandwidth: %d\n", oxcf->target_bandwidth);
414         printf("noise_sensitivity: %d\n", oxcf->noise_sensitivity);
415         printf("Sharpness: %d\n",    oxcf->Sharpness);
416         printf("cpu_used: %d\n",  oxcf->cpu_used);
417         printf("Mode: %d\n",     oxcf->Mode);
418         printf("auto_key: %d\n",  oxcf->auto_key);
419         printf("key_freq: %d\n", oxcf->key_freq);
420         printf("end_usage: %d\n", oxcf->end_usage);
421         printf("under_shoot_pct: %d\n", oxcf->under_shoot_pct);
422         printf("over_shoot_pct: %d\n", oxcf->over_shoot_pct);
423         printf("starting_buffer_level: %d\n", oxcf->starting_buffer_level);
424         printf("optimal_buffer_level: %d\n",  oxcf->optimal_buffer_level);
425         printf("maximum_buffer_size: %d\n", oxcf->maximum_buffer_size);
426         printf("fixed_q: %d\n",  oxcf->fixed_q);
427         printf("worst_allowed_q: %d\n", oxcf->worst_allowed_q);
428         printf("best_allowed_q: %d\n", oxcf->best_allowed_q);
429         printf("allow_spatial_resampling: %d\n",  oxcf->allow_spatial_resampling);
430         printf("resample_down_water_mark: %d\n", oxcf->resample_down_water_mark);
431         printf("resample_up_water_mark: %d\n", oxcf->resample_up_water_mark);
432         printf("allow_df: %d\n", oxcf->allow_df);
433         printf("drop_frames_water_mark: %d\n", oxcf->drop_frames_water_mark);
434         printf("two_pass_vbrbias: %d\n",  oxcf->two_pass_vbrbias);
435         printf("two_pass_vbrmin_section: %d\n", oxcf->two_pass_vbrmin_section);
436         printf("two_pass_vbrmax_section: %d\n", oxcf->two_pass_vbrmax_section);
437         printf("allow_lag: %d\n", oxcf->allow_lag);
438         printf("lag_in_frames: %d\n", oxcf->lag_in_frames);
439         printf("play_alternate: %d\n", oxcf->play_alternate);
440         printf("Version: %d\n", oxcf->Version);
441         printf("multi_threaded: %d\n",   oxcf->multi_threaded);
442         printf("encode_breakout: %d\n", oxcf->encode_breakout);
443     */
444     return VPX_CODEC_OK;
445 }
446 
vp8e_set_config(vpx_codec_alg_priv_t * ctx,const vpx_codec_enc_cfg_t * cfg)447 static vpx_codec_err_t vp8e_set_config(vpx_codec_alg_priv_t       *ctx,
448                                        const vpx_codec_enc_cfg_t  *cfg)
449 {
450     vpx_codec_err_t res;
451 
452     if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h)
453     {
454         if (cfg->g_lag_in_frames > 1 || cfg->g_pass != VPX_RC_ONE_PASS)
455             ERROR("Cannot change width or height after initialization");
456         if ((ctx->cpi->initial_width && (int)cfg->g_w > ctx->cpi->initial_width) ||
457             (ctx->cpi->initial_height && (int)cfg->g_h > ctx->cpi->initial_height))
458             ERROR("Cannot increast width or height larger than their initial values");
459     }
460 
461     /* Prevent increasing lag_in_frames. This check is stricter than it needs
462      * to be -- the limit is not increasing past the first lag_in_frames
463      * value, but we don't track the initial config, only the last successful
464      * config.
465      */
466     if ((cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames))
467         ERROR("Cannot increase lag_in_frames");
468 
469     res = validate_config(ctx, cfg, &ctx->vp8_cfg, 0);
470 
471     if (!res)
472     {
473         ctx->cfg = *cfg;
474         set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
475         vp8_change_config(ctx->cpi, &ctx->oxcf);
476     }
477 
478     return res;
479 }
480 
get_quantizer(vpx_codec_alg_priv_t * ctx,va_list args)481 static vpx_codec_err_t get_quantizer(vpx_codec_alg_priv_t *ctx, va_list args)
482 {
483   int *const arg = va_arg(args, int *);
484   if (arg == NULL)
485     return VPX_CODEC_INVALID_PARAM;
486   *arg = vp8_get_quantizer(ctx->cpi);
487   return VPX_CODEC_OK;
488 }
489 
get_quantizer64(vpx_codec_alg_priv_t * ctx,va_list args)490 static vpx_codec_err_t get_quantizer64(vpx_codec_alg_priv_t *ctx, va_list args)
491 {
492   int *const arg = va_arg(args, int *);
493   if (arg == NULL)
494     return VPX_CODEC_INVALID_PARAM;
495   *arg = vp8_reverse_trans(vp8_get_quantizer(ctx->cpi));
496   return VPX_CODEC_OK;
497 }
498 
update_extracfg(vpx_codec_alg_priv_t * ctx,const struct vp8_extracfg * extra_cfg)499 static vpx_codec_err_t update_extracfg(vpx_codec_alg_priv_t *ctx,
500                                        const struct vp8_extracfg *extra_cfg)
501 {
502   const vpx_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg, 0);
503   if (res == VPX_CODEC_OK) {
504     ctx->vp8_cfg = *extra_cfg;
505     set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
506     vp8_change_config(ctx->cpi, &ctx->oxcf);
507   }
508   return res;
509 }
510 
set_cpu_used(vpx_codec_alg_priv_t * ctx,va_list args)511 static vpx_codec_err_t set_cpu_used(vpx_codec_alg_priv_t *ctx, va_list args)
512 {
513   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
514   extra_cfg.cpu_used = CAST(VP8E_SET_CPUUSED, args);
515   return update_extracfg(ctx, &extra_cfg);
516 }
517 
set_enable_auto_alt_ref(vpx_codec_alg_priv_t * ctx,va_list args)518 static vpx_codec_err_t set_enable_auto_alt_ref(vpx_codec_alg_priv_t *ctx,
519                                                va_list args)
520 {
521   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
522   extra_cfg.enable_auto_alt_ref = CAST(VP8E_SET_ENABLEAUTOALTREF, args);
523   return update_extracfg(ctx, &extra_cfg);
524 }
525 
set_noise_sensitivity(vpx_codec_alg_priv_t * ctx,va_list args)526 static vpx_codec_err_t set_noise_sensitivity(vpx_codec_alg_priv_t *ctx,
527                                              va_list args)
528 {
529   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
530   extra_cfg.noise_sensitivity = CAST(VP8E_SET_NOISE_SENSITIVITY, args);
531   return update_extracfg(ctx, &extra_cfg);
532 }
533 
set_sharpness(vpx_codec_alg_priv_t * ctx,va_list args)534 static vpx_codec_err_t set_sharpness(vpx_codec_alg_priv_t *ctx, va_list args)
535 {
536   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
537   extra_cfg.Sharpness = CAST(VP8E_SET_SHARPNESS, args);
538   return update_extracfg(ctx, &extra_cfg);
539 }
540 
set_static_thresh(vpx_codec_alg_priv_t * ctx,va_list args)541 static vpx_codec_err_t set_static_thresh(vpx_codec_alg_priv_t *ctx,
542                                          va_list args)
543 {
544   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
545   extra_cfg.static_thresh = CAST(VP8E_SET_STATIC_THRESHOLD, args);
546   return update_extracfg(ctx, &extra_cfg);
547 }
548 
set_token_partitions(vpx_codec_alg_priv_t * ctx,va_list args)549 static vpx_codec_err_t set_token_partitions(vpx_codec_alg_priv_t *ctx,
550                                             va_list args)
551 {
552   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
553   extra_cfg.token_partitions = CAST(VP8E_SET_TOKEN_PARTITIONS, args);
554   return update_extracfg(ctx, &extra_cfg);
555 }
556 
set_arnr_max_frames(vpx_codec_alg_priv_t * ctx,va_list args)557 static vpx_codec_err_t set_arnr_max_frames(vpx_codec_alg_priv_t *ctx,
558                                            va_list args)
559 {
560   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
561   extra_cfg.arnr_max_frames = CAST(VP8E_SET_ARNR_MAXFRAMES, args);
562   return update_extracfg(ctx, &extra_cfg);
563 }
564 
set_arnr_strength(vpx_codec_alg_priv_t * ctx,va_list args)565 static vpx_codec_err_t set_arnr_strength(vpx_codec_alg_priv_t *ctx,
566                                          va_list args)
567 {
568   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
569   extra_cfg.arnr_strength = CAST(VP8E_SET_ARNR_STRENGTH, args);
570   return update_extracfg(ctx, &extra_cfg);
571 }
572 
set_arnr_type(vpx_codec_alg_priv_t * ctx,va_list args)573 static vpx_codec_err_t set_arnr_type(vpx_codec_alg_priv_t *ctx, va_list args)
574 {
575   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
576   extra_cfg.arnr_type = CAST(VP8E_SET_ARNR_TYPE, args);
577   return update_extracfg(ctx, &extra_cfg);
578 }
579 
set_tuning(vpx_codec_alg_priv_t * ctx,va_list args)580 static vpx_codec_err_t set_tuning(vpx_codec_alg_priv_t *ctx, va_list args)
581 {
582   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
583   extra_cfg.tuning = CAST(VP8E_SET_TUNING, args);
584   return update_extracfg(ctx, &extra_cfg);
585 }
586 
set_cq_level(vpx_codec_alg_priv_t * ctx,va_list args)587 static vpx_codec_err_t set_cq_level(vpx_codec_alg_priv_t *ctx, va_list args)
588 {
589   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
590   extra_cfg.cq_level = CAST(VP8E_SET_CQ_LEVEL, args);
591   return update_extracfg(ctx, &extra_cfg);
592 }
593 
set_rc_max_intra_bitrate_pct(vpx_codec_alg_priv_t * ctx,va_list args)594 static vpx_codec_err_t set_rc_max_intra_bitrate_pct(vpx_codec_alg_priv_t *ctx,
595                                                     va_list args)
596 {
597   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
598   extra_cfg.rc_max_intra_bitrate_pct =
599       CAST(VP8E_SET_MAX_INTRA_BITRATE_PCT, args);
600   return update_extracfg(ctx, &extra_cfg);
601 }
602 
set_screen_content_mode(vpx_codec_alg_priv_t * ctx,va_list args)603 static vpx_codec_err_t set_screen_content_mode(vpx_codec_alg_priv_t *ctx,
604                                                va_list args)
605 {
606   struct vp8_extracfg extra_cfg = ctx->vp8_cfg;
607   extra_cfg.screen_content_mode =
608       CAST(VP8E_SET_SCREEN_CONTENT_MODE, args);
609   return update_extracfg(ctx, &extra_cfg);
610 }
611 
vp8e_mr_alloc_mem(const vpx_codec_enc_cfg_t * cfg,void ** mem_loc)612 static vpx_codec_err_t vp8e_mr_alloc_mem(const vpx_codec_enc_cfg_t *cfg,
613                                         void **mem_loc)
614 {
615     vpx_codec_err_t res = 0;
616 
617 #if CONFIG_MULTI_RES_ENCODING
618     LOWER_RES_FRAME_INFO *shared_mem_loc;
619     int mb_rows = ((cfg->g_w + 15) >>4);
620     int mb_cols = ((cfg->g_h + 15) >>4);
621 
622     shared_mem_loc = calloc(1, sizeof(LOWER_RES_FRAME_INFO));
623     if(!shared_mem_loc)
624     {
625         res = VPX_CODEC_MEM_ERROR;
626     }
627 
628     shared_mem_loc->mb_info = calloc(mb_rows*mb_cols, sizeof(LOWER_RES_MB_INFO));
629     if(!(shared_mem_loc->mb_info))
630     {
631         res = VPX_CODEC_MEM_ERROR;
632     }
633     else
634     {
635         *mem_loc = (void *)shared_mem_loc;
636         res = VPX_CODEC_OK;
637     }
638 #else
639     (void)cfg;
640     (void)mem_loc;
641 #endif
642     return res;
643 }
644 
vp8e_init(vpx_codec_ctx_t * ctx,vpx_codec_priv_enc_mr_cfg_t * mr_cfg)645 static vpx_codec_err_t vp8e_init(vpx_codec_ctx_t *ctx,
646                                  vpx_codec_priv_enc_mr_cfg_t *mr_cfg)
647 {
648     vpx_codec_err_t        res = VPX_CODEC_OK;
649 
650 
651     vp8_rtcd();
652     vpx_dsp_rtcd();
653     vpx_scale_rtcd();
654 
655     if (!ctx->priv)
656     {
657         struct vpx_codec_alg_priv *priv =
658             (struct vpx_codec_alg_priv *)vpx_calloc(1, sizeof(*priv));
659 
660         if (!priv)
661         {
662             return VPX_CODEC_MEM_ERROR;
663         }
664 
665         ctx->priv = (vpx_codec_priv_t *)priv;
666         ctx->priv->init_flags = ctx->init_flags;
667 
668         if (ctx->config.enc)
669         {
670             /* Update the reference to the config structure to an
671              * internal copy.
672              */
673             priv->cfg = *ctx->config.enc;
674             ctx->config.enc = &priv->cfg;
675         }
676 
677         priv->vp8_cfg = default_extracfg;
678         priv->vp8_cfg.pkt_list = &priv->pkt_list.head;
679 
680         priv->cx_data_sz = priv->cfg.g_w * priv->cfg.g_h * 3 / 2 * 2;
681 
682         if (priv->cx_data_sz < 32768) priv->cx_data_sz = 32768;
683 
684         priv->cx_data = malloc(priv->cx_data_sz);
685 
686         if (!priv->cx_data)
687         {
688             return VPX_CODEC_MEM_ERROR;
689         }
690 
691         if(mr_cfg)
692             ctx->priv->enc.total_encoders   = mr_cfg->mr_total_resolutions;
693         else
694             ctx->priv->enc.total_encoders   = 1;
695 
696         res = validate_config(priv, &priv->cfg, &priv->vp8_cfg, 0);
697 
698         if (!res)
699         {
700             set_vp8e_config(&priv->oxcf, priv->cfg, priv->vp8_cfg, mr_cfg);
701             priv->cpi = vp8_create_compressor(&priv->oxcf);
702             if (!priv->cpi)
703                 res = VPX_CODEC_MEM_ERROR;
704         }
705     }
706 
707     return res;
708 }
709 
vp8e_destroy(vpx_codec_alg_priv_t * ctx)710 static vpx_codec_err_t vp8e_destroy(vpx_codec_alg_priv_t *ctx)
711 {
712 #if CONFIG_MULTI_RES_ENCODING
713     /* Free multi-encoder shared memory */
714     if (ctx->oxcf.mr_total_resolutions > 0 && (ctx->oxcf.mr_encoder_id == ctx->oxcf.mr_total_resolutions-1))
715     {
716         LOWER_RES_FRAME_INFO *shared_mem_loc = (LOWER_RES_FRAME_INFO *)ctx->oxcf.mr_low_res_mode_info;
717         free(shared_mem_loc->mb_info);
718         free(ctx->oxcf.mr_low_res_mode_info);
719     }
720 #endif
721 
722     free(ctx->cx_data);
723     vp8_remove_compressor(&ctx->cpi);
724     vpx_free(ctx);
725     return VPX_CODEC_OK;
726 }
727 
image2yuvconfig(const vpx_image_t * img,YV12_BUFFER_CONFIG * yv12)728 static vpx_codec_err_t image2yuvconfig(const vpx_image_t   *img,
729                                        YV12_BUFFER_CONFIG  *yv12)
730 {
731     const int y_w = img->d_w;
732     const int y_h = img->d_h;
733     const int uv_w = (img->d_w + 1) / 2;
734     const int uv_h = (img->d_h + 1) / 2;
735     vpx_codec_err_t        res = VPX_CODEC_OK;
736     yv12->y_buffer = img->planes[VPX_PLANE_Y];
737     yv12->u_buffer = img->planes[VPX_PLANE_U];
738     yv12->v_buffer = img->planes[VPX_PLANE_V];
739 
740     yv12->y_crop_width  = y_w;
741     yv12->y_crop_height = y_h;
742     yv12->y_width  = y_w;
743     yv12->y_height = y_h;
744     yv12->uv_crop_width = uv_w;
745     yv12->uv_crop_height = uv_h;
746     yv12->uv_width = uv_w;
747     yv12->uv_height = uv_h;
748 
749     yv12->y_stride = img->stride[VPX_PLANE_Y];
750     yv12->uv_stride = img->stride[VPX_PLANE_U];
751 
752     yv12->border  = (img->stride[VPX_PLANE_Y] - img->w) / 2;
753     return res;
754 }
755 
pick_quickcompress_mode(vpx_codec_alg_priv_t * ctx,unsigned long duration,unsigned long deadline)756 static void pick_quickcompress_mode(vpx_codec_alg_priv_t  *ctx,
757                                     unsigned long          duration,
758                                     unsigned long          deadline)
759 {
760     unsigned int new_qc;
761 
762 #if !(CONFIG_REALTIME_ONLY)
763     /* Use best quality mode if no deadline is given. */
764     new_qc = MODE_BESTQUALITY;
765 
766     if (deadline)
767     {
768         uint64_t     duration_us;
769 
770         /* Convert duration parameter from stream timebase to microseconds */
771         duration_us = (uint64_t)duration * 1000000
772                       * (uint64_t)ctx->cfg.g_timebase.num
773                       / (uint64_t)ctx->cfg.g_timebase.den;
774 
775         /* If the deadline is more that the duration this frame is to be shown,
776          * use good quality mode. Otherwise use realtime mode.
777          */
778         new_qc = (deadline > duration_us) ? MODE_GOODQUALITY : MODE_REALTIME;
779     }
780 
781 #else
782     new_qc = MODE_REALTIME;
783 #endif
784 
785     if (ctx->cfg.g_pass == VPX_RC_FIRST_PASS)
786         new_qc = MODE_FIRSTPASS;
787     else if (ctx->cfg.g_pass == VPX_RC_LAST_PASS)
788         new_qc = (new_qc == MODE_BESTQUALITY)
789                  ? MODE_SECONDPASS_BEST
790                  : MODE_SECONDPASS;
791 
792     if (ctx->oxcf.Mode != new_qc)
793     {
794         ctx->oxcf.Mode = new_qc;
795         vp8_change_config(ctx->cpi, &ctx->oxcf);
796     }
797 }
798 
set_reference_and_update(vpx_codec_alg_priv_t * ctx,int flags)799 static vpx_codec_err_t set_reference_and_update(vpx_codec_alg_priv_t *ctx,
800                                                 int flags)
801 {
802 
803     /* Handle Flags */
804     if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF))
805         || ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF)))
806     {
807         ctx->base.err_detail = "Conflicting flags.";
808         return VPX_CODEC_INVALID_PARAM;
809     }
810 
811     if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF
812                  | VP8_EFLAG_NO_REF_ARF))
813     {
814         int ref = 7;
815 
816         if (flags & VP8_EFLAG_NO_REF_LAST)
817             ref ^= VP8_LAST_FRAME;
818 
819         if (flags & VP8_EFLAG_NO_REF_GF)
820             ref ^= VP8_GOLD_FRAME;
821 
822         if (flags & VP8_EFLAG_NO_REF_ARF)
823             ref ^= VP8_ALTR_FRAME;
824 
825         vp8_use_as_reference(ctx->cpi, ref);
826     }
827 
828     if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF
829                  | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF
830                  | VP8_EFLAG_FORCE_ARF))
831     {
832         int upd = 7;
833 
834         if (flags & VP8_EFLAG_NO_UPD_LAST)
835             upd ^= VP8_LAST_FRAME;
836 
837         if (flags & VP8_EFLAG_NO_UPD_GF)
838             upd ^= VP8_GOLD_FRAME;
839 
840         if (flags & VP8_EFLAG_NO_UPD_ARF)
841             upd ^= VP8_ALTR_FRAME;
842 
843         vp8_update_reference(ctx->cpi, upd);
844     }
845 
846     if (flags & VP8_EFLAG_NO_UPD_ENTROPY)
847     {
848         vp8_update_entropy(ctx->cpi, 0);
849     }
850 
851     return VPX_CODEC_OK;
852 }
853 
vp8e_encode(vpx_codec_alg_priv_t * ctx,const vpx_image_t * img,vpx_codec_pts_t pts,unsigned long duration,vpx_enc_frame_flags_t flags,unsigned long deadline)854 static vpx_codec_err_t vp8e_encode(vpx_codec_alg_priv_t  *ctx,
855                                    const vpx_image_t     *img,
856                                    vpx_codec_pts_t        pts,
857                                    unsigned long          duration,
858                                    vpx_enc_frame_flags_t  flags,
859                                    unsigned long          deadline)
860 {
861     vpx_codec_err_t res = VPX_CODEC_OK;
862 
863     if (!ctx->cfg.rc_target_bitrate)
864         return res;
865 
866     if (img)
867         res = validate_img(ctx, img);
868 
869     if (!res)
870         res = validate_config(ctx, &ctx->cfg, &ctx->vp8_cfg, 1);
871 
872     pick_quickcompress_mode(ctx, duration, deadline);
873     vpx_codec_pkt_list_init(&ctx->pkt_list);
874 
875     // If no flags are set in the encode call, then use the frame flags as
876     // defined via the control function: vp8e_set_frame_flags.
877     if (!flags) {
878         flags = ctx->control_frame_flags;
879     }
880     ctx->control_frame_flags = 0;
881 
882     res = set_reference_and_update(ctx, flags);
883 
884     /* Handle fixed keyframe intervals */
885     if (ctx->cfg.kf_mode == VPX_KF_AUTO
886         && ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist)
887     {
888         if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist)
889         {
890             flags |= VPX_EFLAG_FORCE_KF;
891             ctx->fixed_kf_cntr = 1;
892         }
893     }
894 
895     /* Initialize the encoder instance on the first frame*/
896     if (!res && ctx->cpi)
897     {
898         unsigned int lib_flags;
899         YV12_BUFFER_CONFIG sd;
900         int64_t dst_time_stamp, dst_end_time_stamp;
901         unsigned long size, cx_data_sz;
902         unsigned char *cx_data;
903         unsigned char *cx_data_end;
904         int comp_data_state = 0;
905 
906         /* Set up internal flags */
907         if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
908             ((VP8_COMP *)ctx->cpi)->b_calculate_psnr = 1;
909 
910         if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
911             ((VP8_COMP *)ctx->cpi)->output_partition = 1;
912 
913         /* Convert API flags to internal codec lib flags */
914         lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
915 
916         /* vp8 use 10,000,000 ticks/second as time stamp */
917         dst_time_stamp    = pts * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
918         dst_end_time_stamp = (pts + duration) * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
919 
920         if (img != NULL)
921         {
922             res = image2yuvconfig(img, &sd);
923 
924             if (sd.y_width != ctx->cfg.g_w || sd.y_height != ctx->cfg.g_h) {
925                 /* from vpx_encoder.h for g_w/g_h:
926                    "Note that the frames passed as input to the encoder must have this resolution"
927                 */
928                 ctx->base.err_detail = "Invalid input frame resolution";
929                 res = VPX_CODEC_INVALID_PARAM;
930             } else {
931                 if (vp8_receive_raw_frame(ctx->cpi, ctx->next_frame_flag | lib_flags,
932                                           &sd, dst_time_stamp, dst_end_time_stamp))
933                 {
934                     VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
935                     res = update_error_state(ctx, &cpi->common.error);
936                 }
937             }
938 
939             /* reset for next frame */
940             ctx->next_frame_flag = 0;
941         }
942 
943         cx_data = ctx->cx_data;
944         cx_data_sz = ctx->cx_data_sz;
945         cx_data_end = ctx->cx_data + cx_data_sz;
946         lib_flags = 0;
947 
948         while (cx_data_sz >= ctx->cx_data_sz / 2)
949         {
950             comp_data_state = vp8_get_compressed_data(ctx->cpi,
951                                                   &lib_flags,
952                                                   &size,
953                                                   cx_data,
954                                                   cx_data_end,
955                                                   &dst_time_stamp,
956                                                   &dst_end_time_stamp,
957                                                   !img);
958 
959             if(comp_data_state == VPX_CODEC_CORRUPT_FRAME)
960                 return VPX_CODEC_CORRUPT_FRAME;
961             else if(comp_data_state == -1)
962                 break;
963 
964             if (size)
965             {
966                 vpx_codec_pts_t    round, delta;
967                 vpx_codec_cx_pkt_t pkt;
968                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
969 
970                 /* Add the frame packet to the list of returned packets. */
971                 round = (vpx_codec_pts_t)10000000
972                         * ctx->cfg.g_timebase.num / 2 - 1;
973                 delta = (dst_end_time_stamp - dst_time_stamp);
974                 pkt.kind = VPX_CODEC_CX_FRAME_PKT;
975                 pkt.data.frame.pts =
976                     (dst_time_stamp * ctx->cfg.g_timebase.den + round)
977                     / ctx->cfg.g_timebase.num / 10000000;
978                 pkt.data.frame.duration = (unsigned long)
979                     ((delta * ctx->cfg.g_timebase.den + round)
980                     / ctx->cfg.g_timebase.num / 10000000);
981                 pkt.data.frame.flags = lib_flags << 16;
982 
983                 if (lib_flags & FRAMEFLAGS_KEY)
984                     pkt.data.frame.flags |= VPX_FRAME_IS_KEY;
985 
986                 if (!cpi->common.show_frame)
987                 {
988                     pkt.data.frame.flags |= VPX_FRAME_IS_INVISIBLE;
989 
990                     /* This timestamp should be as close as possible to the
991                      * prior PTS so that if a decoder uses pts to schedule when
992                      * to do this, we start right after last frame was decoded.
993                      * Invisible frames have no duration.
994                      */
995                     pkt.data.frame.pts = ((cpi->last_time_stamp_seen
996                         * ctx->cfg.g_timebase.den + round)
997                         / ctx->cfg.g_timebase.num / 10000000) + 1;
998                     pkt.data.frame.duration = 0;
999                 }
1000 
1001                 if (cpi->droppable)
1002                     pkt.data.frame.flags |= VPX_FRAME_IS_DROPPABLE;
1003 
1004                 if (cpi->output_partition)
1005                 {
1006                     int i;
1007                     const int num_partitions =
1008                             (1 << cpi->common.multi_token_partition) + 1;
1009 
1010                     pkt.data.frame.flags |= VPX_FRAME_IS_FRAGMENT;
1011 
1012                     for (i = 0; i < num_partitions; ++i)
1013                     {
1014 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1015                         pkt.data.frame.buf = cpi->partition_d[i];
1016 #else
1017                         pkt.data.frame.buf = cx_data;
1018                         cx_data += cpi->partition_sz[i];
1019                         cx_data_sz -= cpi->partition_sz[i];
1020 #endif
1021                         pkt.data.frame.sz = cpi->partition_sz[i];
1022                         pkt.data.frame.partition_id = i;
1023                         /* don't set the fragment bit for the last partition */
1024                         if (i == (num_partitions - 1))
1025                             pkt.data.frame.flags &= ~VPX_FRAME_IS_FRAGMENT;
1026                         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1027                     }
1028 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1029                     /* In lagged mode the encoder can buffer multiple frames.
1030                      * We don't want this in partitioned output because
1031                      * partitions are spread all over the output buffer.
1032                      * So, force an exit!
1033                      */
1034                     cx_data_sz -= ctx->cx_data_sz / 2;
1035 #endif
1036                 }
1037                 else
1038                 {
1039                     pkt.data.frame.buf = cx_data;
1040                     pkt.data.frame.sz  = size;
1041                     pkt.data.frame.partition_id = -1;
1042                     vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1043                     cx_data += size;
1044                     cx_data_sz -= size;
1045                 }
1046             }
1047         }
1048     }
1049 
1050     return res;
1051 }
1052 
1053 
vp8e_get_cxdata(vpx_codec_alg_priv_t * ctx,vpx_codec_iter_t * iter)1054 static const vpx_codec_cx_pkt_t *vp8e_get_cxdata(vpx_codec_alg_priv_t  *ctx,
1055         vpx_codec_iter_t      *iter)
1056 {
1057     return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
1058 }
1059 
vp8e_set_reference(vpx_codec_alg_priv_t * ctx,va_list args)1060 static vpx_codec_err_t vp8e_set_reference(vpx_codec_alg_priv_t *ctx,
1061                                           va_list args)
1062 {
1063     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
1064 
1065     if (data)
1066     {
1067         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
1068         YV12_BUFFER_CONFIG sd;
1069 
1070         image2yuvconfig(&frame->img, &sd);
1071         vp8_set_reference(ctx->cpi, frame->frame_type, &sd);
1072         return VPX_CODEC_OK;
1073     }
1074     else
1075         return VPX_CODEC_INVALID_PARAM;
1076 
1077 }
1078 
vp8e_get_reference(vpx_codec_alg_priv_t * ctx,va_list args)1079 static vpx_codec_err_t vp8e_get_reference(vpx_codec_alg_priv_t *ctx,
1080                                           va_list args)
1081 {
1082 
1083     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
1084 
1085     if (data)
1086     {
1087         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
1088         YV12_BUFFER_CONFIG sd;
1089 
1090         image2yuvconfig(&frame->img, &sd);
1091         vp8_get_reference(ctx->cpi, frame->frame_type, &sd);
1092         return VPX_CODEC_OK;
1093     }
1094     else
1095         return VPX_CODEC_INVALID_PARAM;
1096 }
1097 
vp8e_set_previewpp(vpx_codec_alg_priv_t * ctx,va_list args)1098 static vpx_codec_err_t vp8e_set_previewpp(vpx_codec_alg_priv_t *ctx,
1099                                           va_list args)
1100 {
1101 #if CONFIG_POSTPROC
1102     vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
1103 
1104     if (data)
1105     {
1106         ctx->preview_ppcfg = *((vp8_postproc_cfg_t *)data);
1107         return VPX_CODEC_OK;
1108     }
1109     else
1110         return VPX_CODEC_INVALID_PARAM;
1111 #else
1112     (void)ctx;
1113     (void)args;
1114     return VPX_CODEC_INCAPABLE;
1115 #endif
1116 }
1117 
1118 
vp8e_get_preview(vpx_codec_alg_priv_t * ctx)1119 static vpx_image_t *vp8e_get_preview(vpx_codec_alg_priv_t *ctx)
1120 {
1121 
1122     YV12_BUFFER_CONFIG sd;
1123     vp8_ppflags_t flags = {0};
1124 
1125     if (ctx->preview_ppcfg.post_proc_flag)
1126     {
1127         flags.post_proc_flag        = ctx->preview_ppcfg.post_proc_flag;
1128         flags.deblocking_level      = ctx->preview_ppcfg.deblocking_level;
1129         flags.noise_level           = ctx->preview_ppcfg.noise_level;
1130     }
1131 
1132     if (0 == vp8_get_preview_raw_frame(ctx->cpi, &sd, &flags))
1133     {
1134 
1135         /*
1136         vpx_img_wrap(&ctx->preview_img, VPX_IMG_FMT_YV12,
1137             sd.y_width + 2*VP8BORDERINPIXELS,
1138             sd.y_height + 2*VP8BORDERINPIXELS,
1139             1,
1140             sd.buffer_alloc);
1141         vpx_img_set_rect(&ctx->preview_img,
1142             VP8BORDERINPIXELS, VP8BORDERINPIXELS,
1143             sd.y_width, sd.y_height);
1144             */
1145 
1146         ctx->preview_img.bps = 12;
1147         ctx->preview_img.planes[VPX_PLANE_Y] = sd.y_buffer;
1148         ctx->preview_img.planes[VPX_PLANE_U] = sd.u_buffer;
1149         ctx->preview_img.planes[VPX_PLANE_V] = sd.v_buffer;
1150 
1151         ctx->preview_img.fmt = VPX_IMG_FMT_I420;
1152         ctx->preview_img.x_chroma_shift = 1;
1153         ctx->preview_img.y_chroma_shift = 1;
1154 
1155         ctx->preview_img.d_w = sd.y_width;
1156         ctx->preview_img.d_h = sd.y_height;
1157         ctx->preview_img.stride[VPX_PLANE_Y] = sd.y_stride;
1158         ctx->preview_img.stride[VPX_PLANE_U] = sd.uv_stride;
1159         ctx->preview_img.stride[VPX_PLANE_V] = sd.uv_stride;
1160         ctx->preview_img.w   = sd.y_width;
1161         ctx->preview_img.h   = sd.y_height;
1162 
1163         return &ctx->preview_img;
1164     }
1165     else
1166         return NULL;
1167 }
1168 
vp8e_update_entropy(vpx_codec_alg_priv_t * ctx,va_list args)1169 static vpx_codec_err_t vp8e_update_entropy(vpx_codec_alg_priv_t *ctx,
1170                                            va_list args)
1171 {
1172     int update = va_arg(args, int);
1173     vp8_update_entropy(ctx->cpi, update);
1174     return VPX_CODEC_OK;
1175 
1176 }
1177 
vp8e_update_reference(vpx_codec_alg_priv_t * ctx,va_list args)1178 static vpx_codec_err_t vp8e_update_reference(vpx_codec_alg_priv_t *ctx,
1179                                              va_list args)
1180 {
1181     int update = va_arg(args, int);
1182     vp8_update_reference(ctx->cpi, update);
1183     return VPX_CODEC_OK;
1184 }
1185 
vp8e_use_reference(vpx_codec_alg_priv_t * ctx,va_list args)1186 static vpx_codec_err_t vp8e_use_reference(vpx_codec_alg_priv_t *ctx,
1187                                           va_list args)
1188 {
1189     int reference_flag = va_arg(args, int);
1190     vp8_use_as_reference(ctx->cpi, reference_flag);
1191     return VPX_CODEC_OK;
1192 }
1193 
vp8e_set_frame_flags(vpx_codec_alg_priv_t * ctx,va_list args)1194 static vpx_codec_err_t vp8e_set_frame_flags(vpx_codec_alg_priv_t *ctx,
1195                                             va_list args)
1196 {
1197     int frame_flags = va_arg(args, int);
1198     ctx->control_frame_flags = frame_flags;
1199     return set_reference_and_update(ctx, frame_flags);
1200 }
1201 
vp8e_set_temporal_layer_id(vpx_codec_alg_priv_t * ctx,va_list args)1202 static vpx_codec_err_t vp8e_set_temporal_layer_id(vpx_codec_alg_priv_t *ctx,
1203                                                   va_list args)
1204 {
1205     int layer_id = va_arg(args, int);
1206     if (layer_id < 0 || layer_id >= (int)ctx->cfg.ts_number_layers) {
1207       return VPX_CODEC_INVALID_PARAM;
1208     }
1209     ctx->cpi->temporal_layer_id = layer_id;
1210     return VPX_CODEC_OK;
1211 }
1212 
vp8e_set_roi_map(vpx_codec_alg_priv_t * ctx,va_list args)1213 static vpx_codec_err_t vp8e_set_roi_map(vpx_codec_alg_priv_t *ctx,
1214                                         va_list args)
1215 {
1216     vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
1217 
1218     if (data)
1219     {
1220         vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
1221 
1222         if (!vp8_set_roimap(ctx->cpi, roi->roi_map, roi->rows, roi->cols, roi->delta_q, roi->delta_lf, roi->static_threshold))
1223             return VPX_CODEC_OK;
1224         else
1225             return VPX_CODEC_INVALID_PARAM;
1226     }
1227     else
1228         return VPX_CODEC_INVALID_PARAM;
1229 }
1230 
1231 
vp8e_set_activemap(vpx_codec_alg_priv_t * ctx,va_list args)1232 static vpx_codec_err_t vp8e_set_activemap(vpx_codec_alg_priv_t *ctx,
1233                                           va_list args)
1234 {
1235     vpx_active_map_t *data = va_arg(args, vpx_active_map_t *);
1236 
1237     if (data)
1238     {
1239 
1240         vpx_active_map_t *map = (vpx_active_map_t *)data;
1241 
1242         if (!vp8_set_active_map(ctx->cpi, map->active_map, map->rows, map->cols))
1243             return VPX_CODEC_OK;
1244         else
1245             return VPX_CODEC_INVALID_PARAM;
1246     }
1247     else
1248         return VPX_CODEC_INVALID_PARAM;
1249 }
1250 
vp8e_set_scalemode(vpx_codec_alg_priv_t * ctx,va_list args)1251 static vpx_codec_err_t vp8e_set_scalemode(vpx_codec_alg_priv_t *ctx,
1252                                           va_list args)
1253 {
1254 
1255     vpx_scaling_mode_t *data =  va_arg(args, vpx_scaling_mode_t *);
1256 
1257     if (data)
1258     {
1259         int res;
1260         vpx_scaling_mode_t scalemode = *(vpx_scaling_mode_t *)data ;
1261         res = vp8_set_internal_size(ctx->cpi,
1262                                     (VPX_SCALING)scalemode.h_scaling_mode,
1263                                     (VPX_SCALING)scalemode.v_scaling_mode);
1264 
1265         if (!res)
1266         {
1267             /*force next frame a key frame to effect scaling mode */
1268             ctx->next_frame_flag |= FRAMEFLAGS_KEY;
1269             return VPX_CODEC_OK;
1270         }
1271         else
1272             return VPX_CODEC_INVALID_PARAM;
1273     }
1274     else
1275         return VPX_CODEC_INVALID_PARAM;
1276 }
1277 
1278 
1279 static vpx_codec_ctrl_fn_map_t vp8e_ctf_maps[] =
1280 {
1281     {VP8_SET_REFERENCE,                 vp8e_set_reference},
1282     {VP8_COPY_REFERENCE,                vp8e_get_reference},
1283     {VP8_SET_POSTPROC,                  vp8e_set_previewpp},
1284     {VP8E_UPD_ENTROPY,                  vp8e_update_entropy},
1285     {VP8E_UPD_REFERENCE,                vp8e_update_reference},
1286     {VP8E_USE_REFERENCE,                vp8e_use_reference},
1287     {VP8E_SET_FRAME_FLAGS,              vp8e_set_frame_flags},
1288     {VP8E_SET_TEMPORAL_LAYER_ID,        vp8e_set_temporal_layer_id},
1289     {VP8E_SET_ROI_MAP,                  vp8e_set_roi_map},
1290     {VP8E_SET_ACTIVEMAP,                vp8e_set_activemap},
1291     {VP8E_SET_SCALEMODE,                vp8e_set_scalemode},
1292     {VP8E_SET_CPUUSED,                  set_cpu_used},
1293     {VP8E_SET_NOISE_SENSITIVITY,        set_noise_sensitivity},
1294     {VP8E_SET_ENABLEAUTOALTREF,         set_enable_auto_alt_ref},
1295     {VP8E_SET_SHARPNESS,                set_sharpness},
1296     {VP8E_SET_STATIC_THRESHOLD,         set_static_thresh},
1297     {VP8E_SET_TOKEN_PARTITIONS,         set_token_partitions},
1298     {VP8E_GET_LAST_QUANTIZER,           get_quantizer},
1299     {VP8E_GET_LAST_QUANTIZER_64,        get_quantizer64},
1300     {VP8E_SET_ARNR_MAXFRAMES,           set_arnr_max_frames},
1301     {VP8E_SET_ARNR_STRENGTH ,           set_arnr_strength},
1302     {VP8E_SET_ARNR_TYPE     ,           set_arnr_type},
1303     {VP8E_SET_TUNING,                   set_tuning},
1304     {VP8E_SET_CQ_LEVEL,                 set_cq_level},
1305     {VP8E_SET_MAX_INTRA_BITRATE_PCT,    set_rc_max_intra_bitrate_pct},
1306     {VP8E_SET_SCREEN_CONTENT_MODE,      set_screen_content_mode},
1307     { -1, NULL},
1308 };
1309 
1310 static vpx_codec_enc_cfg_map_t vp8e_usage_cfg_map[] =
1311 {
1312     {
1313     0,
1314     {
1315         0,                  /* g_usage */
1316         0,                  /* g_threads */
1317         0,                  /* g_profile */
1318 
1319         320,                /* g_width */
1320         240,                /* g_height */
1321         VPX_BITS_8,         /* g_bit_depth */
1322         8,                  /* g_input_bit_depth */
1323 
1324         {1, 30},            /* g_timebase */
1325 
1326         0,                  /* g_error_resilient */
1327 
1328         VPX_RC_ONE_PASS,    /* g_pass */
1329 
1330         0,                  /* g_lag_in_frames */
1331 
1332         0,                  /* rc_dropframe_thresh */
1333         0,                  /* rc_resize_allowed */
1334         1,                  /* rc_scaled_width */
1335         1,                  /* rc_scaled_height */
1336         60,                 /* rc_resize_down_thresold */
1337         30,                 /* rc_resize_up_thresold */
1338 
1339         VPX_VBR,            /* rc_end_usage */
1340         {0},                /* rc_twopass_stats_in */
1341         {0},                /* rc_firstpass_mb_stats_in */
1342         256,                /* rc_target_bandwidth */
1343         4,                  /* rc_min_quantizer */
1344         63,                 /* rc_max_quantizer */
1345         100,                /* rc_undershoot_pct */
1346         100,                /* rc_overshoot_pct */
1347 
1348         6000,               /* rc_max_buffer_size */
1349         4000,               /* rc_buffer_initial_size; */
1350         5000,               /* rc_buffer_optimal_size; */
1351 
1352         50,                 /* rc_two_pass_vbrbias  */
1353         0,                  /* rc_two_pass_vbrmin_section */
1354         400,                /* rc_two_pass_vbrmax_section */
1355 
1356         /* keyframing settings (kf) */
1357         VPX_KF_AUTO,        /* g_kfmode*/
1358         0,                  /* kf_min_dist */
1359         128,                /* kf_max_dist */
1360 
1361         VPX_SS_DEFAULT_LAYERS, /* ss_number_layers */
1362         {0},
1363         {0},                /* ss_target_bitrate */
1364         1,                  /* ts_number_layers */
1365         {0},                /* ts_target_bitrate */
1366         {0},                /* ts_rate_decimator */
1367         0,                  /* ts_periodicity */
1368         {0},                /* ts_layer_id */
1369     }},
1370 };
1371 
1372 
1373 #ifndef VERSION_STRING
1374 #define VERSION_STRING
1375 #endif
1376 CODEC_INTERFACE(vpx_codec_vp8_cx) =
1377 {
1378     "WebM Project VP8 Encoder" VERSION_STRING,
1379     VPX_CODEC_INTERNAL_ABI_VERSION,
1380     VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR |
1381     VPX_CODEC_CAP_OUTPUT_PARTITION,
1382     /* vpx_codec_caps_t          caps; */
1383     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1384     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1385     vp8e_ctf_maps,      /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1386     {
1387         NULL,    /* vpx_codec_peek_si_fn_t    peek_si; */
1388         NULL,    /* vpx_codec_get_si_fn_t     get_si; */
1389         NULL,    /* vpx_codec_decode_fn_t     decode; */
1390         NULL,    /* vpx_codec_frame_get_fn_t  frame_get; */
1391         NULL,    /* vpx_codec_set_fb_fn_t     set_fb_fn; */
1392     },
1393     {
1394         1,                  /* 1 cfg map */
1395         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    cfg_maps; */
1396         vp8e_encode,        /* vpx_codec_encode_fn_t      encode; */
1397         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   get_cx_data; */
1398         vp8e_set_config,
1399         NULL,
1400         vp8e_get_preview,
1401         vp8e_mr_alloc_mem,
1402     } /* encoder functions */
1403 };
1404