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