]> git.sesse.net Git - ffmpeg/blob - libavcodec/libvpxenc.c
avcodec/golomb: get_ur_golomb_jpegls: Fix reading huge k values
[ffmpeg] / libavcodec / libvpxenc.c
1 /*
2  * Copyright (c) 2010, Google, Inc.
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * VP8 encoder support via libvpx
24  */
25
26 #define VPX_DISABLE_CTRL_TYPECHECKS 1
27 #define VPX_CODEC_DISABLE_COMPAT    1
28 #include <vpx/vpx_encoder.h>
29 #include <vpx/vp8cx.h>
30
31 #include "avcodec.h"
32 #include "internal.h"
33 #include "libavutil/avassert.h"
34 #include "libvpx.h"
35 #include "libavutil/base64.h"
36 #include "libavutil/common.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40
41 /**
42  * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
43  * One encoded frame returned from the library.
44  */
45 struct FrameListData {
46     void *buf;                       /**< compressed data buffer */
47     size_t sz;                       /**< length of compressed data */
48     void *buf_alpha;
49     size_t sz_alpha;
50     int64_t pts;                     /**< time stamp to show frame
51                                           (in timebase units) */
52     unsigned long duration;          /**< duration to show frame
53                                           (in timebase units) */
54     uint32_t flags;                  /**< flags for this frame */
55     uint64_t sse[4];
56     int have_sse;                    /**< true if we have pending sse[] */
57     uint64_t frame_number;
58     struct FrameListData *next;
59 };
60
61 typedef struct VP8EncoderContext {
62     AVClass *class;
63     struct vpx_codec_ctx encoder;
64     struct vpx_image rawimg;
65     struct vpx_codec_ctx encoder_alpha;
66     struct vpx_image rawimg_alpha;
67     uint8_t is_alpha;
68     struct vpx_fixed_buf twopass_stats;
69     int deadline; //i.e., RT/GOOD/BEST
70     uint64_t sse[4];
71     int have_sse; /**< true if we have pending sse[] */
72     uint64_t frame_number;
73     struct FrameListData *coded_frame_list;
74
75     int cpu_used;
76     /**
77      * VP8 specific flags, see VP8F_* below.
78      */
79     int flags;
80 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
81 #define VP8F_AUTO_ALT_REF    0x00000002 ///< Enable automatic alternate reference frame generation
82
83     int auto_alt_ref;
84
85     int arnr_max_frames;
86     int arnr_strength;
87     int arnr_type;
88
89     int lag_in_frames;
90     int error_resilient;
91     int crf;
92     int static_thresh;
93     int max_intra_rate;
94
95     // VP9-only
96     int lossless;
97     int tile_columns;
98     int tile_rows;
99     int frame_parallel;
100     int aq_mode;
101 } VP8Context;
102
103 /** String mappings for enum vp8e_enc_control_id */
104 static const char *const ctlidstr[] = {
105     [VP8E_UPD_ENTROPY]           = "VP8E_UPD_ENTROPY",
106     [VP8E_UPD_REFERENCE]         = "VP8E_UPD_REFERENCE",
107     [VP8E_USE_REFERENCE]         = "VP8E_USE_REFERENCE",
108     [VP8E_SET_ROI_MAP]           = "VP8E_SET_ROI_MAP",
109     [VP8E_SET_ACTIVEMAP]         = "VP8E_SET_ACTIVEMAP",
110     [VP8E_SET_SCALEMODE]         = "VP8E_SET_SCALEMODE",
111     [VP8E_SET_CPUUSED]           = "VP8E_SET_CPUUSED",
112     [VP8E_SET_ENABLEAUTOALTREF]  = "VP8E_SET_ENABLEAUTOALTREF",
113     [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
114     [VP8E_SET_SHARPNESS]         = "VP8E_SET_SHARPNESS",
115     [VP8E_SET_STATIC_THRESHOLD]  = "VP8E_SET_STATIC_THRESHOLD",
116     [VP8E_SET_TOKEN_PARTITIONS]  = "VP8E_SET_TOKEN_PARTITIONS",
117     [VP8E_GET_LAST_QUANTIZER]    = "VP8E_GET_LAST_QUANTIZER",
118     [VP8E_SET_ARNR_MAXFRAMES]    = "VP8E_SET_ARNR_MAXFRAMES",
119     [VP8E_SET_ARNR_STRENGTH]     = "VP8E_SET_ARNR_STRENGTH",
120     [VP8E_SET_ARNR_TYPE]         = "VP8E_SET_ARNR_TYPE",
121     [VP8E_SET_CQ_LEVEL]          = "VP8E_SET_CQ_LEVEL",
122     [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
123 #if CONFIG_LIBVPX_VP9_ENCODER
124     [VP9E_SET_LOSSLESS]                = "VP9E_SET_LOSSLESS",
125     [VP9E_SET_TILE_COLUMNS]            = "VP9E_SET_TILE_COLUMNS",
126     [VP9E_SET_TILE_ROWS]               = "VP9E_SET_TILE_ROWS",
127     [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
128     [VP9E_SET_AQ_MODE]                 = "VP9E_SET_AQ_MODE",
129 #endif
130 };
131
132 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
133 {
134     VP8Context *ctx = avctx->priv_data;
135     const char *error  = vpx_codec_error(&ctx->encoder);
136     const char *detail = vpx_codec_error_detail(&ctx->encoder);
137
138     av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
139     if (detail)
140         av_log(avctx, AV_LOG_ERROR, "  Additional information: %s\n", detail);
141 }
142
143 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
144                                  const struct vpx_codec_enc_cfg *cfg)
145 {
146     int width = -30;
147     int level = AV_LOG_DEBUG;
148
149     av_log(avctx, level, "vpx_codec_enc_cfg\n");
150     av_log(avctx, level, "generic settings\n"
151            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
152 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
153            "  %*s%u\n  %*s%u\n"
154 #endif
155            "  %*s{%u/%u}\n  %*s%u\n  %*s%d\n  %*s%u\n",
156            width, "g_usage:",           cfg->g_usage,
157            width, "g_threads:",         cfg->g_threads,
158            width, "g_profile:",         cfg->g_profile,
159            width, "g_w:",               cfg->g_w,
160            width, "g_h:",               cfg->g_h,
161 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
162            width, "g_bit_depth:",       cfg->g_bit_depth,
163            width, "g_input_bit_depth:", cfg->g_input_bit_depth,
164 #endif
165            width, "g_timebase:",        cfg->g_timebase.num, cfg->g_timebase.den,
166            width, "g_error_resilient:", cfg->g_error_resilient,
167            width, "g_pass:",            cfg->g_pass,
168            width, "g_lag_in_frames:",   cfg->g_lag_in_frames);
169     av_log(avctx, level, "rate control settings\n"
170            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
171            "  %*s%d\n  %*s%p(%"SIZE_SPECIFIER")\n  %*s%u\n",
172            width, "rc_dropframe_thresh:",   cfg->rc_dropframe_thresh,
173            width, "rc_resize_allowed:",     cfg->rc_resize_allowed,
174            width, "rc_resize_up_thresh:",   cfg->rc_resize_up_thresh,
175            width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
176            width, "rc_end_usage:",          cfg->rc_end_usage,
177            width, "rc_twopass_stats_in:",   cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
178            width, "rc_target_bitrate:",     cfg->rc_target_bitrate);
179     av_log(avctx, level, "quantizer settings\n"
180            "  %*s%u\n  %*s%u\n",
181            width, "rc_min_quantizer:", cfg->rc_min_quantizer,
182            width, "rc_max_quantizer:", cfg->rc_max_quantizer);
183     av_log(avctx, level, "bitrate tolerance\n"
184            "  %*s%u\n  %*s%u\n",
185            width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
186            width, "rc_overshoot_pct:",  cfg->rc_overshoot_pct);
187     av_log(avctx, level, "decoder buffer model\n"
188             "  %*s%u\n  %*s%u\n  %*s%u\n",
189             width, "rc_buf_sz:",         cfg->rc_buf_sz,
190             width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
191             width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
192     av_log(avctx, level, "2 pass rate control settings\n"
193            "  %*s%u\n  %*s%u\n  %*s%u\n",
194            width, "rc_2pass_vbr_bias_pct:",       cfg->rc_2pass_vbr_bias_pct,
195            width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
196            width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
197     av_log(avctx, level, "keyframing settings\n"
198            "  %*s%d\n  %*s%u\n  %*s%u\n",
199            width, "kf_mode:",     cfg->kf_mode,
200            width, "kf_min_dist:", cfg->kf_min_dist,
201            width, "kf_max_dist:", cfg->kf_max_dist);
202     av_log(avctx, level, "\n");
203 }
204
205 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
206 {
207     struct FrameListData **p = list;
208
209     while (*p)
210         p = &(*p)->next;
211     *p = cx_frame;
212     cx_frame->next = NULL;
213 }
214
215 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
216 {
217     av_freep(&cx_frame->buf);
218     if (cx_frame->buf_alpha)
219         av_freep(&cx_frame->buf_alpha);
220     av_freep(&cx_frame);
221 }
222
223 static av_cold void free_frame_list(struct FrameListData *list)
224 {
225     struct FrameListData *p = list;
226
227     while (p) {
228         list = list->next;
229         free_coded_frame(p);
230         p = list;
231     }
232 }
233
234 static av_cold int codecctl_int(AVCodecContext *avctx,
235                                 enum vp8e_enc_control_id id, int val)
236 {
237     VP8Context *ctx = avctx->priv_data;
238     char buf[80];
239     int width = -30;
240     int res;
241
242     snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
243     av_log(avctx, AV_LOG_DEBUG, "  %*s%d\n", width, buf, val);
244
245     res = vpx_codec_control(&ctx->encoder, id, val);
246     if (res != VPX_CODEC_OK) {
247         snprintf(buf, sizeof(buf), "Failed to set %s codec control",
248                  ctlidstr[id]);
249         log_encoder_error(avctx, buf);
250     }
251
252     return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
253 }
254
255 static av_cold int vp8_free(AVCodecContext *avctx)
256 {
257     VP8Context *ctx = avctx->priv_data;
258
259     vpx_codec_destroy(&ctx->encoder);
260     if (ctx->is_alpha)
261         vpx_codec_destroy(&ctx->encoder_alpha);
262     av_freep(&ctx->twopass_stats.buf);
263     av_frame_free(&avctx->coded_frame);
264     av_freep(&avctx->stats_out);
265     free_frame_list(ctx->coded_frame_list);
266     return 0;
267 }
268
269 #if CONFIG_LIBVPX_VP9_ENCODER
270 static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
271                        struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
272                        vpx_img_fmt_t *img_fmt)
273 {
274 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
275     enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
276 #endif
277     switch (avctx->pix_fmt) {
278     case AV_PIX_FMT_YUV420P:
279         enccfg->g_profile = 0;
280         *img_fmt = VPX_IMG_FMT_I420;
281         return 0;
282     case AV_PIX_FMT_YUV422P:
283     case AV_PIX_FMT_YUV444P:
284         enccfg->g_profile = 1;
285         *img_fmt = avctx->pix_fmt == AV_PIX_FMT_YUV422P ? VPX_IMG_FMT_I422 : VPX_IMG_FMT_I444;
286         return 0;
287 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
288     case AV_PIX_FMT_YUV420P10LE:
289     case AV_PIX_FMT_YUV420P12LE:
290         if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
291             enccfg->g_bit_depth = enccfg->g_input_bit_depth =
292                 avctx->pix_fmt == AV_PIX_FMT_YUV420P10LE ? 10 : 12;
293             enccfg->g_profile = 2;
294             *img_fmt = VPX_IMG_FMT_I42016;
295             *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
296             return 0;
297         }
298         break;
299     case AV_PIX_FMT_YUV422P10LE:
300     case AV_PIX_FMT_YUV422P12LE:
301         if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
302             enccfg->g_bit_depth = enccfg->g_input_bit_depth =
303                 avctx->pix_fmt == AV_PIX_FMT_YUV422P10LE ? 10 : 12;
304             enccfg->g_profile = 3;
305             *img_fmt = VPX_IMG_FMT_I42216;
306             *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
307             return 0;
308         }
309         break;
310     case AV_PIX_FMT_YUV444P10LE:
311     case AV_PIX_FMT_YUV444P12LE:
312         if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
313             enccfg->g_bit_depth = enccfg->g_input_bit_depth =
314                 avctx->pix_fmt == AV_PIX_FMT_YUV444P10LE ? 10 : 12;
315             enccfg->g_profile = 3;
316             *img_fmt = VPX_IMG_FMT_I44416;
317             *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
318             return 0;
319         }
320         break;
321 #endif
322     default:
323         break;
324     }
325     av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
326     return AVERROR_INVALIDDATA;
327 }
328 #endif
329
330 static av_cold int vpx_init(AVCodecContext *avctx,
331                             const struct vpx_codec_iface *iface)
332 {
333     VP8Context *ctx = avctx->priv_data;
334     struct vpx_codec_enc_cfg enccfg;
335     struct vpx_codec_enc_cfg enccfg_alpha;
336     vpx_codec_flags_t flags = (avctx->flags & CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
337     int res;
338     vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
339 #if CONFIG_LIBVPX_VP9_ENCODER
340     vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
341 #endif
342
343     av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
344     av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
345
346     if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
347         ctx->is_alpha = 1;
348
349     if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
350         av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
351                vpx_codec_err_to_string(res));
352         return AVERROR(EINVAL);
353     }
354
355 #if CONFIG_LIBVPX_VP9_ENCODER
356     if (avctx->codec_id == AV_CODEC_ID_VP9) {
357         if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
358             return AVERROR(EINVAL);
359     }
360 #endif
361
362     if(!avctx->bit_rate)
363         if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
364             av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
365             return AVERROR(EINVAL);
366         }
367
368     dump_enc_cfg(avctx, &enccfg);
369
370     enccfg.g_w            = avctx->width;
371     enccfg.g_h            = avctx->height;
372     enccfg.g_timebase.num = avctx->time_base.num;
373     enccfg.g_timebase.den = avctx->time_base.den;
374     enccfg.g_threads      = avctx->thread_count;
375     enccfg.g_lag_in_frames= ctx->lag_in_frames;
376
377     if (avctx->flags & CODEC_FLAG_PASS1)
378         enccfg.g_pass = VPX_RC_FIRST_PASS;
379     else if (avctx->flags & CODEC_FLAG_PASS2)
380         enccfg.g_pass = VPX_RC_LAST_PASS;
381     else
382         enccfg.g_pass = VPX_RC_ONE_PASS;
383
384     if (avctx->rc_min_rate == avctx->rc_max_rate &&
385         avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
386         enccfg.rc_end_usage = VPX_CBR;
387     } else if (ctx->crf >= 0) {
388         enccfg.rc_end_usage = VPX_CQ;
389 #if CONFIG_LIBVPX_VP9_ENCODER
390         if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
391             enccfg.rc_end_usage = VPX_Q;
392 #endif
393     }
394
395     if (avctx->bit_rate) {
396         enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
397                                                   AV_ROUND_NEAR_INF);
398 #if CONFIG_LIBVPX_VP9_ENCODER
399     } else if (enccfg.rc_end_usage == VPX_Q) {
400 #endif
401     } else {
402         if (enccfg.rc_end_usage == VPX_CQ) {
403             enccfg.rc_target_bitrate = 1000000;
404         } else {
405             avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
406             av_log(avctx, AV_LOG_WARNING,
407                    "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
408                    enccfg.rc_target_bitrate);
409         }
410     }
411
412     if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
413         enccfg.rc_min_quantizer =
414         enccfg.rc_max_quantizer = 0;
415     } else {
416         if (avctx->qmin >= 0)
417             enccfg.rc_min_quantizer = avctx->qmin;
418         if (avctx->qmax >= 0)
419             enccfg.rc_max_quantizer = avctx->qmax;
420     }
421
422     if (enccfg.rc_end_usage == VPX_CQ
423 #if CONFIG_LIBVPX_VP9_ENCODER
424         || enccfg.rc_end_usage == VPX_Q
425 #endif
426        ) {
427         if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
428             av_log(avctx, AV_LOG_ERROR,
429                    "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
430                    ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
431             return AVERROR(EINVAL);
432         }
433     }
434
435     enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
436
437     //0-100 (0 => CBR, 100 => VBR)
438     enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);
439     if (avctx->bit_rate)
440         enccfg.rc_2pass_vbr_minsection_pct =
441             avctx->rc_min_rate * 100LL / avctx->bit_rate;
442     if (avctx->rc_max_rate)
443         enccfg.rc_2pass_vbr_maxsection_pct =
444             avctx->rc_max_rate * 100LL / avctx->bit_rate;
445
446     if (avctx->rc_buffer_size)
447         enccfg.rc_buf_sz         =
448             avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
449     if (avctx->rc_initial_buffer_occupancy)
450         enccfg.rc_buf_initial_sz =
451             avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
452     enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;
453     enccfg.rc_undershoot_pct     = round(avctx->rc_buffer_aggressivity * 100);
454
455     //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
456     if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
457         enccfg.kf_min_dist = avctx->keyint_min;
458     if (avctx->gop_size >= 0)
459         enccfg.kf_max_dist = avctx->gop_size;
460
461     if (enccfg.g_pass == VPX_RC_FIRST_PASS)
462         enccfg.g_lag_in_frames = 0;
463     else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
464         int decode_size, ret;
465
466         if (!avctx->stats_in) {
467             av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
468             return AVERROR_INVALIDDATA;
469         }
470
471         ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;
472         ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
473         if (ret < 0) {
474             av_log(avctx, AV_LOG_ERROR,
475                    "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
476                    ctx->twopass_stats.sz);
477             ctx->twopass_stats.sz = 0;
478             return ret;
479         }
480         decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
481                                        ctx->twopass_stats.sz);
482         if (decode_size < 0) {
483             av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
484             return AVERROR_INVALIDDATA;
485         }
486
487         ctx->twopass_stats.sz      = decode_size;
488         enccfg.rc_twopass_stats_in = ctx->twopass_stats;
489     }
490
491     /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
492        complexity playback on low powered devices at the expense of encode
493        quality. */
494     if (avctx->profile != FF_PROFILE_UNKNOWN)
495         enccfg.g_profile = avctx->profile;
496
497     enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
498
499     dump_enc_cfg(avctx, &enccfg);
500     /* Construct Encoder Context */
501     res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
502     if (res != VPX_CODEC_OK) {
503         log_encoder_error(avctx, "Failed to initialize encoder");
504         return AVERROR(EINVAL);
505     }
506
507     if (ctx->is_alpha) {
508         enccfg_alpha = enccfg;
509         res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
510         if (res != VPX_CODEC_OK) {
511             log_encoder_error(avctx, "Failed to initialize alpha encoder");
512             return AVERROR(EINVAL);
513         }
514     }
515
516     //codec control failures are currently treated only as warnings
517     av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
518     codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);
519     if (ctx->flags & VP8F_AUTO_ALT_REF)
520         ctx->auto_alt_ref = 1;
521     if (ctx->auto_alt_ref >= 0)
522         codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
523     if (ctx->arnr_max_frames >= 0)
524         codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);
525     if (ctx->arnr_strength >= 0)
526         codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);
527     if (ctx->arnr_type >= 0)
528         codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);
529     if (avctx->codec_id == AV_CODEC_ID_VP8) {
530         codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
531         codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));
532     }
533 #if FF_API_MPV_OPT
534     FF_DISABLE_DEPRECATION_WARNINGS
535     if (avctx->mb_threshold) {
536         av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
537                "use the static-thresh private option instead.\n");
538         ctx->static_thresh = avctx->mb_threshold;
539     }
540     FF_ENABLE_DEPRECATION_WARNINGS
541 #endif
542     codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  ctx->static_thresh);
543     if (ctx->crf >= 0)
544         codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);
545     if (ctx->max_intra_rate >= 0)
546         codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
547
548 #if CONFIG_LIBVPX_VP9_ENCODER
549     if (avctx->codec_id == AV_CODEC_ID_VP9) {
550         if (ctx->lossless >= 0)
551             codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
552         if (ctx->tile_columns >= 0)
553             codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
554         if (ctx->tile_rows >= 0)
555             codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
556         if (ctx->frame_parallel >= 0)
557             codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
558         if (ctx->aq_mode >= 0)
559             codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
560     }
561 #endif
562
563     av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
564
565     //provide dummy value to initialize wrapper, values will be updated each _encode()
566     vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
567                  (unsigned char*)1);
568 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
569     if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
570         ctx->rawimg.bit_depth = enccfg.g_bit_depth;
571 #endif
572
573     if (ctx->is_alpha)
574         vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
575                      (unsigned char*)1);
576
577     avctx->coded_frame = av_frame_alloc();
578     if (!avctx->coded_frame) {
579         av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
580         vp8_free(avctx);
581         return AVERROR(ENOMEM);
582     }
583     return 0;
584 }
585
586 static inline void cx_pktcpy(struct FrameListData *dst,
587                              const struct vpx_codec_cx_pkt *src,
588                              const struct vpx_codec_cx_pkt *src_alpha,
589                              VP8Context *ctx)
590 {
591     dst->pts      = src->data.frame.pts;
592     dst->duration = src->data.frame.duration;
593     dst->flags    = src->data.frame.flags;
594     dst->sz       = src->data.frame.sz;
595     dst->buf      = src->data.frame.buf;
596     dst->have_sse = 0;
597     /* For alt-ref frame, don't store PSNR or increment frame_number */
598     if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
599         dst->frame_number = ++ctx->frame_number;
600         dst->have_sse = ctx->have_sse;
601         if (ctx->have_sse) {
602             /* associate last-seen SSE to the frame. */
603             /* Transfers ownership from ctx to dst. */
604             /* WARNING! This makes the assumption that PSNR_PKT comes
605                just before the frame it refers to! */
606             memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
607             ctx->have_sse = 0;
608         }
609     } else {
610         dst->frame_number = -1;   /* sanity marker */
611     }
612     if (src_alpha) {
613         dst->buf_alpha = src_alpha->data.frame.buf;
614         dst->sz_alpha = src_alpha->data.frame.sz;
615     } else {
616         dst->buf_alpha = NULL;
617         dst->sz_alpha = 0;
618     }
619 }
620
621 /**
622  * Store coded frame information in format suitable for return from encode2().
623  *
624  * Write information from @a cx_frame to @a pkt
625  * @return packet data size on success
626  * @return a negative AVERROR on error
627  */
628 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
629                       AVPacket *pkt, AVFrame *coded_frame)
630 {
631     int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz);
632     uint8_t *side_data;
633     if (ret >= 0) {
634         memcpy(pkt->data, cx_frame->buf, pkt->size);
635         pkt->pts = pkt->dts    = cx_frame->pts;
636         coded_frame->pts       = cx_frame->pts;
637         coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
638
639         if (coded_frame->key_frame) {
640             coded_frame->pict_type = AV_PICTURE_TYPE_I;
641             pkt->flags            |= AV_PKT_FLAG_KEY;
642         } else
643             coded_frame->pict_type = AV_PICTURE_TYPE_P;
644
645         if (cx_frame->have_sse) {
646             int i;
647             /* Beware of the Y/U/V/all order! */
648             coded_frame->error[0] = cx_frame->sse[1];
649             coded_frame->error[1] = cx_frame->sse[2];
650             coded_frame->error[2] = cx_frame->sse[3];
651             coded_frame->error[3] = 0;    // alpha
652             for (i = 0; i < 4; ++i) {
653                 avctx->error[i] += coded_frame->error[i];
654             }
655             cx_frame->have_sse = 0;
656         }
657         if (cx_frame->sz_alpha > 0) {
658             side_data = av_packet_new_side_data(pkt,
659                                                 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
660                                                 cx_frame->sz_alpha + 8);
661             if(!side_data) {
662                 av_free_packet(pkt);
663                 av_free(pkt);
664                 return AVERROR(ENOMEM);
665             }
666             AV_WB64(side_data, 1);
667             memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
668         }
669     } else {
670         return ret;
671     }
672     return pkt->size;
673 }
674
675 /**
676  * Queue multiple output frames from the encoder, returning the front-most.
677  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
678  * the frame queue. Return the head frame if available.
679  * @return Stored frame size
680  * @return AVERROR(EINVAL) on output size error
681  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
682  */
683 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out,
684                         AVFrame *coded_frame)
685 {
686     VP8Context *ctx = avctx->priv_data;
687     const struct vpx_codec_cx_pkt *pkt;
688     const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
689     const void *iter = NULL;
690     const void *iter_alpha = NULL;
691     int size = 0;
692
693     if (ctx->coded_frame_list) {
694         struct FrameListData *cx_frame = ctx->coded_frame_list;
695         /* return the leading frame if we've already begun queueing */
696         size = storeframe(avctx, cx_frame, pkt_out, coded_frame);
697         if (size < 0)
698             return size;
699         ctx->coded_frame_list = cx_frame->next;
700         free_coded_frame(cx_frame);
701     }
702
703     /* consume all available output from the encoder before returning. buffers
704        are only good through the next vpx_codec call */
705     while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
706            (!ctx->is_alpha ||
707             (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
708         switch (pkt->kind) {
709         case VPX_CODEC_CX_FRAME_PKT:
710             if (!size) {
711                 struct FrameListData cx_frame;
712
713                 /* avoid storing the frame when the list is empty and we haven't yet
714                    provided a frame for output */
715                 av_assert0(!ctx->coded_frame_list);
716                 cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
717                 size = storeframe(avctx, &cx_frame, pkt_out, coded_frame);
718                 if (size < 0)
719                     return size;
720             } else {
721                 struct FrameListData *cx_frame =
722                     av_malloc(sizeof(struct FrameListData));
723
724                 if (!cx_frame) {
725                     av_log(avctx, AV_LOG_ERROR,
726                            "Frame queue element alloc failed\n");
727                     return AVERROR(ENOMEM);
728                 }
729                 cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
730                 cx_frame->buf = av_malloc(cx_frame->sz);
731
732                 if (!cx_frame->buf) {
733                     av_log(avctx, AV_LOG_ERROR,
734                            "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
735                            cx_frame->sz);
736                     av_freep(&cx_frame);
737                     return AVERROR(ENOMEM);
738                 }
739                 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
740                 if (ctx->is_alpha) {
741                     cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
742                     if (!cx_frame->buf_alpha) {
743                         av_log(avctx, AV_LOG_ERROR,
744                                "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
745                                cx_frame->sz_alpha);
746                         av_free(cx_frame);
747                         return AVERROR(ENOMEM);
748                     }
749                     memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
750                 }
751                 coded_frame_add(&ctx->coded_frame_list, cx_frame);
752             }
753             break;
754         case VPX_CODEC_STATS_PKT: {
755             struct vpx_fixed_buf *stats = &ctx->twopass_stats;
756             int err;
757             if ((err = av_reallocp(&stats->buf,
758                                    stats->sz +
759                                    pkt->data.twopass_stats.sz)) < 0) {
760                 stats->sz = 0;
761                 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
762                 return err;
763             }
764             memcpy((uint8_t*)stats->buf + stats->sz,
765                    pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
766             stats->sz += pkt->data.twopass_stats.sz;
767             break;
768         }
769         case VPX_CODEC_PSNR_PKT:
770             av_assert0(!ctx->have_sse);
771             ctx->sse[0] = pkt->data.psnr.sse[0];
772             ctx->sse[1] = pkt->data.psnr.sse[1];
773             ctx->sse[2] = pkt->data.psnr.sse[2];
774             ctx->sse[3] = pkt->data.psnr.sse[3];
775             ctx->have_sse = 1;
776             break;
777         case VPX_CODEC_CUSTOM_PKT:
778             //ignore unsupported/unrecognized packet types
779             break;
780         }
781     }
782
783     return size;
784 }
785
786 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
787                       const AVFrame *frame, int *got_packet)
788 {
789     VP8Context *ctx = avctx->priv_data;
790     struct vpx_image *rawimg = NULL;
791     struct vpx_image *rawimg_alpha = NULL;
792     int64_t timestamp = 0;
793     int res, coded_size;
794     vpx_enc_frame_flags_t flags = 0;
795
796     if (frame) {
797         rawimg                      = &ctx->rawimg;
798         rawimg->planes[VPX_PLANE_Y] = frame->data[0];
799         rawimg->planes[VPX_PLANE_U] = frame->data[1];
800         rawimg->planes[VPX_PLANE_V] = frame->data[2];
801         rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
802         rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
803         rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
804         if (ctx->is_alpha) {
805             uint8_t *u_plane, *v_plane;
806             rawimg_alpha = &ctx->rawimg_alpha;
807             rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
808             u_plane = av_malloc(frame->linesize[1] * frame->height);
809             v_plane = av_malloc(frame->linesize[2] * frame->height);
810             if (!u_plane || !v_plane) {
811                 av_free(u_plane);
812                 av_free(v_plane);
813                 return AVERROR(ENOMEM);
814             }
815             memset(u_plane, 0x80, frame->linesize[1] * frame->height);
816             rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
817             memset(v_plane, 0x80, frame->linesize[2] * frame->height);
818             rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
819             rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
820             rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
821             rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
822         }
823         timestamp                   = frame->pts;
824         if (frame->pict_type == AV_PICTURE_TYPE_I)
825             flags |= VPX_EFLAG_FORCE_KF;
826     }
827
828     res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
829                            avctx->ticks_per_frame, flags, ctx->deadline);
830     if (res != VPX_CODEC_OK) {
831         log_encoder_error(avctx, "Error encoding frame");
832         return AVERROR_INVALIDDATA;
833     }
834
835     if (ctx->is_alpha) {
836         res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
837                                avctx->ticks_per_frame, flags, ctx->deadline);
838         if (res != VPX_CODEC_OK) {
839             log_encoder_error(avctx, "Error encoding alpha frame");
840             return AVERROR_INVALIDDATA;
841         }
842     }
843
844     coded_size = queue_frames(avctx, pkt, avctx->coded_frame);
845
846     if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
847         unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
848
849         avctx->stats_out = av_malloc(b64_size);
850         if (!avctx->stats_out) {
851             av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
852                    b64_size);
853             return AVERROR(ENOMEM);
854         }
855         av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
856                          ctx->twopass_stats.sz);
857     }
858
859     if (rawimg_alpha) {
860         av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
861         av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
862     }
863
864     *got_packet = !!coded_size;
865     return 0;
866 }
867
868 #define OFFSET(x) offsetof(VP8Context, x)
869 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
870
871 #ifndef VPX_ERROR_RESILIENT_DEFAULT
872 #define VPX_ERROR_RESILIENT_DEFAULT 1
873 #define VPX_ERROR_RESILIENT_PARTITIONS 2
874 #endif
875
876 #define COMMON_OPTIONS \
877     { "cpu-used",        "Quality/Speed ratio modifier",           OFFSET(cpu_used),        AV_OPT_TYPE_INT, {.i64 = 1},       -16,     16,      VE}, \
878     { "auto-alt-ref",    "Enable use of alternate reference " \
879                          "frames (2-pass only)",                   OFFSET(auto_alt_ref),    AV_OPT_TYPE_INT, {.i64 = -1},      -1,      1,       VE}, \
880     { "lag-in-frames",   "Number of frames to look ahead for " \
881                          "alternate reference frame selection",    OFFSET(lag_in_frames),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
882     { "arnr-maxframes",  "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
883     { "arnr-strength",   "altref noise reduction filter strength", OFFSET(arnr_strength),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
884     { "arnr-type",       "altref noise reduction filter type",     OFFSET(arnr_type),       AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE, "arnr_type"}, \
885     { "backward",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
886     { "forward",         NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
887     { "centered",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
888     { "deadline",        "Time to spend encoding, in microseconds.", OFFSET(deadline),      AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
889     { "best",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
890     { "good",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
891     { "realtime",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME},     0, 0, VE, "quality"}, \
892     { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
893     { "max-intra-rate",  "Maximum I-frame bitrate (pct) 0=unlimited",  OFFSET(max_intra_rate),  AV_OPT_TYPE_INT,  {.i64 = -1}, -1,      INT_MAX, VE}, \
894     { "default",         "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
895     { "partitions",      "The frame partitions are independently decodable " \
896                          "by the bool decoder, meaning that partitions can be decoded even " \
897                          "though earlier partitions have been lost. Note that intra predicition" \
898                          " is still done over the partition boundary.",       0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
899     { "crf",              "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
900     { "static-thresh",    "A change threshold on blocks below which they will be skipped by the encoder", OFFSET(static_thresh), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE }, \
901
902 #define LEGACY_OPTIONS \
903     {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
904     {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
905     {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
906     {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
907     {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"}, \
908     {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
909     {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
910     {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
911     {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE}, \
912
913 #if CONFIG_LIBVPX_VP8_ENCODER
914 static const AVOption vp8_options[] = {
915     COMMON_OPTIONS
916     LEGACY_OPTIONS
917     { NULL }
918 };
919 #endif
920
921 #if CONFIG_LIBVPX_VP9_ENCODER
922 static const AVOption vp9_options[] = {
923     COMMON_OPTIONS
924     { "lossless",        "Lossless mode",                               OFFSET(lossless),        AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
925     { "tile-columns",    "Number of tile columns to use, log2",         OFFSET(tile_columns),    AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
926     { "tile-rows",       "Number of tile rows to use, log2",            OFFSET(tile_rows),       AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
927     { "frame-parallel",  "Enable frame parallel decodability features", OFFSET(frame_parallel),  AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
928     { "aq-mode",         "adaptive quantization mode",                  OFFSET(aq_mode),         AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
929     { "none",            "Aq not used",         0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" }, \
930     { "variance",        "Variance based Aq",   0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" }, \
931     { "complexity",      "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" }, \
932     { "cyclic",          "Cyclic Refresh Aq",   0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" }, \
933     LEGACY_OPTIONS
934     { NULL }
935 };
936 #endif
937
938 #undef COMMON_OPTIONS
939 #undef LEGACY_OPTIONS
940
941 static const AVCodecDefault defaults[] = {
942     { "qmin",             "-1" },
943     { "qmax",             "-1" },
944     { "g",                "-1" },
945     { "keyint_min",       "-1" },
946     { NULL },
947 };
948
949 #if CONFIG_LIBVPX_VP8_ENCODER
950 static av_cold int vp8_init(AVCodecContext *avctx)
951 {
952     return vpx_init(avctx, vpx_codec_vp8_cx());
953 }
954
955 static const AVClass class_vp8 = {
956     .class_name = "libvpx-vp8 encoder",
957     .item_name  = av_default_item_name,
958     .option     = vp8_options,
959     .version    = LIBAVUTIL_VERSION_INT,
960 };
961
962 AVCodec ff_libvpx_vp8_encoder = {
963     .name           = "libvpx",
964     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP8"),
965     .type           = AVMEDIA_TYPE_VIDEO,
966     .id             = AV_CODEC_ID_VP8,
967     .priv_data_size = sizeof(VP8Context),
968     .init           = vp8_init,
969     .encode2        = vp8_encode,
970     .close          = vp8_free,
971     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
972     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
973     .priv_class     = &class_vp8,
974     .defaults       = defaults,
975 };
976 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
977
978 #if CONFIG_LIBVPX_VP9_ENCODER
979 static av_cold int vp9_init(AVCodecContext *avctx)
980 {
981     return vpx_init(avctx, vpx_codec_vp9_cx());
982 }
983
984 static const AVClass class_vp9 = {
985     .class_name = "libvpx-vp9 encoder",
986     .item_name  = av_default_item_name,
987     .option     = vp9_options,
988     .version    = LIBAVUTIL_VERSION_INT,
989 };
990
991 AVCodec ff_libvpx_vp9_encoder = {
992     .name           = "libvpx-vp9",
993     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP9"),
994     .type           = AVMEDIA_TYPE_VIDEO,
995     .id             = AV_CODEC_ID_VP9,
996     .priv_data_size = sizeof(VP8Context),
997     .init           = vp9_init,
998     .encode2        = vp8_encode,
999     .close          = vp8_free,
1000     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
1001     .priv_class     = &class_vp9,
1002     .defaults       = defaults,
1003     .init_static_data = ff_vp9_init_static,
1004 };
1005 #endif /* CONFIG_LIBVPX_VP9_ENCODER */