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