Fixed bugs in multi-layer code related to changing params
[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_in_ms   = cfg.rc_buf_sz;
339     oxcf->starting_buffer_level_in_ms = cfg.rc_buf_initial_sz;
340     oxcf->optimal_buffer_level_in_ms  = cfg.rc_buf_optimal_sz;
341
342     oxcf->maximum_buffer_size      = cfg.rc_buf_sz;
343     oxcf->starting_buffer_level    = cfg.rc_buf_initial_sz;
344     oxcf->optimal_buffer_level     = cfg.rc_buf_optimal_sz;
345
346     oxcf->two_pass_vbrbias         = cfg.rc_2pass_vbr_bias_pct;
347     oxcf->two_pass_vbrmin_section  = cfg.rc_2pass_vbr_minsection_pct;
348     oxcf->two_pass_vbrmax_section  = cfg.rc_2pass_vbr_maxsection_pct;
349
350     oxcf->auto_key                 = cfg.kf_mode == VPX_KF_AUTO
351                                        && cfg.kf_min_dist != cfg.kf_max_dist;
352     //oxcf->kf_min_dist            = cfg.kf_min_dis;
353     oxcf->key_freq                 = cfg.kf_max_dist;
354
355     oxcf->number_of_layers         = cfg.ts_number_layers;
356     oxcf->periodicity              = cfg.ts_periodicity;
357
358     if (oxcf->number_of_layers > 1)
359     {
360         memcpy (oxcf->target_bitrate, cfg.ts_target_bitrate,
361                           sizeof(cfg.ts_target_bitrate));
362         memcpy (oxcf->rate_decimator, cfg.ts_rate_decimator,
363                           sizeof(cfg.ts_rate_decimator));
364         memcpy (oxcf->layer_id, cfg.ts_layer_id, sizeof(cfg.ts_layer_id));
365     }
366
367 #if CONFIG_MULTI_RES_ENCODING
368     /* When mr_cfg is NULL, oxcf->mr_total_resolutions and oxcf->mr_encoder_id
369      * are both memset to 0, which ensures the correct logic under this
370      * situation.
371      */
372     if(mr_cfg)
373     {
374         oxcf->mr_total_resolutions        = mr_cfg->mr_total_resolutions;
375         oxcf->mr_encoder_id               = mr_cfg->mr_encoder_id;
376         oxcf->mr_down_sampling_factor.num = mr_cfg->mr_down_sampling_factor.num;
377         oxcf->mr_down_sampling_factor.den = mr_cfg->mr_down_sampling_factor.den;
378         oxcf->mr_low_res_mode_info        = mr_cfg->mr_low_res_mode_info;
379     }
380 #endif
381
382     //oxcf->delete_first_pass_file = cfg.g_delete_firstpassfile;
383     //strcpy(oxcf->first_pass_file, cfg.g_firstpass_file);
384
385     oxcf->cpu_used               = vp8_cfg.cpu_used;
386     oxcf->encode_breakout        = vp8_cfg.static_thresh;
387     oxcf->play_alternate         = vp8_cfg.enable_auto_alt_ref;
388     oxcf->noise_sensitivity      = vp8_cfg.noise_sensitivity;
389     oxcf->Sharpness              = vp8_cfg.Sharpness;
390     oxcf->token_partitions       = vp8_cfg.token_partitions;
391
392     oxcf->two_pass_stats_in      = cfg.rc_twopass_stats_in;
393     oxcf->output_pkt_list        = vp8_cfg.pkt_list;
394
395     oxcf->arnr_max_frames        = vp8_cfg.arnr_max_frames;
396     oxcf->arnr_strength          = vp8_cfg.arnr_strength;
397     oxcf->arnr_type              = vp8_cfg.arnr_type;
398
399     oxcf->tuning                 = vp8_cfg.tuning;
400
401     /*
402         printf("Current VP8 Settings: \n");
403         printf("target_bandwidth: %d\n", oxcf->target_bandwidth);
404         printf("noise_sensitivity: %d\n", oxcf->noise_sensitivity);
405         printf("Sharpness: %d\n",    oxcf->Sharpness);
406         printf("cpu_used: %d\n",  oxcf->cpu_used);
407         printf("Mode: %d\n",     oxcf->Mode);
408         printf("delete_first_pass_file: %d\n",  oxcf->delete_first_pass_file);
409         printf("auto_key: %d\n",  oxcf->auto_key);
410         printf("key_freq: %d\n", oxcf->key_freq);
411         printf("end_usage: %d\n", oxcf->end_usage);
412         printf("under_shoot_pct: %d\n", oxcf->under_shoot_pct);
413         printf("over_shoot_pct: %d\n", oxcf->over_shoot_pct);
414         printf("starting_buffer_level: %d\n", oxcf->starting_buffer_level);
415         printf("optimal_buffer_level: %d\n",  oxcf->optimal_buffer_level);
416         printf("maximum_buffer_size: %d\n", oxcf->maximum_buffer_size);
417         printf("fixed_q: %d\n",  oxcf->fixed_q);
418         printf("worst_allowed_q: %d\n", oxcf->worst_allowed_q);
419         printf("best_allowed_q: %d\n", oxcf->best_allowed_q);
420         printf("allow_spatial_resampling: %d\n",  oxcf->allow_spatial_resampling);
421         printf("resample_down_water_mark: %d\n", oxcf->resample_down_water_mark);
422         printf("resample_up_water_mark: %d\n", oxcf->resample_up_water_mark);
423         printf("allow_df: %d\n", oxcf->allow_df);
424         printf("drop_frames_water_mark: %d\n", oxcf->drop_frames_water_mark);
425         printf("two_pass_vbrbias: %d\n",  oxcf->two_pass_vbrbias);
426         printf("two_pass_vbrmin_section: %d\n", oxcf->two_pass_vbrmin_section);
427         printf("two_pass_vbrmax_section: %d\n", oxcf->two_pass_vbrmax_section);
428         printf("allow_lag: %d\n", oxcf->allow_lag);
429         printf("lag_in_frames: %d\n", oxcf->lag_in_frames);
430         printf("play_alternate: %d\n", oxcf->play_alternate);
431         printf("Version: %d\n", oxcf->Version);
432         printf("multi_threaded: %d\n",   oxcf->multi_threaded);
433         printf("encode_breakout: %d\n", oxcf->encode_breakout);
434     */
435     return VPX_CODEC_OK;
436 }
437
438 static vpx_codec_err_t vp8e_set_config(vpx_codec_alg_priv_t       *ctx,
439                                        const vpx_codec_enc_cfg_t  *cfg)
440 {
441     vpx_codec_err_t res;
442
443     if ((cfg->g_w != ctx->cfg.g_w) || (cfg->g_h != ctx->cfg.g_h))
444         ERROR("Cannot change width or height after initialization");
445
446     /* Prevent increasing lag_in_frames. This check is stricter than it needs
447      * to be -- the limit is not increasing past the first lag_in_frames
448      * value, but we don't track the initial config, only the last successful
449      * config.
450      */
451     if ((cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames))
452         ERROR("Cannot increase lag_in_frames");
453
454     res = validate_config(ctx, cfg, &ctx->vp8_cfg, 0);
455
456     if (!res)
457     {
458         ctx->cfg = *cfg;
459         set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
460         vp8_change_config(ctx->cpi, &ctx->oxcf);
461     }
462
463     return res;
464 }
465
466
467 int vp8_reverse_trans(int);
468
469
470 static vpx_codec_err_t get_param(vpx_codec_alg_priv_t *ctx,
471                                  int                   ctrl_id,
472                                  va_list               args)
473 {
474     void *arg = va_arg(args, void *);
475
476 #define MAP(id, var) case id: *(RECAST(id, arg)) = var; break
477
478     if (!arg)
479         return VPX_CODEC_INVALID_PARAM;
480
481     switch (ctrl_id)
482     {
483         MAP(VP8E_GET_LAST_QUANTIZER, vp8_get_quantizer(ctx->cpi));
484         MAP(VP8E_GET_LAST_QUANTIZER_64, vp8_reverse_trans(vp8_get_quantizer(ctx->cpi)));
485     }
486
487     return VPX_CODEC_OK;
488 #undef MAP
489 }
490
491
492 static vpx_codec_err_t set_param(vpx_codec_alg_priv_t *ctx,
493                                  int                   ctrl_id,
494                                  va_list               args)
495 {
496     vpx_codec_err_t     res  = VPX_CODEC_OK;
497     struct vp8_extracfg xcfg = ctx->vp8_cfg;
498
499 #define MAP(id, var) case id: var = CAST(id, args); break;
500
501     switch (ctrl_id)
502     {
503         MAP(VP8E_SET_ENCODING_MODE,         ctx->deprecated_mode);
504         MAP(VP8E_SET_CPUUSED,               xcfg.cpu_used);
505         MAP(VP8E_SET_ENABLEAUTOALTREF,      xcfg.enable_auto_alt_ref);
506         MAP(VP8E_SET_NOISE_SENSITIVITY,     xcfg.noise_sensitivity);
507         MAP(VP8E_SET_SHARPNESS,             xcfg.Sharpness);
508         MAP(VP8E_SET_STATIC_THRESHOLD,      xcfg.static_thresh);
509         MAP(VP8E_SET_TOKEN_PARTITIONS,      xcfg.token_partitions);
510
511         MAP(VP8E_SET_ARNR_MAXFRAMES,        xcfg.arnr_max_frames);
512         MAP(VP8E_SET_ARNR_STRENGTH ,        xcfg.arnr_strength);
513         MAP(VP8E_SET_ARNR_TYPE     ,        xcfg.arnr_type);
514         MAP(VP8E_SET_TUNING,                xcfg.tuning);
515         MAP(VP8E_SET_CQ_LEVEL,              xcfg.cq_level);
516         MAP(VP8E_SET_MAX_INTRA_BITRATE_PCT, xcfg.rc_max_intra_bitrate_pct);
517
518     }
519
520     res = validate_config(ctx, &ctx->cfg, &xcfg, 0);
521
522     if (!res)
523     {
524         ctx->vp8_cfg = xcfg;
525         set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
526         vp8_change_config(ctx->cpi, &ctx->oxcf);
527     }
528
529     return res;
530 #undef MAP
531 }
532
533 static vpx_codec_err_t vp8e_mr_alloc_mem(const vpx_codec_enc_cfg_t *cfg,
534                                         void **mem_loc)
535 {
536     vpx_codec_err_t res = 0;
537
538 #if CONFIG_MULTI_RES_ENCODING
539     int mb_rows = ((cfg->g_w + 15) >>4);
540     int mb_cols = ((cfg->g_h + 15) >>4);
541
542     *mem_loc = calloc(mb_rows*mb_cols, sizeof(LOWER_RES_INFO));
543     if(!(*mem_loc))
544     {
545         free(*mem_loc);
546         res = VPX_CODEC_MEM_ERROR;
547     }
548     else
549         res = VPX_CODEC_OK;
550 #endif
551
552     return res;
553 }
554
555 static vpx_codec_err_t vp8e_init(vpx_codec_ctx_t *ctx,
556                                  vpx_codec_priv_enc_mr_cfg_t *mr_cfg)
557 {
558     vpx_codec_err_t        res = VPX_DEC_OK;
559     struct vpx_codec_alg_priv *priv;
560     vpx_codec_enc_cfg_t       *cfg;
561     unsigned int               i;
562
563     struct VP8_COMP *optr;
564
565     if (!ctx->priv)
566     {
567         priv = calloc(1, sizeof(struct vpx_codec_alg_priv));
568
569         if (!priv)
570         {
571             return VPX_CODEC_MEM_ERROR;
572         }
573
574         ctx->priv = &priv->base;
575         ctx->priv->sz = sizeof(*ctx->priv);
576         ctx->priv->iface = ctx->iface;
577         ctx->priv->alg_priv = priv;
578         ctx->priv->init_flags = ctx->init_flags;
579
580         if (ctx->config.enc)
581         {
582             /* Update the reference to the config structure to an
583              * internal copy.
584              */
585             ctx->priv->alg_priv->cfg = *ctx->config.enc;
586             ctx->config.enc = &ctx->priv->alg_priv->cfg;
587         }
588
589         cfg =  &ctx->priv->alg_priv->cfg;
590
591         /* Select the extra vp8 configuration table based on the current
592          * usage value. If the current usage value isn't found, use the
593          * values for usage case 0.
594          */
595         for (i = 0;
596              extracfg_map[i].usage && extracfg_map[i].usage != cfg->g_usage;
597              i++);
598
599         priv->vp8_cfg = extracfg_map[i].cfg;
600         priv->vp8_cfg.pkt_list = &priv->pkt_list.head;
601
602         priv->cx_data_sz = priv->cfg.g_w * priv->cfg.g_h * 3 / 2 * 2;
603
604         if (priv->cx_data_sz < 32768) priv->cx_data_sz = 32768;
605
606         priv->cx_data = malloc(priv->cx_data_sz);
607
608         if (!priv->cx_data)
609         {
610             return VPX_CODEC_MEM_ERROR;
611         }
612
613         priv->deprecated_mode = NO_MODE_SET;
614
615         vp8_initialize();
616
617         res = validate_config(priv, &priv->cfg, &priv->vp8_cfg, 0);
618
619         if (!res)
620         {
621             if(mr_cfg)
622                 ctx->priv->enc.total_encoders   = mr_cfg->mr_total_resolutions;
623             else
624                 ctx->priv->enc.total_encoders   = 1;
625
626             set_vp8e_config(&ctx->priv->alg_priv->oxcf,
627                              ctx->priv->alg_priv->cfg,
628                              ctx->priv->alg_priv->vp8_cfg,
629                              mr_cfg);
630
631             optr = vp8_create_compressor(&ctx->priv->alg_priv->oxcf);
632
633             if (!optr)
634                 res = VPX_CODEC_MEM_ERROR;
635             else
636                 ctx->priv->alg_priv->cpi = optr;
637         }
638     }
639
640     return res;
641 }
642
643 static vpx_codec_err_t vp8e_destroy(vpx_codec_alg_priv_t *ctx)
644 {
645 #if CONFIG_MULTI_RES_ENCODING
646     /* Free multi-encoder shared memory */
647     if (ctx->oxcf.mr_total_resolutions > 0 && (ctx->oxcf.mr_encoder_id == ctx->oxcf.mr_total_resolutions-1))
648         free(ctx->oxcf.mr_low_res_mode_info);
649 #endif
650
651     free(ctx->cx_data);
652     vp8_remove_compressor(&ctx->cpi);
653     free(ctx);
654     return VPX_CODEC_OK;
655 }
656
657 static vpx_codec_err_t image2yuvconfig(const vpx_image_t   *img,
658                                        YV12_BUFFER_CONFIG  *yv12)
659 {
660     vpx_codec_err_t        res = VPX_CODEC_OK;
661     yv12->y_buffer = img->planes[VPX_PLANE_Y];
662     yv12->u_buffer = img->planes[VPX_PLANE_U];
663     yv12->v_buffer = img->planes[VPX_PLANE_V];
664
665     yv12->y_width  = img->d_w;
666     yv12->y_height = img->d_h;
667     yv12->uv_width = (1 + yv12->y_width) / 2;
668     yv12->uv_height = (1 + yv12->y_height) / 2;
669
670     yv12->y_stride = img->stride[VPX_PLANE_Y];
671     yv12->uv_stride = img->stride[VPX_PLANE_U];
672
673     yv12->border  = (img->stride[VPX_PLANE_Y] - img->w) / 2;
674     yv12->clrtype = (img->fmt == VPX_IMG_FMT_VPXI420 || img->fmt == VPX_IMG_FMT_VPXYV12); //REG_YUV = 0
675     return res;
676 }
677
678 static void pick_quickcompress_mode(vpx_codec_alg_priv_t  *ctx,
679                                     unsigned long          duration,
680                                     unsigned long          deadline)
681 {
682     unsigned int new_qc;
683
684 #if !(CONFIG_REALTIME_ONLY)
685     /* Use best quality mode if no deadline is given. */
686     new_qc = MODE_BESTQUALITY;
687
688     if (deadline)
689     {
690         uint64_t     duration_us;
691
692         /* Convert duration parameter from stream timebase to microseconds */
693         duration_us = (uint64_t)duration * 1000000
694                       * (uint64_t)ctx->cfg.g_timebase.num
695                       / (uint64_t)ctx->cfg.g_timebase.den;
696
697         /* If the deadline is more that the duration this frame is to be shown,
698          * use good quality mode. Otherwise use realtime mode.
699          */
700         new_qc = (deadline > duration_us) ? MODE_GOODQUALITY : MODE_REALTIME;
701     }
702
703 #else
704     new_qc = MODE_REALTIME;
705 #endif
706
707     switch (ctx->deprecated_mode)
708     {
709     case VP8_BEST_QUALITY_ENCODING:
710         new_qc = MODE_BESTQUALITY;
711         break;
712     case VP8_GOOD_QUALITY_ENCODING:
713         new_qc = MODE_GOODQUALITY;
714         break;
715     case VP8_REAL_TIME_ENCODING:
716         new_qc = MODE_REALTIME;
717         break;
718     }
719
720     if (ctx->cfg.g_pass == VPX_RC_FIRST_PASS)
721         new_qc = MODE_FIRSTPASS;
722     else if (ctx->cfg.g_pass == VPX_RC_LAST_PASS)
723         new_qc = (new_qc == MODE_BESTQUALITY)
724                  ? MODE_SECONDPASS_BEST
725                  : MODE_SECONDPASS;
726
727     if (ctx->oxcf.Mode != new_qc)
728     {
729         ctx->oxcf.Mode = new_qc;
730         vp8_change_config(ctx->cpi, &ctx->oxcf);
731     }
732 }
733
734
735 static vpx_codec_err_t vp8e_encode(vpx_codec_alg_priv_t  *ctx,
736                                    const vpx_image_t     *img,
737                                    vpx_codec_pts_t        pts,
738                                    unsigned long          duration,
739                                    vpx_enc_frame_flags_t  flags,
740                                    unsigned long          deadline)
741 {
742     vpx_codec_err_t res = VPX_CODEC_OK;
743
744     if (img)
745         res = validate_img(ctx, img);
746
747     if (!res)
748         res = validate_config(ctx, &ctx->cfg, &ctx->vp8_cfg, 1);
749
750     pick_quickcompress_mode(ctx, duration, deadline);
751     vpx_codec_pkt_list_init(&ctx->pkt_list);
752
753     /* Handle Flags */
754     if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF))
755         || ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF)))
756     {
757         ctx->base.err_detail = "Conflicting flags.";
758         return VPX_CODEC_INVALID_PARAM;
759     }
760
761     if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF
762                  | VP8_EFLAG_NO_REF_ARF))
763     {
764         int ref = 7;
765
766         if (flags & VP8_EFLAG_NO_REF_LAST)
767             ref ^= VP8_LAST_FLAG;
768
769         if (flags & VP8_EFLAG_NO_REF_GF)
770             ref ^= VP8_GOLD_FLAG;
771
772         if (flags & VP8_EFLAG_NO_REF_ARF)
773             ref ^= VP8_ALT_FLAG;
774
775         vp8_use_as_reference(ctx->cpi, ref);
776     }
777
778     if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF
779                  | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF
780                  | VP8_EFLAG_FORCE_ARF))
781     {
782         int upd = 7;
783
784         if (flags & VP8_EFLAG_NO_UPD_LAST)
785             upd ^= VP8_LAST_FLAG;
786
787         if (flags & VP8_EFLAG_NO_UPD_GF)
788             upd ^= VP8_GOLD_FLAG;
789
790         if (flags & VP8_EFLAG_NO_UPD_ARF)
791             upd ^= VP8_ALT_FLAG;
792
793         vp8_update_reference(ctx->cpi, upd);
794     }
795
796     if (flags & VP8_EFLAG_NO_UPD_ENTROPY)
797     {
798         vp8_update_entropy(ctx->cpi, 0);
799     }
800
801     /* Handle fixed keyframe intervals */
802     if (ctx->cfg.kf_mode == VPX_KF_AUTO
803         && ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist)
804     {
805         if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist)
806         {
807             flags |= VPX_EFLAG_FORCE_KF;
808             ctx->fixed_kf_cntr = 1;
809         }
810     }
811
812     /* Initialize the encoder instance on the first frame*/
813     if (!res && ctx->cpi)
814     {
815         unsigned int lib_flags;
816         YV12_BUFFER_CONFIG sd;
817         int64_t dst_time_stamp, dst_end_time_stamp;
818         unsigned long size, cx_data_sz;
819         unsigned char *cx_data;
820         unsigned char *cx_data_end;
821         int comp_data_state = 0;
822
823         /* Set up internal flags */
824         if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
825             ((VP8_COMP *)ctx->cpi)->b_calculate_psnr = 1;
826
827         if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
828             ((VP8_COMP *)ctx->cpi)->output_partition = 1;
829
830         /* Convert API flags to internal codec lib flags */
831         lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
832
833         /* vp8 use 10,000,000 ticks/second as time stamp */
834         dst_time_stamp    = pts * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
835         dst_end_time_stamp = (pts + duration) * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
836
837         if (img != NULL)
838         {
839             res = image2yuvconfig(img, &sd);
840
841             if (vp8_receive_raw_frame(ctx->cpi, ctx->next_frame_flag | lib_flags,
842                                       &sd, dst_time_stamp, dst_end_time_stamp))
843             {
844                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
845                 res = update_error_state(ctx, &cpi->common.error);
846             }
847
848             /* reset for next frame */
849             ctx->next_frame_flag = 0;
850         }
851
852         cx_data = ctx->cx_data;
853         cx_data_sz = ctx->cx_data_sz;
854         cx_data_end = ctx->cx_data + cx_data_sz;
855         lib_flags = 0;
856
857         while (cx_data_sz >= ctx->cx_data_sz / 2)
858         {
859             comp_data_state = vp8_get_compressed_data(ctx->cpi,
860                                                   &lib_flags,
861                                                   &size,
862                                                   cx_data,
863                                                   cx_data_end,
864                                                   &dst_time_stamp,
865                                                   &dst_end_time_stamp,
866                                                   !img);
867
868             if(comp_data_state == VPX_CODEC_CORRUPT_FRAME)
869                 return VPX_CODEC_CORRUPT_FRAME;
870             else if(comp_data_state == -1)
871                 break;
872
873             if (size)
874             {
875                 vpx_codec_pts_t    round, delta;
876                 vpx_codec_cx_pkt_t pkt;
877                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
878
879                 /* Add the frame packet to the list of returned packets. */
880                 round = 1000000 * ctx->cfg.g_timebase.num / 2 - 1;
881                 delta = (dst_end_time_stamp - dst_time_stamp);
882                 pkt.kind = VPX_CODEC_CX_FRAME_PKT;
883                 pkt.data.frame.pts =
884                     (dst_time_stamp * ctx->cfg.g_timebase.den + round)
885                     / ctx->cfg.g_timebase.num / 10000000;
886                 pkt.data.frame.duration =
887                     (delta * ctx->cfg.g_timebase.den + round)
888                     / ctx->cfg.g_timebase.num / 10000000;
889                 pkt.data.frame.flags = lib_flags << 16;
890
891                 if (lib_flags & FRAMEFLAGS_KEY)
892                     pkt.data.frame.flags |= VPX_FRAME_IS_KEY;
893
894                 if (!cpi->common.show_frame)
895                 {
896                     pkt.data.frame.flags |= VPX_FRAME_IS_INVISIBLE;
897
898                     // This timestamp should be as close as possible to the
899                     // prior PTS so that if a decoder uses pts to schedule when
900                     // to do this, we start right after last frame was decoded.
901                     // Invisible frames have no duration.
902                     pkt.data.frame.pts = ((cpi->last_time_stamp_seen
903                         * ctx->cfg.g_timebase.den + round)
904                         / ctx->cfg.g_timebase.num / 10000000) + 1;
905                     pkt.data.frame.duration = 0;
906                 }
907
908                 if (cpi->droppable)
909                     pkt.data.frame.flags |= VPX_FRAME_IS_DROPPABLE;
910
911                 if (cpi->output_partition)
912                 {
913                     int i;
914                     const int num_partitions =
915                             (1 << cpi->common.multi_token_partition) + 1;
916
917                     pkt.data.frame.flags |= VPX_FRAME_IS_FRAGMENT;
918
919                     for (i = 0; i < num_partitions; ++i)
920                     {
921                         pkt.data.frame.buf = cx_data;
922                         pkt.data.frame.sz = cpi->partition_sz[i];
923                         pkt.data.frame.partition_id = i;
924                         /* don't set the fragment bit for the last partition */
925                         if (i == (num_partitions - 1))
926                             pkt.data.frame.flags &= ~VPX_FRAME_IS_FRAGMENT;
927                         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
928                         cx_data += cpi->partition_sz[i];
929                         cx_data_sz -= cpi->partition_sz[i];
930                     }
931                 }
932                 else
933                 {
934                     pkt.data.frame.buf = cx_data;
935                     pkt.data.frame.sz  = size;
936                     pkt.data.frame.partition_id = -1;
937                     vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
938                     cx_data += size;
939                     cx_data_sz -= size;
940                 }
941
942                 //printf("timestamp: %lld, duration: %d\n", pkt->data.frame.pts, pkt->data.frame.duration);
943             }
944         }
945     }
946
947     return res;
948 }
949
950
951 static const vpx_codec_cx_pkt_t *vp8e_get_cxdata(vpx_codec_alg_priv_t  *ctx,
952         vpx_codec_iter_t      *iter)
953 {
954     return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
955 }
956
957 static vpx_codec_err_t vp8e_set_reference(vpx_codec_alg_priv_t *ctx,
958         int ctr_id,
959         va_list args)
960 {
961     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
962
963     if (data)
964     {
965         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
966         YV12_BUFFER_CONFIG sd;
967
968         image2yuvconfig(&frame->img, &sd);
969         vp8_set_reference(ctx->cpi, frame->frame_type, &sd);
970         return VPX_CODEC_OK;
971     }
972     else
973         return VPX_CODEC_INVALID_PARAM;
974
975 }
976
977 static vpx_codec_err_t vp8e_get_reference(vpx_codec_alg_priv_t *ctx,
978         int ctr_id,
979         va_list args)
980 {
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_get_reference(ctx->cpi, frame->frame_type, &sd);
991         return VPX_CODEC_OK;
992     }
993     else
994         return VPX_CODEC_INVALID_PARAM;
995 }
996
997 static vpx_codec_err_t vp8e_set_previewpp(vpx_codec_alg_priv_t *ctx,
998         int ctr_id,
999         va_list args)
1000 {
1001 #if CONFIG_POSTPROC
1002     vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
1003     (void)ctr_id;
1004
1005     if (data)
1006     {
1007         ctx->preview_ppcfg = *((vp8_postproc_cfg_t *)data);
1008         return VPX_CODEC_OK;
1009     }
1010     else
1011         return VPX_CODEC_INVALID_PARAM;
1012 #else
1013     (void)ctx;
1014     (void)ctr_id;
1015     (void)args;
1016     return VPX_CODEC_INCAPABLE;
1017 #endif
1018 }
1019
1020
1021 static vpx_image_t *vp8e_get_preview(vpx_codec_alg_priv_t *ctx)
1022 {
1023
1024     YV12_BUFFER_CONFIG sd;
1025     vp8_ppflags_t flags = {0};
1026
1027     if (ctx->preview_ppcfg.post_proc_flag)
1028     {
1029         flags.post_proc_flag        = ctx->preview_ppcfg.post_proc_flag;
1030         flags.deblocking_level      = ctx->preview_ppcfg.deblocking_level;
1031         flags.noise_level           = ctx->preview_ppcfg.noise_level;
1032     }
1033
1034     if (0 == vp8_get_preview_raw_frame(ctx->cpi, &sd, &flags))
1035     {
1036
1037         /*
1038         vpx_img_wrap(&ctx->preview_img, VPX_IMG_FMT_YV12,
1039             sd.y_width + 2*VP8BORDERINPIXELS,
1040             sd.y_height + 2*VP8BORDERINPIXELS,
1041             1,
1042             sd.buffer_alloc);
1043         vpx_img_set_rect(&ctx->preview_img,
1044             VP8BORDERINPIXELS, VP8BORDERINPIXELS,
1045             sd.y_width, sd.y_height);
1046             */
1047
1048         ctx->preview_img.bps = 12;
1049         ctx->preview_img.planes[VPX_PLANE_Y] = sd.y_buffer;
1050         ctx->preview_img.planes[VPX_PLANE_U] = sd.u_buffer;
1051         ctx->preview_img.planes[VPX_PLANE_V] = sd.v_buffer;
1052
1053         if (sd.clrtype == REG_YUV)
1054             ctx->preview_img.fmt = VPX_IMG_FMT_I420;
1055         else
1056             ctx->preview_img.fmt = VPX_IMG_FMT_VPXI420;
1057
1058         ctx->preview_img.x_chroma_shift = 1;
1059         ctx->preview_img.y_chroma_shift = 1;
1060
1061         ctx->preview_img.d_w = sd.y_width;
1062         ctx->preview_img.d_h = sd.y_height;
1063         ctx->preview_img.stride[VPX_PLANE_Y] = sd.y_stride;
1064         ctx->preview_img.stride[VPX_PLANE_U] = sd.uv_stride;
1065         ctx->preview_img.stride[VPX_PLANE_V] = sd.uv_stride;
1066         ctx->preview_img.w   = sd.y_width;
1067         ctx->preview_img.h   = sd.y_height;
1068
1069         return &ctx->preview_img;
1070     }
1071     else
1072         return NULL;
1073 }
1074
1075 static vpx_codec_err_t vp8e_update_entropy(vpx_codec_alg_priv_t *ctx,
1076         int ctr_id,
1077         va_list args)
1078 {
1079     int update = va_arg(args, int);
1080     vp8_update_entropy(ctx->cpi, update);
1081     return VPX_CODEC_OK;
1082
1083 }
1084
1085 static vpx_codec_err_t vp8e_update_reference(vpx_codec_alg_priv_t *ctx,
1086         int ctr_id,
1087         va_list args)
1088 {
1089     int update = va_arg(args, int);
1090     vp8_update_reference(ctx->cpi, update);
1091     return VPX_CODEC_OK;
1092 }
1093
1094 static vpx_codec_err_t vp8e_use_reference(vpx_codec_alg_priv_t *ctx,
1095         int ctr_id,
1096         va_list args)
1097 {
1098     int reference_flag = va_arg(args, int);
1099     vp8_use_as_reference(ctx->cpi, reference_flag);
1100     return VPX_CODEC_OK;
1101 }
1102
1103 static vpx_codec_err_t vp8e_set_roi_map(vpx_codec_alg_priv_t *ctx,
1104                                         int ctr_id,
1105                                         va_list args)
1106 {
1107     vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
1108
1109     if (data)
1110     {
1111         vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
1112
1113         if (!vp8_set_roimap(ctx->cpi, roi->roi_map, roi->rows, roi->cols, roi->delta_q, roi->delta_lf, roi->static_threshold))
1114             return VPX_CODEC_OK;
1115         else
1116             return VPX_CODEC_INVALID_PARAM;
1117     }
1118     else
1119         return VPX_CODEC_INVALID_PARAM;
1120 }
1121
1122
1123 static vpx_codec_err_t vp8e_set_activemap(vpx_codec_alg_priv_t *ctx,
1124         int ctr_id,
1125         va_list args)
1126 {
1127     vpx_active_map_t *data = va_arg(args, vpx_active_map_t *);
1128
1129     if (data)
1130     {
1131
1132         vpx_active_map_t *map = (vpx_active_map_t *)data;
1133
1134         if (!vp8_set_active_map(ctx->cpi, map->active_map, map->rows, map->cols))
1135             return VPX_CODEC_OK;
1136         else
1137             return VPX_CODEC_INVALID_PARAM;
1138     }
1139     else
1140         return VPX_CODEC_INVALID_PARAM;
1141 }
1142
1143 static vpx_codec_err_t vp8e_set_scalemode(vpx_codec_alg_priv_t *ctx,
1144         int ctr_id,
1145         va_list args)
1146 {
1147
1148     vpx_scaling_mode_t *data =  va_arg(args, vpx_scaling_mode_t *);
1149
1150     if (data)
1151     {
1152         int res;
1153         vpx_scaling_mode_t scalemode = *(vpx_scaling_mode_t *)data ;
1154         res = vp8_set_internal_size(ctx->cpi, scalemode.h_scaling_mode, scalemode.v_scaling_mode);
1155
1156         if (!res)
1157         {
1158             /*force next frame a key frame to effect scaling mode */
1159             ctx->next_frame_flag |= FRAMEFLAGS_KEY;
1160             return VPX_CODEC_OK;
1161         }
1162         else
1163             return VPX_CODEC_INVALID_PARAM;
1164     }
1165     else
1166         return VPX_CODEC_INVALID_PARAM;
1167 }
1168
1169
1170 static vpx_codec_ctrl_fn_map_t vp8e_ctf_maps[] =
1171 {
1172     {VP8_SET_REFERENCE,                 vp8e_set_reference},
1173     {VP8_COPY_REFERENCE,                vp8e_get_reference},
1174     {VP8_SET_POSTPROC,                  vp8e_set_previewpp},
1175     {VP8E_UPD_ENTROPY,                  vp8e_update_entropy},
1176     {VP8E_UPD_REFERENCE,                vp8e_update_reference},
1177     {VP8E_USE_REFERENCE,                vp8e_use_reference},
1178     {VP8E_SET_ROI_MAP,                  vp8e_set_roi_map},
1179     {VP8E_SET_ACTIVEMAP,                vp8e_set_activemap},
1180     {VP8E_SET_SCALEMODE,                vp8e_set_scalemode},
1181     {VP8E_SET_ENCODING_MODE,            set_param},
1182     {VP8E_SET_CPUUSED,                  set_param},
1183     {VP8E_SET_NOISE_SENSITIVITY,        set_param},
1184     {VP8E_SET_ENABLEAUTOALTREF,         set_param},
1185     {VP8E_SET_SHARPNESS,                set_param},
1186     {VP8E_SET_STATIC_THRESHOLD,         set_param},
1187     {VP8E_SET_TOKEN_PARTITIONS,         set_param},
1188     {VP8E_GET_LAST_QUANTIZER,           get_param},
1189     {VP8E_GET_LAST_QUANTIZER_64,        get_param},
1190     {VP8E_SET_ARNR_MAXFRAMES,           set_param},
1191     {VP8E_SET_ARNR_STRENGTH ,           set_param},
1192     {VP8E_SET_ARNR_TYPE     ,           set_param},
1193     {VP8E_SET_TUNING,                   set_param},
1194     {VP8E_SET_CQ_LEVEL,                 set_param},
1195     {VP8E_SET_MAX_INTRA_BITRATE_PCT,    set_param},
1196     { -1, NULL},
1197 };
1198
1199 static vpx_codec_enc_cfg_map_t vp8e_usage_cfg_map[] =
1200 {
1201     {
1202     0,
1203     {
1204         0,                  /* g_usage */
1205         0,                  /* g_threads */
1206         0,                  /* g_profile */
1207
1208         320,                /* g_width */
1209         240,                /* g_height */
1210         {1, 30},            /* g_timebase */
1211
1212         0,                  /* g_error_resilient */
1213
1214         VPX_RC_ONE_PASS,    /* g_pass */
1215
1216         0,                  /* g_lag_in_frames */
1217
1218         0,                  /* rc_dropframe_thresh */
1219         0,                  /* rc_resize_allowed */
1220         60,                 /* rc_resize_down_thresold */
1221         30,                 /* rc_resize_up_thresold */
1222
1223         VPX_VBR,            /* rc_end_usage */
1224 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1225         {0},                /* rc_twopass_stats_in */
1226 #endif
1227         256,                /* rc_target_bandwidth */
1228         4,                  /* rc_min_quantizer */
1229         63,                 /* rc_max_quantizer */
1230         100,                /* rc_undershoot_pct */
1231         100,                /* rc_overshoot_pct */
1232
1233         6000,               /* rc_max_buffer_size */
1234         4000,               /* rc_buffer_initial_size; */
1235         5000,               /* rc_buffer_optimal_size; */
1236
1237         50,                 /* rc_two_pass_vbrbias  */
1238         0,                  /* rc_two_pass_vbrmin_section */
1239         400,                /* rc_two_pass_vbrmax_section */
1240
1241         /* keyframing settings (kf) */
1242         VPX_KF_AUTO,        /* g_kfmode*/
1243         0,                  /* kf_min_dist */
1244         128,                /* kf_max_dist */
1245
1246 #if VPX_ENCODER_ABI_VERSION == (1 + VPX_CODEC_ABI_VERSION)
1247         1,                  /* g_delete_first_pass_file */
1248         "vp8.fpf"           /* first pass filename */
1249 #endif
1250
1251         1,                  /* ts_number_layers */
1252         {0},                /* ts_target_bitrate */
1253         {0},                /* ts_rate_decimator */
1254         0,                  /* ts_periodicity */
1255         {0},                /* ts_layer_id */
1256     }},
1257     { -1, {NOT_IMPLEMENTED}}
1258 };
1259
1260
1261 #ifndef VERSION_STRING
1262 #define VERSION_STRING
1263 #endif
1264 CODEC_INTERFACE(vpx_codec_vp8_cx) =
1265 {
1266     "WebM Project VP8 Encoder" VERSION_STRING,
1267     VPX_CODEC_INTERNAL_ABI_VERSION,
1268     VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR |
1269     VPX_CODEC_CAP_OUTPUT_PARTITION,
1270     /* vpx_codec_caps_t          caps; */
1271     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1272     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1273     vp8e_ctf_maps,      /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1274     NOT_IMPLEMENTED,    /* vpx_codec_get_mmap_fn_t   get_mmap; */
1275     NOT_IMPLEMENTED,    /* vpx_codec_set_mmap_fn_t   set_mmap; */
1276     {
1277         NOT_IMPLEMENTED,    /* vpx_codec_peek_si_fn_t    peek_si; */
1278         NOT_IMPLEMENTED,    /* vpx_codec_get_si_fn_t     get_si; */
1279         NOT_IMPLEMENTED,    /* vpx_codec_decode_fn_t     decode; */
1280         NOT_IMPLEMENTED,    /* vpx_codec_frame_get_fn_t  frame_get; */
1281     },
1282     {
1283         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    peek_si; */
1284         vp8e_encode,        /* vpx_codec_encode_fn_t      encode; */
1285         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   frame_get; */
1286         vp8e_set_config,
1287         NOT_IMPLEMENTED,
1288         vp8e_get_preview,
1289         vp8e_mr_alloc_mem,
1290     } /* encoder functions */
1291 };
1292
1293
1294 /*
1295  * BEGIN BACKWARDS COMPATIBILITY SHIM.
1296  */
1297 #define FORCE_KEY   2
1298 static vpx_codec_err_t api1_control(vpx_codec_alg_priv_t *ctx,
1299                                     int                   ctrl_id,
1300                                     va_list               args)
1301 {
1302     vpx_codec_ctrl_fn_map_t *entry;
1303
1304     switch (ctrl_id)
1305     {
1306     case VP8E_SET_FLUSHFLAG:
1307         /* VP8 sample code did VP8E_SET_FLUSHFLAG followed by
1308          * vpx_codec_get_cx_data() rather than vpx_codec_encode().
1309          */
1310         return vp8e_encode(ctx, NULL, 0, 0, 0, 0);
1311     case VP8E_SET_FRAMETYPE:
1312         ctx->base.enc.tbd |= FORCE_KEY;
1313         return VPX_CODEC_OK;
1314     }
1315
1316     for (entry = vp8e_ctf_maps; entry && entry->fn; entry++)
1317     {
1318         if (!entry->ctrl_id || entry->ctrl_id == ctrl_id)
1319         {
1320             return entry->fn(ctx, ctrl_id, args);
1321         }
1322     }
1323
1324     return VPX_CODEC_ERROR;
1325 }
1326
1327
1328 static vpx_codec_ctrl_fn_map_t api1_ctrl_maps[] =
1329 {
1330     {0, api1_control},
1331     { -1, NULL}
1332 };
1333
1334
1335 static vpx_codec_err_t api1_encode(vpx_codec_alg_priv_t  *ctx,
1336                                    const vpx_image_t     *img,
1337                                    vpx_codec_pts_t        pts,
1338                                    unsigned long          duration,
1339                                    vpx_enc_frame_flags_t  flags,
1340                                    unsigned long          deadline)
1341 {
1342     int force = ctx->base.enc.tbd;
1343
1344     ctx->base.enc.tbd = 0;
1345     return vp8e_encode
1346            (ctx,
1347             img,
1348             pts,
1349             duration,
1350             flags | ((force & FORCE_KEY) ? VPX_EFLAG_FORCE_KF : 0),
1351             deadline);
1352 }
1353
1354
1355 vpx_codec_iface_t vpx_enc_vp8_algo =
1356 {
1357     "WebM Project VP8 Encoder (Deprecated API)" VERSION_STRING,
1358     VPX_CODEC_INTERNAL_ABI_VERSION,
1359     VPX_CODEC_CAP_ENCODER,
1360     /* vpx_codec_caps_t          caps; */
1361     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1362     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1363     api1_ctrl_maps,     /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1364     NOT_IMPLEMENTED,    /* vpx_codec_get_mmap_fn_t   get_mmap; */
1365     NOT_IMPLEMENTED,    /* vpx_codec_set_mmap_fn_t   set_mmap; */
1366     {NOT_IMPLEMENTED},  /* decoder functions */
1367     {
1368         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    peek_si; */
1369         api1_encode,        /* vpx_codec_encode_fn_t      encode; */
1370         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   frame_get; */
1371         vp8e_set_config,
1372         NOT_IMPLEMENTED,
1373         vp8e_get_preview,
1374         vp8e_mr_alloc_mem,
1375     } /* encoder functions */
1376 };