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