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