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