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