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