]> granicus.if.org Git - libvpx/blob - vp8/vp8_cx_iface.c
Merge "vp8: modifcatiion to skin map computation."
[libvpx] / vp8 / vp8_cx_iface.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11
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
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
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
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
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
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 increase 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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     if (!res)
883         res = set_reference_and_update(ctx, flags);
884
885     /* Handle fixed keyframe intervals */
886     if (ctx->cfg.kf_mode == VPX_KF_AUTO
887         && ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist)
888     {
889         if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist)
890         {
891             flags |= VPX_EFLAG_FORCE_KF;
892             ctx->fixed_kf_cntr = 1;
893         }
894     }
895
896     /* Initialize the encoder instance on the first frame*/
897     if (!res && ctx->cpi)
898     {
899         unsigned int lib_flags;
900         YV12_BUFFER_CONFIG sd;
901         int64_t dst_time_stamp, dst_end_time_stamp;
902         unsigned long size, cx_data_sz;
903         unsigned char *cx_data;
904         unsigned char *cx_data_end;
905         int comp_data_state = 0;
906
907         /* Set up internal flags */
908         if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
909             ((VP8_COMP *)ctx->cpi)->b_calculate_psnr = 1;
910
911         if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
912             ((VP8_COMP *)ctx->cpi)->output_partition = 1;
913
914         /* Convert API flags to internal codec lib flags */
915         lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
916
917         /* vp8 use 10,000,000 ticks/second as time stamp */
918         dst_time_stamp    = pts * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
919         dst_end_time_stamp = (pts + duration) * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
920
921         if (img != NULL)
922         {
923             res = image2yuvconfig(img, &sd);
924
925             if (vp8_receive_raw_frame(ctx->cpi, ctx->next_frame_flag | lib_flags,
926                                       &sd, dst_time_stamp, dst_end_time_stamp))
927             {
928                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
929                 res = update_error_state(ctx, &cpi->common.error);
930             }
931
932             /* reset for next frame */
933             ctx->next_frame_flag = 0;
934         }
935
936         cx_data = ctx->cx_data;
937         cx_data_sz = ctx->cx_data_sz;
938         cx_data_end = ctx->cx_data + cx_data_sz;
939         lib_flags = 0;
940
941         while (cx_data_sz >= ctx->cx_data_sz / 2)
942         {
943             comp_data_state = vp8_get_compressed_data(ctx->cpi,
944                                                   &lib_flags,
945                                                   &size,
946                                                   cx_data,
947                                                   cx_data_end,
948                                                   &dst_time_stamp,
949                                                   &dst_end_time_stamp,
950                                                   !img);
951
952             if(comp_data_state == VPX_CODEC_CORRUPT_FRAME)
953                 return VPX_CODEC_CORRUPT_FRAME;
954             else if(comp_data_state == -1)
955                 break;
956
957             if (size)
958             {
959                 vpx_codec_pts_t    round, delta;
960                 vpx_codec_cx_pkt_t pkt;
961                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
962
963                 /* Add the frame packet to the list of returned packets. */
964                 round = (vpx_codec_pts_t)10000000
965                         * ctx->cfg.g_timebase.num / 2 - 1;
966                 delta = (dst_end_time_stamp - dst_time_stamp);
967                 pkt.kind = VPX_CODEC_CX_FRAME_PKT;
968                 pkt.data.frame.pts =
969                     (dst_time_stamp * ctx->cfg.g_timebase.den + round)
970                     / ctx->cfg.g_timebase.num / 10000000;
971                 pkt.data.frame.duration = (unsigned long)
972                     ((delta * ctx->cfg.g_timebase.den + round)
973                     / ctx->cfg.g_timebase.num / 10000000);
974                 pkt.data.frame.flags = lib_flags << 16;
975
976                 if (lib_flags & FRAMEFLAGS_KEY)
977                     pkt.data.frame.flags |= VPX_FRAME_IS_KEY;
978
979                 if (!cpi->common.show_frame)
980                 {
981                     pkt.data.frame.flags |= VPX_FRAME_IS_INVISIBLE;
982
983                     /* This timestamp should be as close as possible to the
984                      * prior PTS so that if a decoder uses pts to schedule when
985                      * to do this, we start right after last frame was decoded.
986                      * Invisible frames have no duration.
987                      */
988                     pkt.data.frame.pts = ((cpi->last_time_stamp_seen
989                         * ctx->cfg.g_timebase.den + round)
990                         / ctx->cfg.g_timebase.num / 10000000) + 1;
991                     pkt.data.frame.duration = 0;
992                 }
993
994                 if (cpi->droppable)
995                     pkt.data.frame.flags |= VPX_FRAME_IS_DROPPABLE;
996
997                 if (cpi->output_partition)
998                 {
999                     int i;
1000                     const int num_partitions =
1001                             (1 << cpi->common.multi_token_partition) + 1;
1002
1003                     pkt.data.frame.flags |= VPX_FRAME_IS_FRAGMENT;
1004
1005                     for (i = 0; i < num_partitions; ++i)
1006                     {
1007 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1008                         pkt.data.frame.buf = cpi->partition_d[i];
1009 #else
1010                         pkt.data.frame.buf = cx_data;
1011                         cx_data += cpi->partition_sz[i];
1012                         cx_data_sz -= cpi->partition_sz[i];
1013 #endif
1014                         pkt.data.frame.sz = cpi->partition_sz[i];
1015                         pkt.data.frame.partition_id = i;
1016                         /* don't set the fragment bit for the last partition */
1017                         if (i == (num_partitions - 1))
1018                             pkt.data.frame.flags &= ~VPX_FRAME_IS_FRAGMENT;
1019                         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1020                     }
1021 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
1022                     /* In lagged mode the encoder can buffer multiple frames.
1023                      * We don't want this in partitioned output because
1024                      * partitions are spread all over the output buffer.
1025                      * So, force an exit!
1026                      */
1027                     cx_data_sz -= ctx->cx_data_sz / 2;
1028 #endif
1029                 }
1030                 else
1031                 {
1032                     pkt.data.frame.buf = cx_data;
1033                     pkt.data.frame.sz  = size;
1034                     pkt.data.frame.partition_id = -1;
1035                     vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
1036                     cx_data += size;
1037                     cx_data_sz -= size;
1038                 }
1039             }
1040         }
1041     }
1042
1043     return res;
1044 }
1045
1046
1047 static const vpx_codec_cx_pkt_t *vp8e_get_cxdata(vpx_codec_alg_priv_t  *ctx,
1048         vpx_codec_iter_t      *iter)
1049 {
1050     return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
1051 }
1052
1053 static vpx_codec_err_t vp8e_set_reference(vpx_codec_alg_priv_t *ctx,
1054                                           va_list args)
1055 {
1056     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
1057
1058     if (data)
1059     {
1060         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
1061         YV12_BUFFER_CONFIG sd;
1062
1063         image2yuvconfig(&frame->img, &sd);
1064         vp8_set_reference(ctx->cpi, frame->frame_type, &sd);
1065         return VPX_CODEC_OK;
1066     }
1067     else
1068         return VPX_CODEC_INVALID_PARAM;
1069
1070 }
1071
1072 static vpx_codec_err_t vp8e_get_reference(vpx_codec_alg_priv_t *ctx,
1073                                           va_list args)
1074 {
1075
1076     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
1077
1078     if (data)
1079     {
1080         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
1081         YV12_BUFFER_CONFIG sd;
1082
1083         image2yuvconfig(&frame->img, &sd);
1084         vp8_get_reference(ctx->cpi, frame->frame_type, &sd);
1085         return VPX_CODEC_OK;
1086     }
1087     else
1088         return VPX_CODEC_INVALID_PARAM;
1089 }
1090
1091 static vpx_codec_err_t vp8e_set_previewpp(vpx_codec_alg_priv_t *ctx,
1092                                           va_list args)
1093 {
1094 #if CONFIG_POSTPROC
1095     vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
1096
1097     if (data)
1098     {
1099         ctx->preview_ppcfg = *((vp8_postproc_cfg_t *)data);
1100         return VPX_CODEC_OK;
1101     }
1102     else
1103         return VPX_CODEC_INVALID_PARAM;
1104 #else
1105     (void)ctx;
1106     (void)args;
1107     return VPX_CODEC_INCAPABLE;
1108 #endif
1109 }
1110
1111
1112 static vpx_image_t *vp8e_get_preview(vpx_codec_alg_priv_t *ctx)
1113 {
1114
1115     YV12_BUFFER_CONFIG sd;
1116     vp8_ppflags_t flags = {0};
1117
1118     if (ctx->preview_ppcfg.post_proc_flag)
1119     {
1120         flags.post_proc_flag        = ctx->preview_ppcfg.post_proc_flag;
1121         flags.deblocking_level      = ctx->preview_ppcfg.deblocking_level;
1122         flags.noise_level           = ctx->preview_ppcfg.noise_level;
1123     }
1124
1125     if (0 == vp8_get_preview_raw_frame(ctx->cpi, &sd, &flags))
1126     {
1127
1128         /*
1129         vpx_img_wrap(&ctx->preview_img, VPX_IMG_FMT_YV12,
1130             sd.y_width + 2*VP8BORDERINPIXELS,
1131             sd.y_height + 2*VP8BORDERINPIXELS,
1132             1,
1133             sd.buffer_alloc);
1134         vpx_img_set_rect(&ctx->preview_img,
1135             VP8BORDERINPIXELS, VP8BORDERINPIXELS,
1136             sd.y_width, sd.y_height);
1137             */
1138
1139         ctx->preview_img.bps = 12;
1140         ctx->preview_img.planes[VPX_PLANE_Y] = sd.y_buffer;
1141         ctx->preview_img.planes[VPX_PLANE_U] = sd.u_buffer;
1142         ctx->preview_img.planes[VPX_PLANE_V] = sd.v_buffer;
1143
1144         ctx->preview_img.fmt = VPX_IMG_FMT_I420;
1145         ctx->preview_img.x_chroma_shift = 1;
1146         ctx->preview_img.y_chroma_shift = 1;
1147
1148         ctx->preview_img.d_w = sd.y_width;
1149         ctx->preview_img.d_h = sd.y_height;
1150         ctx->preview_img.stride[VPX_PLANE_Y] = sd.y_stride;
1151         ctx->preview_img.stride[VPX_PLANE_U] = sd.uv_stride;
1152         ctx->preview_img.stride[VPX_PLANE_V] = sd.uv_stride;
1153         ctx->preview_img.w   = sd.y_width;
1154         ctx->preview_img.h   = sd.y_height;
1155
1156         return &ctx->preview_img;
1157     }
1158     else
1159         return NULL;
1160 }
1161
1162 static vpx_codec_err_t vp8e_update_entropy(vpx_codec_alg_priv_t *ctx,
1163                                            va_list args)
1164 {
1165     int update = va_arg(args, int);
1166     vp8_update_entropy(ctx->cpi, update);
1167     return VPX_CODEC_OK;
1168
1169 }
1170
1171 static vpx_codec_err_t vp8e_update_reference(vpx_codec_alg_priv_t *ctx,
1172                                              va_list args)
1173 {
1174     int update = va_arg(args, int);
1175     vp8_update_reference(ctx->cpi, update);
1176     return VPX_CODEC_OK;
1177 }
1178
1179 static vpx_codec_err_t vp8e_use_reference(vpx_codec_alg_priv_t *ctx,
1180                                           va_list args)
1181 {
1182     int reference_flag = va_arg(args, int);
1183     vp8_use_as_reference(ctx->cpi, reference_flag);
1184     return VPX_CODEC_OK;
1185 }
1186
1187 static vpx_codec_err_t vp8e_set_frame_flags(vpx_codec_alg_priv_t *ctx,
1188                                             va_list args)
1189 {
1190     int frame_flags = va_arg(args, int);
1191     ctx->control_frame_flags = frame_flags;
1192     return set_reference_and_update(ctx, frame_flags);
1193 }
1194
1195 static vpx_codec_err_t vp8e_set_temporal_layer_id(vpx_codec_alg_priv_t *ctx,
1196                                                   va_list args)
1197 {
1198     int layer_id = va_arg(args, int);
1199     if (layer_id < 0 || layer_id >= (int)ctx->cfg.ts_number_layers) {
1200       return VPX_CODEC_INVALID_PARAM;
1201     }
1202     ctx->cpi->temporal_layer_id = layer_id;
1203     return VPX_CODEC_OK;
1204 }
1205
1206 static vpx_codec_err_t vp8e_set_roi_map(vpx_codec_alg_priv_t *ctx,
1207                                         va_list args)
1208 {
1209     vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
1210
1211     if (data)
1212     {
1213         vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
1214
1215         if (!vp8_set_roimap(ctx->cpi, roi->roi_map, roi->rows, roi->cols, roi->delta_q, roi->delta_lf, roi->static_threshold))
1216             return VPX_CODEC_OK;
1217         else
1218             return VPX_CODEC_INVALID_PARAM;
1219     }
1220     else
1221         return VPX_CODEC_INVALID_PARAM;
1222 }
1223
1224
1225 static vpx_codec_err_t vp8e_set_activemap(vpx_codec_alg_priv_t *ctx,
1226                                           va_list args)
1227 {
1228     vpx_active_map_t *data = va_arg(args, vpx_active_map_t *);
1229
1230     if (data)
1231     {
1232
1233         vpx_active_map_t *map = (vpx_active_map_t *)data;
1234
1235         if (!vp8_set_active_map(ctx->cpi, map->active_map, map->rows, map->cols))
1236             return VPX_CODEC_OK;
1237         else
1238             return VPX_CODEC_INVALID_PARAM;
1239     }
1240     else
1241         return VPX_CODEC_INVALID_PARAM;
1242 }
1243
1244 static vpx_codec_err_t vp8e_set_scalemode(vpx_codec_alg_priv_t *ctx,
1245                                           va_list args)
1246 {
1247
1248     vpx_scaling_mode_t *data =  va_arg(args, vpx_scaling_mode_t *);
1249
1250     if (data)
1251     {
1252         int res;
1253         vpx_scaling_mode_t scalemode = *(vpx_scaling_mode_t *)data ;
1254         res = vp8_set_internal_size(ctx->cpi,
1255                                     (VPX_SCALING)scalemode.h_scaling_mode,
1256                                     (VPX_SCALING)scalemode.v_scaling_mode);
1257
1258         if (!res)
1259         {
1260             /*force next frame a key frame to effect scaling mode */
1261             ctx->next_frame_flag |= FRAMEFLAGS_KEY;
1262             return VPX_CODEC_OK;
1263         }
1264         else
1265             return VPX_CODEC_INVALID_PARAM;
1266     }
1267     else
1268         return VPX_CODEC_INVALID_PARAM;
1269 }
1270
1271
1272 static vpx_codec_ctrl_fn_map_t vp8e_ctf_maps[] =
1273 {
1274     {VP8_SET_REFERENCE,                 vp8e_set_reference},
1275     {VP8_COPY_REFERENCE,                vp8e_get_reference},
1276     {VP8_SET_POSTPROC,                  vp8e_set_previewpp},
1277     {VP8E_UPD_ENTROPY,                  vp8e_update_entropy},
1278     {VP8E_UPD_REFERENCE,                vp8e_update_reference},
1279     {VP8E_USE_REFERENCE,                vp8e_use_reference},
1280     {VP8E_SET_FRAME_FLAGS,              vp8e_set_frame_flags},
1281     {VP8E_SET_TEMPORAL_LAYER_ID,        vp8e_set_temporal_layer_id},
1282     {VP8E_SET_ROI_MAP,                  vp8e_set_roi_map},
1283     {VP8E_SET_ACTIVEMAP,                vp8e_set_activemap},
1284     {VP8E_SET_SCALEMODE,                vp8e_set_scalemode},
1285     {VP8E_SET_CPUUSED,                  set_cpu_used},
1286     {VP8E_SET_NOISE_SENSITIVITY,        set_noise_sensitivity},
1287     {VP8E_SET_ENABLEAUTOALTREF,         set_enable_auto_alt_ref},
1288     {VP8E_SET_SHARPNESS,                set_sharpness},
1289     {VP8E_SET_STATIC_THRESHOLD,         set_static_thresh},
1290     {VP8E_SET_TOKEN_PARTITIONS,         set_token_partitions},
1291     {VP8E_GET_LAST_QUANTIZER,           get_quantizer},
1292     {VP8E_GET_LAST_QUANTIZER_64,        get_quantizer64},
1293     {VP8E_SET_ARNR_MAXFRAMES,           set_arnr_max_frames},
1294     {VP8E_SET_ARNR_STRENGTH ,           set_arnr_strength},
1295     {VP8E_SET_ARNR_TYPE     ,           set_arnr_type},
1296     {VP8E_SET_TUNING,                   set_tuning},
1297     {VP8E_SET_CQ_LEVEL,                 set_cq_level},
1298     {VP8E_SET_MAX_INTRA_BITRATE_PCT,    set_rc_max_intra_bitrate_pct},
1299     {VP8E_SET_SCREEN_CONTENT_MODE,      set_screen_content_mode},
1300     { -1, NULL},
1301 };
1302
1303 static vpx_codec_enc_cfg_map_t vp8e_usage_cfg_map[] =
1304 {
1305     {
1306     0,
1307     {
1308         0,                  /* g_usage */
1309         0,                  /* g_threads */
1310         0,                  /* g_profile */
1311
1312         320,                /* g_width */
1313         240,                /* g_height */
1314         VPX_BITS_8,         /* g_bit_depth */
1315         8,                  /* g_input_bit_depth */
1316
1317         {1, 30},            /* g_timebase */
1318
1319         0,                  /* g_error_resilient */
1320
1321         VPX_RC_ONE_PASS,    /* g_pass */
1322
1323         0,                  /* g_lag_in_frames */
1324
1325         0,                  /* rc_dropframe_thresh */
1326         0,                  /* rc_resize_allowed */
1327         1,                  /* rc_scaled_width */
1328         1,                  /* rc_scaled_height */
1329         60,                 /* rc_resize_down_thresold */
1330         30,                 /* rc_resize_up_thresold */
1331
1332         VPX_VBR,            /* rc_end_usage */
1333         {0},                /* rc_twopass_stats_in */
1334         {0},                /* rc_firstpass_mb_stats_in */
1335         256,                /* rc_target_bandwidth */
1336         4,                  /* rc_min_quantizer */
1337         63,                 /* rc_max_quantizer */
1338         100,                /* rc_undershoot_pct */
1339         100,                /* rc_overshoot_pct */
1340
1341         6000,               /* rc_max_buffer_size */
1342         4000,               /* rc_buffer_initial_size; */
1343         5000,               /* rc_buffer_optimal_size; */
1344
1345         50,                 /* rc_two_pass_vbrbias  */
1346         0,                  /* rc_two_pass_vbrmin_section */
1347         400,                /* rc_two_pass_vbrmax_section */
1348
1349         /* keyframing settings (kf) */
1350         VPX_KF_AUTO,        /* g_kfmode*/
1351         0,                  /* kf_min_dist */
1352         128,                /* kf_max_dist */
1353
1354         VPX_SS_DEFAULT_LAYERS, /* ss_number_layers */
1355         {0},
1356         {0},                /* ss_target_bitrate */
1357         1,                  /* ts_number_layers */
1358         {0},                /* ts_target_bitrate */
1359         {0},                /* ts_rate_decimator */
1360         0,                  /* ts_periodicity */
1361         {0},                /* ts_layer_id */
1362     }},
1363 };
1364
1365
1366 #ifndef VERSION_STRING
1367 #define VERSION_STRING
1368 #endif
1369 CODEC_INTERFACE(vpx_codec_vp8_cx) =
1370 {
1371     "WebM Project VP8 Encoder" VERSION_STRING,
1372     VPX_CODEC_INTERNAL_ABI_VERSION,
1373     VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR |
1374     VPX_CODEC_CAP_OUTPUT_PARTITION,
1375     /* vpx_codec_caps_t          caps; */
1376     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1377     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1378     vp8e_ctf_maps,      /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1379     {
1380         NULL,    /* vpx_codec_peek_si_fn_t    peek_si; */
1381         NULL,    /* vpx_codec_get_si_fn_t     get_si; */
1382         NULL,    /* vpx_codec_decode_fn_t     decode; */
1383         NULL,    /* vpx_codec_frame_get_fn_t  frame_get; */
1384         NULL,    /* vpx_codec_set_fb_fn_t     set_fb_fn; */
1385     },
1386     {
1387         1,                  /* 1 cfg map */
1388         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    cfg_maps; */
1389         vp8e_encode,        /* vpx_codec_encode_fn_t      encode; */
1390         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   get_cx_data; */
1391         vp8e_set_config,
1392         NULL,
1393         vp8e_get_preview,
1394         vp8e_mr_alloc_mem,
1395     } /* encoder functions */
1396 };