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