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