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