]> git.sesse.net Git - ffmpeg/blob - libavcodec/libvpxenc.c
Merge commit 'c34df422628e6b7b657faee241fe7bb2629e0f57'
[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     AVCPBProperties *cpb_props;
379     int res;
380     vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
381 #if CONFIG_LIBVPX_VP9_ENCODER
382     vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
383 #endif
384
385     av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
386     av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
387
388     if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
389         ctx->is_alpha = 1;
390
391     if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
392         av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
393                vpx_codec_err_to_string(res));
394         return AVERROR(EINVAL);
395     }
396
397 #if CONFIG_LIBVPX_VP9_ENCODER
398     if (avctx->codec_id == AV_CODEC_ID_VP9) {
399         if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
400             return AVERROR(EINVAL);
401     }
402 #endif
403
404     if(!avctx->bit_rate)
405         if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
406             av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
407             return AVERROR(EINVAL);
408         }
409
410     dump_enc_cfg(avctx, &enccfg);
411
412     enccfg.g_w            = avctx->width;
413     enccfg.g_h            = avctx->height;
414     enccfg.g_timebase.num = avctx->time_base.num;
415     enccfg.g_timebase.den = avctx->time_base.den;
416     enccfg.g_threads      = avctx->thread_count;
417     enccfg.g_lag_in_frames= ctx->lag_in_frames;
418
419     if (avctx->flags & AV_CODEC_FLAG_PASS1)
420         enccfg.g_pass = VPX_RC_FIRST_PASS;
421     else if (avctx->flags & AV_CODEC_FLAG_PASS2)
422         enccfg.g_pass = VPX_RC_LAST_PASS;
423     else
424         enccfg.g_pass = VPX_RC_ONE_PASS;
425
426     if (avctx->rc_min_rate == avctx->rc_max_rate &&
427         avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
428         enccfg.rc_end_usage = VPX_CBR;
429     } else if (ctx->crf >= 0) {
430         enccfg.rc_end_usage = VPX_CQ;
431 #if CONFIG_LIBVPX_VP9_ENCODER
432         if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
433             enccfg.rc_end_usage = VPX_Q;
434 #endif
435     }
436
437     if (avctx->bit_rate) {
438         enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
439                                                   AV_ROUND_NEAR_INF);
440 #if CONFIG_LIBVPX_VP9_ENCODER
441     } else if (enccfg.rc_end_usage == VPX_Q) {
442 #endif
443     } else {
444         if (enccfg.rc_end_usage == VPX_CQ) {
445             enccfg.rc_target_bitrate = 1000000;
446         } else {
447             avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
448             av_log(avctx, AV_LOG_WARNING,
449                    "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
450                    enccfg.rc_target_bitrate);
451         }
452     }
453
454     if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
455         enccfg.rc_min_quantizer =
456         enccfg.rc_max_quantizer = 0;
457     } else {
458         if (avctx->qmin >= 0)
459             enccfg.rc_min_quantizer = avctx->qmin;
460         if (avctx->qmax >= 0)
461             enccfg.rc_max_quantizer = avctx->qmax;
462     }
463
464     if (enccfg.rc_end_usage == VPX_CQ
465 #if CONFIG_LIBVPX_VP9_ENCODER
466         || enccfg.rc_end_usage == VPX_Q
467 #endif
468        ) {
469         if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
470             av_log(avctx, AV_LOG_ERROR,
471                    "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
472                    ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
473             return AVERROR(EINVAL);
474         }
475     }
476
477     enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
478
479     //0-100 (0 => CBR, 100 => VBR)
480     enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);
481     if (avctx->bit_rate)
482         enccfg.rc_2pass_vbr_minsection_pct =
483             avctx->rc_min_rate * 100LL / avctx->bit_rate;
484     if (avctx->rc_max_rate)
485         enccfg.rc_2pass_vbr_maxsection_pct =
486             avctx->rc_max_rate * 100LL / avctx->bit_rate;
487
488     if (avctx->rc_buffer_size)
489         enccfg.rc_buf_sz         =
490             avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
491     if (avctx->rc_initial_buffer_occupancy)
492         enccfg.rc_buf_initial_sz =
493             avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
494     enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;
495 #if FF_API_MPV_OPT
496     FF_DISABLE_DEPRECATION_WARNINGS
497     if (avctx->rc_buffer_aggressivity != 1.0) {
498         av_log(avctx, AV_LOG_WARNING, "The rc_buffer_aggressivity option is "
499                "deprecated, use the undershoot-pct private option instead.\n");
500         enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
501     }
502     FF_ENABLE_DEPRECATION_WARNINGS
503 #endif
504     if (ctx->rc_undershoot_pct >= 0)
505         enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
506     if (ctx->rc_overshoot_pct >= 0)
507         enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
508
509     //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
510     if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
511         enccfg.kf_min_dist = avctx->keyint_min;
512     if (avctx->gop_size >= 0)
513         enccfg.kf_max_dist = avctx->gop_size;
514
515     if (enccfg.g_pass == VPX_RC_FIRST_PASS)
516         enccfg.g_lag_in_frames = 0;
517     else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
518         int decode_size, ret;
519
520         if (!avctx->stats_in) {
521             av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
522             return AVERROR_INVALIDDATA;
523         }
524
525         ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;
526         ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
527         if (ret < 0) {
528             av_log(avctx, AV_LOG_ERROR,
529                    "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
530                    ctx->twopass_stats.sz);
531             ctx->twopass_stats.sz = 0;
532             return ret;
533         }
534         decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
535                                        ctx->twopass_stats.sz);
536         if (decode_size < 0) {
537             av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
538             return AVERROR_INVALIDDATA;
539         }
540
541         ctx->twopass_stats.sz      = decode_size;
542         enccfg.rc_twopass_stats_in = ctx->twopass_stats;
543     }
544
545     /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
546        complexity playback on low powered devices at the expense of encode
547        quality. */
548     if (avctx->profile != FF_PROFILE_UNKNOWN)
549         enccfg.g_profile = avctx->profile;
550
551     enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
552
553     dump_enc_cfg(avctx, &enccfg);
554     /* Construct Encoder Context */
555     res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
556     if (res != VPX_CODEC_OK) {
557         log_encoder_error(avctx, "Failed to initialize encoder");
558         return AVERROR(EINVAL);
559     }
560
561     if (ctx->is_alpha) {
562         enccfg_alpha = enccfg;
563         res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
564         if (res != VPX_CODEC_OK) {
565             log_encoder_error(avctx, "Failed to initialize alpha encoder");
566             return AVERROR(EINVAL);
567         }
568     }
569
570     //codec control failures are currently treated only as warnings
571     av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
572     codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);
573     if (ctx->flags & VP8F_AUTO_ALT_REF)
574         ctx->auto_alt_ref = 1;
575     if (ctx->auto_alt_ref >= 0)
576         codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
577     if (ctx->arnr_max_frames >= 0)
578         codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);
579     if (ctx->arnr_strength >= 0)
580         codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);
581     if (ctx->arnr_type >= 0)
582         codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);
583
584     if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
585         codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
586         codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));
587     }
588 #if FF_API_MPV_OPT
589     FF_DISABLE_DEPRECATION_WARNINGS
590     if (avctx->mb_threshold) {
591         av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
592                "use the static-thresh private option instead.\n");
593         ctx->static_thresh = avctx->mb_threshold;
594     }
595     FF_ENABLE_DEPRECATION_WARNINGS
596 #endif
597     codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  ctx->static_thresh);
598     if (ctx->crf >= 0)
599         codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);
600     if (ctx->max_intra_rate >= 0)
601         codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
602
603 #if CONFIG_LIBVPX_VP9_ENCODER
604     if (avctx->codec_id == AV_CODEC_ID_VP9) {
605         if (ctx->lossless >= 0)
606             codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
607         if (ctx->tile_columns >= 0)
608             codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
609         if (ctx->tile_rows >= 0)
610             codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
611         if (ctx->frame_parallel >= 0)
612             codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
613         if (ctx->aq_mode >= 0)
614             codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
615 #if VPX_ENCODER_ABI_VERSION > 8
616         set_colorspace(avctx);
617 #endif
618     }
619 #endif
620
621     av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
622
623     //provide dummy value to initialize wrapper, values will be updated each _encode()
624     vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
625                  (unsigned char*)1);
626 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
627     if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
628         ctx->rawimg.bit_depth = enccfg.g_bit_depth;
629 #endif
630
631     if (ctx->is_alpha)
632         vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
633                      (unsigned char*)1);
634
635     cpb_props = ff_add_cpb_side_data(avctx);
636     if (!cpb_props)
637         return AVERROR(ENOMEM);
638
639     if (enccfg.rc_end_usage == VPX_CBR ||
640         enccfg.g_pass != VPX_RC_ONE_PASS) {
641         cpb_props->max_bitrate = avctx->rc_max_rate;
642         cpb_props->min_bitrate = avctx->rc_min_rate;
643         cpb_props->avg_bitrate = avctx->bit_rate;
644     }
645     cpb_props->buffer_size = avctx->rc_buffer_size;
646
647     return 0;
648 }
649
650 static inline void cx_pktcpy(struct FrameListData *dst,
651                              const struct vpx_codec_cx_pkt *src,
652                              const struct vpx_codec_cx_pkt *src_alpha,
653                              VP8Context *ctx)
654 {
655     dst->pts      = src->data.frame.pts;
656     dst->duration = src->data.frame.duration;
657     dst->flags    = src->data.frame.flags;
658     dst->sz       = src->data.frame.sz;
659     dst->buf      = src->data.frame.buf;
660     dst->have_sse = 0;
661     /* For alt-ref frame, don't store PSNR or increment frame_number */
662     if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
663         dst->frame_number = ++ctx->frame_number;
664         dst->have_sse = ctx->have_sse;
665         if (ctx->have_sse) {
666             /* associate last-seen SSE to the frame. */
667             /* Transfers ownership from ctx to dst. */
668             /* WARNING! This makes the assumption that PSNR_PKT comes
669                just before the frame it refers to! */
670             memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
671             ctx->have_sse = 0;
672         }
673     } else {
674         dst->frame_number = -1;   /* sanity marker */
675     }
676     if (src_alpha) {
677         dst->buf_alpha = src_alpha->data.frame.buf;
678         dst->sz_alpha = src_alpha->data.frame.sz;
679     } else {
680         dst->buf_alpha = NULL;
681         dst->sz_alpha = 0;
682     }
683 }
684
685 /**
686  * Store coded frame information in format suitable for return from encode2().
687  *
688  * Write information from @a cx_frame to @a pkt
689  * @return packet data size on success
690  * @return a negative AVERROR on error
691  */
692 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
693                       AVPacket *pkt)
694 {
695     int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
696     uint8_t *side_data;
697     if (ret >= 0) {
698         int pict_type;
699         memcpy(pkt->data, cx_frame->buf, pkt->size);
700         pkt->pts = pkt->dts = cx_frame->pts;
701 #if FF_API_CODED_FRAME
702 FF_DISABLE_DEPRECATION_WARNINGS
703         avctx->coded_frame->pts       = cx_frame->pts;
704         avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
705 FF_ENABLE_DEPRECATION_WARNINGS
706 #endif
707
708         if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
709             pict_type = AV_PICTURE_TYPE_I;
710 #if FF_API_CODED_FRAME
711 FF_DISABLE_DEPRECATION_WARNINGS
712             avctx->coded_frame->pict_type = pict_type;
713 FF_ENABLE_DEPRECATION_WARNINGS
714 #endif
715             pkt->flags |= AV_PKT_FLAG_KEY;
716         } else {
717             pict_type = AV_PICTURE_TYPE_P;
718 #if FF_API_CODED_FRAME
719 FF_DISABLE_DEPRECATION_WARNINGS
720             avctx->coded_frame->pict_type = pict_type;
721 FF_ENABLE_DEPRECATION_WARNINGS
722 #endif
723         }
724
725         ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
726                                        cx_frame->have_sse ? 3 : 0, pict_type);
727
728         if (cx_frame->have_sse) {
729             int i;
730             /* Beware of the Y/U/V/all order! */
731 #if FF_API_CODED_FRAME
732 FF_DISABLE_DEPRECATION_WARNINGS
733             avctx->coded_frame->error[0] = cx_frame->sse[1];
734             avctx->coded_frame->error[1] = cx_frame->sse[2];
735             avctx->coded_frame->error[2] = cx_frame->sse[3];
736             avctx->coded_frame->error[3] = 0;    // alpha
737 FF_ENABLE_DEPRECATION_WARNINGS
738 #endif
739             for (i = 0; i < 3; ++i) {
740                 avctx->error[i] += cx_frame->sse[i + 1];
741             }
742             cx_frame->have_sse = 0;
743         }
744         if (cx_frame->sz_alpha > 0) {
745             side_data = av_packet_new_side_data(pkt,
746                                                 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
747                                                 cx_frame->sz_alpha + 8);
748             if(!side_data) {
749                 av_packet_unref(pkt);
750                 av_free(pkt);
751                 return AVERROR(ENOMEM);
752             }
753             AV_WB64(side_data, 1);
754             memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
755         }
756     } else {
757         return ret;
758     }
759     return pkt->size;
760 }
761
762 /**
763  * Queue multiple output frames from the encoder, returning the front-most.
764  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
765  * the frame queue. Return the head frame if available.
766  * @return Stored frame size
767  * @return AVERROR(EINVAL) on output size error
768  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
769  */
770 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
771 {
772     VP8Context *ctx = avctx->priv_data;
773     const struct vpx_codec_cx_pkt *pkt;
774     const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
775     const void *iter = NULL;
776     const void *iter_alpha = NULL;
777     int size = 0;
778
779     if (ctx->coded_frame_list) {
780         struct FrameListData *cx_frame = ctx->coded_frame_list;
781         /* return the leading frame if we've already begun queueing */
782         size = storeframe(avctx, cx_frame, pkt_out);
783         if (size < 0)
784             return size;
785         ctx->coded_frame_list = cx_frame->next;
786         free_coded_frame(cx_frame);
787     }
788
789     /* consume all available output from the encoder before returning. buffers
790        are only good through the next vpx_codec call */
791     while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
792            (!ctx->is_alpha ||
793             (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
794         switch (pkt->kind) {
795         case VPX_CODEC_CX_FRAME_PKT:
796             if (!size) {
797                 struct FrameListData cx_frame;
798
799                 /* avoid storing the frame when the list is empty and we haven't yet
800                    provided a frame for output */
801                 av_assert0(!ctx->coded_frame_list);
802                 cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
803                 size = storeframe(avctx, &cx_frame, pkt_out);
804                 if (size < 0)
805                     return size;
806             } else {
807                 struct FrameListData *cx_frame =
808                     av_malloc(sizeof(struct FrameListData));
809
810                 if (!cx_frame) {
811                     av_log(avctx, AV_LOG_ERROR,
812                            "Frame queue element alloc failed\n");
813                     return AVERROR(ENOMEM);
814                 }
815                 cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
816                 cx_frame->buf = av_malloc(cx_frame->sz);
817
818                 if (!cx_frame->buf) {
819                     av_log(avctx, AV_LOG_ERROR,
820                            "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
821                            cx_frame->sz);
822                     av_freep(&cx_frame);
823                     return AVERROR(ENOMEM);
824                 }
825                 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
826                 if (ctx->is_alpha) {
827                     cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
828                     if (!cx_frame->buf_alpha) {
829                         av_log(avctx, AV_LOG_ERROR,
830                                "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
831                                cx_frame->sz_alpha);
832                         av_free(cx_frame);
833                         return AVERROR(ENOMEM);
834                     }
835                     memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
836                 }
837                 coded_frame_add(&ctx->coded_frame_list, cx_frame);
838             }
839             break;
840         case VPX_CODEC_STATS_PKT: {
841             struct vpx_fixed_buf *stats = &ctx->twopass_stats;
842             int err;
843             if ((err = av_reallocp(&stats->buf,
844                                    stats->sz +
845                                    pkt->data.twopass_stats.sz)) < 0) {
846                 stats->sz = 0;
847                 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
848                 return err;
849             }
850             memcpy((uint8_t*)stats->buf + stats->sz,
851                    pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
852             stats->sz += pkt->data.twopass_stats.sz;
853             break;
854         }
855         case VPX_CODEC_PSNR_PKT:
856             av_assert0(!ctx->have_sse);
857             ctx->sse[0] = pkt->data.psnr.sse[0];
858             ctx->sse[1] = pkt->data.psnr.sse[1];
859             ctx->sse[2] = pkt->data.psnr.sse[2];
860             ctx->sse[3] = pkt->data.psnr.sse[3];
861             ctx->have_sse = 1;
862             break;
863         case VPX_CODEC_CUSTOM_PKT:
864             //ignore unsupported/unrecognized packet types
865             break;
866         }
867     }
868
869     return size;
870 }
871
872 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
873                       const AVFrame *frame, int *got_packet)
874 {
875     VP8Context *ctx = avctx->priv_data;
876     struct vpx_image *rawimg = NULL;
877     struct vpx_image *rawimg_alpha = NULL;
878     int64_t timestamp = 0;
879     int res, coded_size;
880     vpx_enc_frame_flags_t flags = 0;
881
882     if (frame) {
883         rawimg                      = &ctx->rawimg;
884         rawimg->planes[VPX_PLANE_Y] = frame->data[0];
885         rawimg->planes[VPX_PLANE_U] = frame->data[1];
886         rawimg->planes[VPX_PLANE_V] = frame->data[2];
887         rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
888         rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
889         rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
890         if (ctx->is_alpha) {
891             uint8_t *u_plane, *v_plane;
892             rawimg_alpha = &ctx->rawimg_alpha;
893             rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
894             u_plane = av_malloc(frame->linesize[1] * frame->height);
895             v_plane = av_malloc(frame->linesize[2] * frame->height);
896             if (!u_plane || !v_plane) {
897                 av_free(u_plane);
898                 av_free(v_plane);
899                 return AVERROR(ENOMEM);
900             }
901             memset(u_plane, 0x80, frame->linesize[1] * frame->height);
902             rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
903             memset(v_plane, 0x80, frame->linesize[2] * frame->height);
904             rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
905             rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
906             rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
907             rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
908         }
909         timestamp                   = frame->pts;
910         if (frame->pict_type == AV_PICTURE_TYPE_I)
911             flags |= VPX_EFLAG_FORCE_KF;
912     }
913
914     res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
915                            avctx->ticks_per_frame, flags, ctx->deadline);
916     if (res != VPX_CODEC_OK) {
917         log_encoder_error(avctx, "Error encoding frame");
918         return AVERROR_INVALIDDATA;
919     }
920
921     if (ctx->is_alpha) {
922         res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
923                                avctx->ticks_per_frame, flags, ctx->deadline);
924         if (res != VPX_CODEC_OK) {
925             log_encoder_error(avctx, "Error encoding alpha frame");
926             return AVERROR_INVALIDDATA;
927         }
928     }
929
930     coded_size = queue_frames(avctx, pkt);
931
932     if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
933         unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
934
935         avctx->stats_out = av_malloc(b64_size);
936         if (!avctx->stats_out) {
937             av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
938                    b64_size);
939             return AVERROR(ENOMEM);
940         }
941         av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
942                          ctx->twopass_stats.sz);
943     }
944
945     if (rawimg_alpha) {
946         av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
947         av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
948     }
949
950     *got_packet = !!coded_size;
951     return 0;
952 }
953
954 #define OFFSET(x) offsetof(VP8Context, x)
955 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
956
957 #ifndef VPX_ERROR_RESILIENT_DEFAULT
958 #define VPX_ERROR_RESILIENT_DEFAULT 1
959 #define VPX_ERROR_RESILIENT_PARTITIONS 2
960 #endif
961
962 #define COMMON_OPTIONS \
963     { "cpu-used",        "Quality/Speed ratio modifier",           OFFSET(cpu_used),        AV_OPT_TYPE_INT, {.i64 = 1},       -16,     16,      VE}, \
964     { "auto-alt-ref",    "Enable use of alternate reference " \
965                          "frames (2-pass only)",                   OFFSET(auto_alt_ref),    AV_OPT_TYPE_BOOL, {.i64 = -1},     -1,      1,       VE}, \
966     { "lag-in-frames",   "Number of frames to look ahead for " \
967                          "alternate reference frame selection",    OFFSET(lag_in_frames),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
968     { "arnr-maxframes",  "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
969     { "arnr-strength",   "altref noise reduction filter strength", OFFSET(arnr_strength),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
970     { "arnr-type",       "altref noise reduction filter type",     OFFSET(arnr_type),       AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE, "arnr_type"}, \
971     { "backward",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
972     { "forward",         NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
973     { "centered",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
974     { "deadline",        "Time to spend encoding, in microseconds.", OFFSET(deadline),      AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
975     { "best",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
976     { "good",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
977     { "realtime",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME},     0, 0, VE, "quality"}, \
978     { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
979     { "max-intra-rate",  "Maximum I-frame bitrate (pct) 0=unlimited",  OFFSET(max_intra_rate),  AV_OPT_TYPE_INT,  {.i64 = -1}, -1,      INT_MAX, VE}, \
980     { "default",         "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
981     { "partitions",      "The frame partitions are independently decodable " \
982                          "by the bool decoder, meaning that partitions can be decoded even " \
983                          "though earlier partitions have been lost. Note that intra predicition" \
984                          " is still done over the partition boundary.",       0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
985     { "crf",              "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
986     { "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 }, \
987     { "undershoot-pct",  "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
988     { "overshoot-pct",   "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
989
990 #define LEGACY_OPTIONS \
991     {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
992     {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
993     {"vp8flags", "", offsetof(VP8Context, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
994     {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
995     {"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"}, \
996     {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
997     {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
998     {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
999     {"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}, \
1000
1001 #if CONFIG_LIBVPX_VP8_ENCODER
1002 static const AVOption vp8_options[] = {
1003     COMMON_OPTIONS
1004     LEGACY_OPTIONS
1005     { NULL }
1006 };
1007 #endif
1008
1009 #if CONFIG_LIBVPX_VP9_ENCODER
1010 static const AVOption vp9_options[] = {
1011     COMMON_OPTIONS
1012     { "lossless",        "Lossless mode",                               OFFSET(lossless),        AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1013     { "tile-columns",    "Number of tile columns to use, log2",         OFFSET(tile_columns),    AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1014     { "tile-rows",       "Number of tile rows to use, log2",            OFFSET(tile_rows),       AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1015     { "frame-parallel",  "Enable frame parallel decodability features", OFFSET(frame_parallel),  AV_OPT_TYPE_BOOL,{.i64 = -1}, -1, 1, VE},
1016     { "aq-mode",         "adaptive quantization mode",                  OFFSET(aq_mode),         AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
1017     { "none",            "Aq not used",         0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
1018     { "variance",        "Variance based Aq",   0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
1019     { "complexity",      "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
1020     { "cyclic",          "Cyclic Refresh Aq",   0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
1021     LEGACY_OPTIONS
1022     { NULL }
1023 };
1024 #endif
1025
1026 #undef COMMON_OPTIONS
1027 #undef LEGACY_OPTIONS
1028
1029 static const AVCodecDefault defaults[] = {
1030     { "qmin",             "-1" },
1031     { "qmax",             "-1" },
1032     { "g",                "-1" },
1033     { "keyint_min",       "-1" },
1034     { NULL },
1035 };
1036
1037 #if CONFIG_LIBVPX_VP8_ENCODER
1038 static av_cold int vp8_init(AVCodecContext *avctx)
1039 {
1040     return vpx_init(avctx, vpx_codec_vp8_cx());
1041 }
1042
1043 static const AVClass class_vp8 = {
1044     .class_name = "libvpx-vp8 encoder",
1045     .item_name  = av_default_item_name,
1046     .option     = vp8_options,
1047     .version    = LIBAVUTIL_VERSION_INT,
1048 };
1049
1050 AVCodec ff_libvpx_vp8_encoder = {
1051     .name           = "libvpx",
1052     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP8"),
1053     .type           = AVMEDIA_TYPE_VIDEO,
1054     .id             = AV_CODEC_ID_VP8,
1055     .priv_data_size = sizeof(VP8Context),
1056     .init           = vp8_init,
1057     .encode2        = vp8_encode,
1058     .close          = vp8_free,
1059     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
1060     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
1061     .priv_class     = &class_vp8,
1062     .defaults       = defaults,
1063 };
1064 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
1065
1066 #if CONFIG_LIBVPX_VP9_ENCODER
1067 static av_cold int vp9_init(AVCodecContext *avctx)
1068 {
1069     return vpx_init(avctx, vpx_codec_vp9_cx());
1070 }
1071
1072 static const AVClass class_vp9 = {
1073     .class_name = "libvpx-vp9 encoder",
1074     .item_name  = av_default_item_name,
1075     .option     = vp9_options,
1076     .version    = LIBAVUTIL_VERSION_INT,
1077 };
1078
1079 static const AVProfile profiles[] = {
1080     { FF_PROFILE_VP9_0, "Profile 0" },
1081     { FF_PROFILE_VP9_1, "Profile 1" },
1082     { FF_PROFILE_VP9_2, "Profile 2" },
1083     { FF_PROFILE_VP9_3, "Profile 3" },
1084     { FF_PROFILE_UNKNOWN },
1085 };
1086
1087 AVCodec ff_libvpx_vp9_encoder = {
1088     .name           = "libvpx-vp9",
1089     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP9"),
1090     .type           = AVMEDIA_TYPE_VIDEO,
1091     .id             = AV_CODEC_ID_VP9,
1092     .priv_data_size = sizeof(VP8Context),
1093     .init           = vp9_init,
1094     .encode2        = vp8_encode,
1095     .close          = vp8_free,
1096     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
1097     .profiles       = NULL_IF_CONFIG_SMALL(profiles),
1098     .priv_class     = &class_vp9,
1099     .defaults       = defaults,
1100     .init_static_data = ff_vp9_init_static,
1101 };
1102 #endif /* CONFIG_LIBVPX_VP9_ENCODER */