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