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