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