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