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