f55a4205fe2b54c8de311e3ce9fc68d25358fd65
[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         res = validate_config(priv, &priv->cfg, &priv->vp8_cfg, 0);
632
633         if (!res)
634         {
635             if(mr_cfg)
636                 ctx->priv->enc.total_encoders   = mr_cfg->mr_total_resolutions;
637             else
638                 ctx->priv->enc.total_encoders   = 1;
639
640             set_vp8e_config(&ctx->priv->alg_priv->oxcf,
641                              ctx->priv->alg_priv->cfg,
642                              ctx->priv->alg_priv->vp8_cfg,
643                              mr_cfg);
644
645             optr = vp8_create_compressor(&ctx->priv->alg_priv->oxcf);
646
647             if (!optr)
648                 res = VPX_CODEC_MEM_ERROR;
649             else
650                 ctx->priv->alg_priv->cpi = optr;
651         }
652     }
653
654     return res;
655 }
656
657 static vpx_codec_err_t vp8e_destroy(vpx_codec_alg_priv_t *ctx)
658 {
659 #if CONFIG_MULTI_RES_ENCODING
660     /* Free multi-encoder shared memory */
661     if (ctx->oxcf.mr_total_resolutions > 0 && (ctx->oxcf.mr_encoder_id == ctx->oxcf.mr_total_resolutions-1))
662         free(ctx->oxcf.mr_low_res_mode_info);
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     switch (ctx->deprecated_mode)
722     {
723     case VP8_BEST_QUALITY_ENCODING:
724         new_qc = MODE_BESTQUALITY;
725         break;
726     case VP8_GOOD_QUALITY_ENCODING:
727         new_qc = MODE_GOODQUALITY;
728         break;
729     case VP8_REAL_TIME_ENCODING:
730         new_qc = MODE_REALTIME;
731         break;
732     }
733
734     if (ctx->cfg.g_pass == VPX_RC_FIRST_PASS)
735         new_qc = MODE_FIRSTPASS;
736     else if (ctx->cfg.g_pass == VPX_RC_LAST_PASS)
737         new_qc = (new_qc == MODE_BESTQUALITY)
738                  ? MODE_SECONDPASS_BEST
739                  : MODE_SECONDPASS;
740
741     if (ctx->oxcf.Mode != new_qc)
742     {
743         ctx->oxcf.Mode = new_qc;
744         vp8_change_config(ctx->cpi, &ctx->oxcf);
745     }
746 }
747
748
749 static vpx_codec_err_t vp8e_encode(vpx_codec_alg_priv_t  *ctx,
750                                    const vpx_image_t     *img,
751                                    vpx_codec_pts_t        pts,
752                                    unsigned long          duration,
753                                    vpx_enc_frame_flags_t  flags,
754                                    unsigned long          deadline)
755 {
756     vpx_codec_err_t res = VPX_CODEC_OK;
757
758     if (!ctx->cfg.rc_target_bitrate)
759         return res;
760
761     if (img)
762         res = validate_img(ctx, img);
763
764     if (!res)
765         res = validate_config(ctx, &ctx->cfg, &ctx->vp8_cfg, 1);
766
767     pick_quickcompress_mode(ctx, duration, deadline);
768     vpx_codec_pkt_list_init(&ctx->pkt_list);
769
770     /* Handle Flags */
771     if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF))
772         || ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF)))
773     {
774         ctx->base.err_detail = "Conflicting flags.";
775         return VPX_CODEC_INVALID_PARAM;
776     }
777
778     if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF
779                  | VP8_EFLAG_NO_REF_ARF))
780     {
781         int ref = 7;
782
783         if (flags & VP8_EFLAG_NO_REF_LAST)
784             ref ^= VP8_LAST_FLAG;
785
786         if (flags & VP8_EFLAG_NO_REF_GF)
787             ref ^= VP8_GOLD_FLAG;
788
789         if (flags & VP8_EFLAG_NO_REF_ARF)
790             ref ^= VP8_ALT_FLAG;
791
792         vp8_use_as_reference(ctx->cpi, ref);
793     }
794
795     if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF
796                  | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF
797                  | VP8_EFLAG_FORCE_ARF))
798     {
799         int upd = 7;
800
801         if (flags & VP8_EFLAG_NO_UPD_LAST)
802             upd ^= VP8_LAST_FLAG;
803
804         if (flags & VP8_EFLAG_NO_UPD_GF)
805             upd ^= VP8_GOLD_FLAG;
806
807         if (flags & VP8_EFLAG_NO_UPD_ARF)
808             upd ^= VP8_ALT_FLAG;
809
810         vp8_update_reference(ctx->cpi, upd);
811     }
812
813     if (flags & VP8_EFLAG_NO_UPD_ENTROPY)
814     {
815         vp8_update_entropy(ctx->cpi, 0);
816     }
817
818     /* Handle fixed keyframe intervals */
819     if (ctx->cfg.kf_mode == VPX_KF_AUTO
820         && ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist)
821     {
822         if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist)
823         {
824             flags |= VPX_EFLAG_FORCE_KF;
825             ctx->fixed_kf_cntr = 1;
826         }
827     }
828
829     /* Initialize the encoder instance on the first frame*/
830     if (!res && ctx->cpi)
831     {
832         unsigned int lib_flags;
833         YV12_BUFFER_CONFIG sd;
834         int64_t dst_time_stamp, dst_end_time_stamp;
835         unsigned long size, cx_data_sz;
836         unsigned char *cx_data;
837         unsigned char *cx_data_end;
838         int comp_data_state = 0;
839
840         /* Set up internal flags */
841         if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
842             ((VP8_COMP *)ctx->cpi)->b_calculate_psnr = 1;
843
844         if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
845             ((VP8_COMP *)ctx->cpi)->output_partition = 1;
846
847         /* Convert API flags to internal codec lib flags */
848         lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
849
850         /* vp8 use 10,000,000 ticks/second as time stamp */
851         dst_time_stamp    = pts * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
852         dst_end_time_stamp = (pts + duration) * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
853
854         if (img != NULL)
855         {
856             res = image2yuvconfig(img, &sd);
857
858             if (vp8_receive_raw_frame(ctx->cpi, ctx->next_frame_flag | lib_flags,
859                                       &sd, dst_time_stamp, dst_end_time_stamp))
860             {
861                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
862                 res = update_error_state(ctx, &cpi->common.error);
863             }
864
865             /* reset for next frame */
866             ctx->next_frame_flag = 0;
867         }
868
869         cx_data = ctx->cx_data;
870         cx_data_sz = ctx->cx_data_sz;
871         cx_data_end = ctx->cx_data + cx_data_sz;
872         lib_flags = 0;
873
874         while (cx_data_sz >= ctx->cx_data_sz / 2)
875         {
876             comp_data_state = vp8_get_compressed_data(ctx->cpi,
877                                                   &lib_flags,
878                                                   &size,
879                                                   cx_data,
880                                                   cx_data_end,
881                                                   &dst_time_stamp,
882                                                   &dst_end_time_stamp,
883                                                   !img);
884
885             if(comp_data_state == VPX_CODEC_CORRUPT_FRAME)
886                 return VPX_CODEC_CORRUPT_FRAME;
887             else if(comp_data_state == -1)
888                 break;
889
890             if (size)
891             {
892                 vpx_codec_pts_t    round, delta;
893                 vpx_codec_cx_pkt_t pkt;
894                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
895
896                 /* Add the frame packet to the list of returned packets. */
897                 round = 1000000 * ctx->cfg.g_timebase.num / 2 - 1;
898                 delta = (dst_end_time_stamp - dst_time_stamp);
899                 pkt.kind = VPX_CODEC_CX_FRAME_PKT;
900                 pkt.data.frame.pts =
901                     (dst_time_stamp * ctx->cfg.g_timebase.den + round)
902                     / ctx->cfg.g_timebase.num / 10000000;
903                 pkt.data.frame.duration =
904                     (delta * ctx->cfg.g_timebase.den + round)
905                     / ctx->cfg.g_timebase.num / 10000000;
906                 pkt.data.frame.flags = lib_flags << 16;
907
908                 if (lib_flags & FRAMEFLAGS_KEY)
909                     pkt.data.frame.flags |= VPX_FRAME_IS_KEY;
910
911                 if (!cpi->common.show_frame)
912                 {
913                     pkt.data.frame.flags |= VPX_FRAME_IS_INVISIBLE;
914
915                     // This timestamp should be as close as possible to the
916                     // prior PTS so that if a decoder uses pts to schedule when
917                     // to do this, we start right after last frame was decoded.
918                     // Invisible frames have no duration.
919                     pkt.data.frame.pts = ((cpi->last_time_stamp_seen
920                         * ctx->cfg.g_timebase.den + round)
921                         / ctx->cfg.g_timebase.num / 10000000) + 1;
922                     pkt.data.frame.duration = 0;
923                 }
924
925                 if (cpi->droppable)
926                     pkt.data.frame.flags |= VPX_FRAME_IS_DROPPABLE;
927
928                 if (cpi->output_partition)
929                 {
930                     int i;
931                     const int num_partitions =
932                             (1 << cpi->common.multi_token_partition) + 1;
933
934                     pkt.data.frame.flags |= VPX_FRAME_IS_FRAGMENT;
935
936                     for (i = 0; i < num_partitions; ++i)
937                     {
938 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
939                         pkt.data.frame.buf = cpi->partition_d[i];
940 #else
941                         pkt.data.frame.buf = cx_data;
942                         cx_data += cpi->partition_sz[i];
943                         cx_data_sz -= cpi->partition_sz[i];
944 #endif
945                         pkt.data.frame.sz = cpi->partition_sz[i];
946                         pkt.data.frame.partition_id = i;
947                         /* don't set the fragment bit for the last partition */
948                         if (i == (num_partitions - 1))
949                             pkt.data.frame.flags &= ~VPX_FRAME_IS_FRAGMENT;
950                         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
951                     }
952 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
953                     /* In lagged mode the encoder can buffer multiple frames.
954                      * We don't want this in partitioned output because
955                      * partitions are spread all over the output buffer.
956                      * So, force an exit!
957                      */
958                     cx_data_sz -= ctx->cx_data_sz / 2;
959 #endif
960                 }
961                 else
962                 {
963                     pkt.data.frame.buf = cx_data;
964                     pkt.data.frame.sz  = size;
965                     pkt.data.frame.partition_id = -1;
966                     vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
967                     cx_data += size;
968                     cx_data_sz -= size;
969                 }
970
971                 //printf("timestamp: %lld, duration: %d\n", pkt->data.frame.pts, pkt->data.frame.duration);
972             }
973         }
974     }
975
976     return res;
977 }
978
979
980 static const vpx_codec_cx_pkt_t *vp8e_get_cxdata(vpx_codec_alg_priv_t  *ctx,
981         vpx_codec_iter_t      *iter)
982 {
983     return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
984 }
985
986 static vpx_codec_err_t vp8e_set_reference(vpx_codec_alg_priv_t *ctx,
987         int ctr_id,
988         va_list args)
989 {
990     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
991
992     if (data)
993     {
994         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
995         YV12_BUFFER_CONFIG sd;
996
997         image2yuvconfig(&frame->img, &sd);
998         vp8_set_reference(ctx->cpi, frame->frame_type, &sd);
999         return VPX_CODEC_OK;
1000     }
1001     else
1002         return VPX_CODEC_INVALID_PARAM;
1003
1004 }
1005
1006 static vpx_codec_err_t vp8e_get_reference(vpx_codec_alg_priv_t *ctx,
1007         int ctr_id,
1008         va_list args)
1009 {
1010
1011     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
1012
1013     if (data)
1014     {
1015         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
1016         YV12_BUFFER_CONFIG sd;
1017
1018         image2yuvconfig(&frame->img, &sd);
1019         vp8_get_reference(ctx->cpi, frame->frame_type, &sd);
1020         return VPX_CODEC_OK;
1021     }
1022     else
1023         return VPX_CODEC_INVALID_PARAM;
1024 }
1025
1026 static vpx_codec_err_t vp8e_set_previewpp(vpx_codec_alg_priv_t *ctx,
1027         int ctr_id,
1028         va_list args)
1029 {
1030 #if CONFIG_POSTPROC
1031     vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
1032     (void)ctr_id;
1033
1034     if (data)
1035     {
1036         ctx->preview_ppcfg = *((vp8_postproc_cfg_t *)data);
1037         return VPX_CODEC_OK;
1038     }
1039     else
1040         return VPX_CODEC_INVALID_PARAM;
1041 #else
1042     (void)ctx;
1043     (void)ctr_id;
1044     (void)args;
1045     return VPX_CODEC_INCAPABLE;
1046 #endif
1047 }
1048
1049
1050 static vpx_image_t *vp8e_get_preview(vpx_codec_alg_priv_t *ctx)
1051 {
1052
1053     YV12_BUFFER_CONFIG sd;
1054     vp8_ppflags_t flags = {0};
1055
1056     if (ctx->preview_ppcfg.post_proc_flag)
1057     {
1058         flags.post_proc_flag        = ctx->preview_ppcfg.post_proc_flag;
1059         flags.deblocking_level      = ctx->preview_ppcfg.deblocking_level;
1060         flags.noise_level           = ctx->preview_ppcfg.noise_level;
1061     }
1062
1063     if (0 == vp8_get_preview_raw_frame(ctx->cpi, &sd, &flags))
1064     {
1065
1066         /*
1067         vpx_img_wrap(&ctx->preview_img, VPX_IMG_FMT_YV12,
1068             sd.y_width + 2*VP8BORDERINPIXELS,
1069             sd.y_height + 2*VP8BORDERINPIXELS,
1070             1,
1071             sd.buffer_alloc);
1072         vpx_img_set_rect(&ctx->preview_img,
1073             VP8BORDERINPIXELS, VP8BORDERINPIXELS,
1074             sd.y_width, sd.y_height);
1075             */
1076
1077         ctx->preview_img.bps = 12;
1078         ctx->preview_img.planes[VPX_PLANE_Y] = sd.y_buffer;
1079         ctx->preview_img.planes[VPX_PLANE_U] = sd.u_buffer;
1080         ctx->preview_img.planes[VPX_PLANE_V] = sd.v_buffer;
1081
1082         if (sd.clrtype == REG_YUV)
1083             ctx->preview_img.fmt = VPX_IMG_FMT_I420;
1084         else
1085             ctx->preview_img.fmt = VPX_IMG_FMT_VPXI420;
1086
1087         ctx->preview_img.x_chroma_shift = 1;
1088         ctx->preview_img.y_chroma_shift = 1;
1089
1090         ctx->preview_img.d_w = sd.y_width;
1091         ctx->preview_img.d_h = sd.y_height;
1092         ctx->preview_img.stride[VPX_PLANE_Y] = sd.y_stride;
1093         ctx->preview_img.stride[VPX_PLANE_U] = sd.uv_stride;
1094         ctx->preview_img.stride[VPX_PLANE_V] = sd.uv_stride;
1095         ctx->preview_img.w   = sd.y_width;
1096         ctx->preview_img.h   = sd.y_height;
1097
1098         return &ctx->preview_img;
1099     }
1100     else
1101         return NULL;
1102 }
1103
1104 static vpx_codec_err_t vp8e_update_entropy(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_entropy(ctx->cpi, update);
1110     return VPX_CODEC_OK;
1111
1112 }
1113
1114 static vpx_codec_err_t vp8e_update_reference(vpx_codec_alg_priv_t *ctx,
1115         int ctr_id,
1116         va_list args)
1117 {
1118     int update = va_arg(args, int);
1119     vp8_update_reference(ctx->cpi, update);
1120     return VPX_CODEC_OK;
1121 }
1122
1123 static vpx_codec_err_t vp8e_use_reference(vpx_codec_alg_priv_t *ctx,
1124         int ctr_id,
1125         va_list args)
1126 {
1127     int reference_flag = va_arg(args, int);
1128     vp8_use_as_reference(ctx->cpi, reference_flag);
1129     return VPX_CODEC_OK;
1130 }
1131
1132 static vpx_codec_err_t vp8e_set_roi_map(vpx_codec_alg_priv_t *ctx,
1133                                         int ctr_id,
1134                                         va_list args)
1135 {
1136     vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
1137
1138     if (data)
1139     {
1140         vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
1141
1142         if (!vp8_set_roimap(ctx->cpi, roi->roi_map, roi->rows, roi->cols, roi->delta_q, roi->delta_lf, roi->static_threshold))
1143             return VPX_CODEC_OK;
1144         else
1145             return VPX_CODEC_INVALID_PARAM;
1146     }
1147     else
1148         return VPX_CODEC_INVALID_PARAM;
1149 }
1150
1151
1152 static vpx_codec_err_t vp8e_set_activemap(vpx_codec_alg_priv_t *ctx,
1153         int ctr_id,
1154         va_list args)
1155 {
1156     vpx_active_map_t *data = va_arg(args, vpx_active_map_t *);
1157
1158     if (data)
1159     {
1160
1161         vpx_active_map_t *map = (vpx_active_map_t *)data;
1162
1163         if (!vp8_set_active_map(ctx->cpi, map->active_map, map->rows, map->cols))
1164             return VPX_CODEC_OK;
1165         else
1166             return VPX_CODEC_INVALID_PARAM;
1167     }
1168     else
1169         return VPX_CODEC_INVALID_PARAM;
1170 }
1171
1172 static vpx_codec_err_t vp8e_set_scalemode(vpx_codec_alg_priv_t *ctx,
1173         int ctr_id,
1174         va_list args)
1175 {
1176
1177     vpx_scaling_mode_t *data =  va_arg(args, vpx_scaling_mode_t *);
1178
1179     if (data)
1180     {
1181         int res;
1182         vpx_scaling_mode_t scalemode = *(vpx_scaling_mode_t *)data ;
1183         res = vp8_set_internal_size(ctx->cpi, scalemode.h_scaling_mode, scalemode.v_scaling_mode);
1184
1185         if (!res)
1186         {
1187             /*force next frame a key frame to effect scaling mode */
1188             ctx->next_frame_flag |= FRAMEFLAGS_KEY;
1189             return VPX_CODEC_OK;
1190         }
1191         else
1192             return VPX_CODEC_INVALID_PARAM;
1193     }
1194     else
1195         return VPX_CODEC_INVALID_PARAM;
1196 }
1197
1198
1199 static vpx_codec_ctrl_fn_map_t vp8e_ctf_maps[] =
1200 {
1201     {VP8_SET_REFERENCE,                 vp8e_set_reference},
1202     {VP8_COPY_REFERENCE,                vp8e_get_reference},
1203     {VP8_SET_POSTPROC,                  vp8e_set_previewpp},
1204     {VP8E_UPD_ENTROPY,                  vp8e_update_entropy},
1205     {VP8E_UPD_REFERENCE,                vp8e_update_reference},
1206     {VP8E_USE_REFERENCE,                vp8e_use_reference},
1207     {VP8E_SET_ROI_MAP,                  vp8e_set_roi_map},
1208     {VP8E_SET_ACTIVEMAP,                vp8e_set_activemap},
1209     {VP8E_SET_SCALEMODE,                vp8e_set_scalemode},
1210     {VP8E_SET_ENCODING_MODE,            set_param},
1211     {VP8E_SET_CPUUSED,                  set_param},
1212     {VP8E_SET_NOISE_SENSITIVITY,        set_param},
1213     {VP8E_SET_ENABLEAUTOALTREF,         set_param},
1214     {VP8E_SET_SHARPNESS,                set_param},
1215     {VP8E_SET_STATIC_THRESHOLD,         set_param},
1216     {VP8E_SET_TOKEN_PARTITIONS,         set_param},
1217     {VP8E_GET_LAST_QUANTIZER,           get_param},
1218     {VP8E_GET_LAST_QUANTIZER_64,        get_param},
1219     {VP8E_SET_ARNR_MAXFRAMES,           set_param},
1220     {VP8E_SET_ARNR_STRENGTH ,           set_param},
1221     {VP8E_SET_ARNR_TYPE     ,           set_param},
1222     {VP8E_SET_TUNING,                   set_param},
1223     {VP8E_SET_CQ_LEVEL,                 set_param},
1224     {VP8E_SET_MAX_INTRA_BITRATE_PCT,    set_param},
1225     { -1, NULL},
1226 };
1227
1228 static vpx_codec_enc_cfg_map_t vp8e_usage_cfg_map[] =
1229 {
1230     {
1231     0,
1232     {
1233         0,                  /* g_usage */
1234         0,                  /* g_threads */
1235         0,                  /* g_profile */
1236
1237         320,                /* g_width */
1238         240,                /* g_height */
1239         {1, 30},            /* g_timebase */
1240
1241         0,                  /* g_error_resilient */
1242
1243         VPX_RC_ONE_PASS,    /* g_pass */
1244
1245         0,                  /* g_lag_in_frames */
1246
1247         0,                  /* rc_dropframe_thresh */
1248         0,                  /* rc_resize_allowed */
1249         60,                 /* rc_resize_down_thresold */
1250         30,                 /* rc_resize_up_thresold */
1251
1252         VPX_VBR,            /* rc_end_usage */
1253 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
1254         {0},                /* rc_twopass_stats_in */
1255 #endif
1256         256,                /* rc_target_bandwidth */
1257         4,                  /* rc_min_quantizer */
1258         63,                 /* rc_max_quantizer */
1259         100,                /* rc_undershoot_pct */
1260         100,                /* rc_overshoot_pct */
1261
1262         6000,               /* rc_max_buffer_size */
1263         4000,               /* rc_buffer_initial_size; */
1264         5000,               /* rc_buffer_optimal_size; */
1265
1266         50,                 /* rc_two_pass_vbrbias  */
1267         0,                  /* rc_two_pass_vbrmin_section */
1268         400,                /* rc_two_pass_vbrmax_section */
1269
1270         /* keyframing settings (kf) */
1271         VPX_KF_AUTO,        /* g_kfmode*/
1272         0,                  /* kf_min_dist */
1273         128,                /* kf_max_dist */
1274
1275 #if VPX_ENCODER_ABI_VERSION == (1 + VPX_CODEC_ABI_VERSION)
1276         1,                  /* g_delete_first_pass_file */
1277         "vp8.fpf"           /* first pass filename */
1278 #endif
1279
1280         1,                  /* ts_number_layers */
1281         {0},                /* ts_target_bitrate */
1282         {0},                /* ts_rate_decimator */
1283         0,                  /* ts_periodicity */
1284         {0},                /* ts_layer_id */
1285     }},
1286     { -1, {NOT_IMPLEMENTED}}
1287 };
1288
1289
1290 #ifndef VERSION_STRING
1291 #define VERSION_STRING
1292 #endif
1293 CODEC_INTERFACE(vpx_codec_vp8_cx) =
1294 {
1295     "WebM Project VP8 Encoder" VERSION_STRING,
1296     VPX_CODEC_INTERNAL_ABI_VERSION,
1297     VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR |
1298     VPX_CODEC_CAP_OUTPUT_PARTITION,
1299     /* vpx_codec_caps_t          caps; */
1300     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1301     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1302     vp8e_ctf_maps,      /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1303     NOT_IMPLEMENTED,    /* vpx_codec_get_mmap_fn_t   get_mmap; */
1304     NOT_IMPLEMENTED,    /* vpx_codec_set_mmap_fn_t   set_mmap; */
1305     {
1306         NOT_IMPLEMENTED,    /* vpx_codec_peek_si_fn_t    peek_si; */
1307         NOT_IMPLEMENTED,    /* vpx_codec_get_si_fn_t     get_si; */
1308         NOT_IMPLEMENTED,    /* vpx_codec_decode_fn_t     decode; */
1309         NOT_IMPLEMENTED,    /* vpx_codec_frame_get_fn_t  frame_get; */
1310     },
1311     {
1312         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    peek_si; */
1313         vp8e_encode,        /* vpx_codec_encode_fn_t      encode; */
1314         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   frame_get; */
1315         vp8e_set_config,
1316         NOT_IMPLEMENTED,
1317         vp8e_get_preview,
1318         vp8e_mr_alloc_mem,
1319     } /* encoder functions */
1320 };
1321
1322
1323 /*
1324  * BEGIN BACKWARDS COMPATIBILITY SHIM.
1325  */
1326 #define FORCE_KEY   2
1327 static vpx_codec_err_t api1_control(vpx_codec_alg_priv_t *ctx,
1328                                     int                   ctrl_id,
1329                                     va_list               args)
1330 {
1331     vpx_codec_ctrl_fn_map_t *entry;
1332
1333     switch (ctrl_id)
1334     {
1335     case VP8E_SET_FLUSHFLAG:
1336         /* VP8 sample code did VP8E_SET_FLUSHFLAG followed by
1337          * vpx_codec_get_cx_data() rather than vpx_codec_encode().
1338          */
1339         return vp8e_encode(ctx, NULL, 0, 0, 0, 0);
1340     case VP8E_SET_FRAMETYPE:
1341         ctx->base.enc.tbd |= FORCE_KEY;
1342         return VPX_CODEC_OK;
1343     }
1344
1345     for (entry = vp8e_ctf_maps; entry && entry->fn; entry++)
1346     {
1347         if (!entry->ctrl_id || entry->ctrl_id == ctrl_id)
1348         {
1349             return entry->fn(ctx, ctrl_id, args);
1350         }
1351     }
1352
1353     return VPX_CODEC_ERROR;
1354 }
1355
1356
1357 static vpx_codec_ctrl_fn_map_t api1_ctrl_maps[] =
1358 {
1359     {0, api1_control},
1360     { -1, NULL}
1361 };
1362
1363
1364 static vpx_codec_err_t api1_encode(vpx_codec_alg_priv_t  *ctx,
1365                                    const vpx_image_t     *img,
1366                                    vpx_codec_pts_t        pts,
1367                                    unsigned long          duration,
1368                                    vpx_enc_frame_flags_t  flags,
1369                                    unsigned long          deadline)
1370 {
1371     int force = ctx->base.enc.tbd;
1372
1373     ctx->base.enc.tbd = 0;
1374     return vp8e_encode
1375            (ctx,
1376             img,
1377             pts,
1378             duration,
1379             flags | ((force & FORCE_KEY) ? VPX_EFLAG_FORCE_KF : 0),
1380             deadline);
1381 }
1382
1383
1384 vpx_codec_iface_t vpx_enc_vp8_algo =
1385 {
1386     "WebM Project VP8 Encoder (Deprecated API)" VERSION_STRING,
1387     VPX_CODEC_INTERNAL_ABI_VERSION,
1388     VPX_CODEC_CAP_ENCODER,
1389     /* vpx_codec_caps_t          caps; */
1390     vp8e_init,          /* vpx_codec_init_fn_t       init; */
1391     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
1392     api1_ctrl_maps,     /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
1393     NOT_IMPLEMENTED,    /* vpx_codec_get_mmap_fn_t   get_mmap; */
1394     NOT_IMPLEMENTED,    /* vpx_codec_set_mmap_fn_t   set_mmap; */
1395     {NOT_IMPLEMENTED},  /* decoder functions */
1396     {
1397         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    peek_si; */
1398         api1_encode,        /* vpx_codec_encode_fn_t      encode; */
1399         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   frame_get; */
1400         vp8e_set_config,
1401         NOT_IMPLEMENTED,
1402         vp8e_get_preview,
1403         vp8e_mr_alloc_mem,
1404     } /* encoder functions */
1405 };