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