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