2 * Copyright (c) 2010, Google, Inc.
4 * This file is part of FFmpeg.
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.
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.
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
23 * VP8/9 encoder support via libvpx
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>
33 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/base64.h"
38 #include "libavutil/common.h"
39 #include "libavutil/internal.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/mathematics.h"
42 #include "libavutil/opt.h"
45 * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
46 * One encoded frame returned from the library.
48 struct FrameListData {
49 void *buf; /**< compressed data buffer */
50 size_t sz; /**< length of compressed data */
53 int64_t pts; /**< time stamp to show frame
54 (in timebase units) */
55 unsigned long duration; /**< duration to show frame
56 (in timebase units) */
57 uint32_t flags; /**< flags for this frame */
59 int have_sse; /**< true if we have pending sse[] */
60 uint64_t frame_number;
61 struct FrameListData *next;
64 typedef struct VPxEncoderContext {
66 struct vpx_codec_ctx encoder;
67 struct vpx_image rawimg;
68 struct vpx_codec_ctx encoder_alpha;
69 struct vpx_image rawimg_alpha;
71 struct vpx_fixed_buf twopass_stats;
72 int deadline; //i.e., RT/GOOD/BEST
74 int have_sse; /**< true if we have pending sse[] */
75 uint64_t frame_number;
76 struct FrameListData *coded_frame_list;
81 * VP8 specific flags, see VP8F_* below.
84 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
85 #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
100 int rc_undershoot_pct;
101 int rc_overshoot_pct;
103 char *vp8_ts_parameters;
112 int noise_sensitivity;
117 int corpus_complexity;
120 * If the driver does not support ROI then warn the first time we
121 * encounter a frame with ROI side data.
126 /** String mappings for enum vp8e_enc_control_id */
127 static const char *const ctlidstr[] = {
128 [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
129 [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
130 [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
131 [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
132 [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
133 [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
134 [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
135 [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
136 [VP8E_SET_TUNING] = "VP8E_SET_TUNING",
137 [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
138 [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
139 [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
140 #if CONFIG_LIBVPX_VP9_ENCODER
141 [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
142 [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
143 [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
144 [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
145 [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
146 [VP9E_SET_COLOR_SPACE] = "VP9E_SET_COLOR_SPACE",
147 #if VPX_ENCODER_ABI_VERSION >= 11
148 [VP9E_SET_COLOR_RANGE] = "VP9E_SET_COLOR_RANGE",
150 #if VPX_ENCODER_ABI_VERSION >= 12
151 [VP9E_SET_TARGET_LEVEL] = "VP9E_SET_TARGET_LEVEL",
152 [VP9E_GET_LEVEL] = "VP9E_GET_LEVEL",
154 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
155 [VP9E_SET_ROW_MT] = "VP9E_SET_ROW_MT",
157 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
158 [VP9E_SET_TUNE_CONTENT] = "VP9E_SET_TUNE_CONTENT",
160 #ifdef VPX_CTRL_VP9E_SET_TPL
161 [VP9E_SET_TPL] = "VP9E_SET_TPL",
166 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
168 VPxContext *ctx = avctx->priv_data;
169 const char *error = vpx_codec_error(&ctx->encoder);
170 const char *detail = vpx_codec_error_detail(&ctx->encoder);
172 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
174 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
177 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
178 const struct vpx_codec_enc_cfg *cfg)
181 int level = AV_LOG_DEBUG;
184 av_log(avctx, level, "vpx_codec_enc_cfg\n");
185 av_log(avctx, level, "generic settings\n"
186 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
187 #if CONFIG_LIBVPX_VP9_ENCODER
190 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
191 width, "g_usage:", cfg->g_usage,
192 width, "g_threads:", cfg->g_threads,
193 width, "g_profile:", cfg->g_profile,
194 width, "g_w:", cfg->g_w,
195 width, "g_h:", cfg->g_h,
196 #if CONFIG_LIBVPX_VP9_ENCODER
197 width, "g_bit_depth:", cfg->g_bit_depth,
198 width, "g_input_bit_depth:", cfg->g_input_bit_depth,
200 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
201 width, "g_error_resilient:", cfg->g_error_resilient,
202 width, "g_pass:", cfg->g_pass,
203 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
204 av_log(avctx, level, "rate control settings\n"
205 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
206 " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
207 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
208 width, "rc_resize_allowed:", cfg->rc_resize_allowed,
209 width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
210 width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
211 width, "rc_end_usage:", cfg->rc_end_usage,
212 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
213 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
214 av_log(avctx, level, "quantizer settings\n"
216 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
217 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
218 av_log(avctx, level, "bitrate tolerance\n"
220 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
221 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
222 av_log(avctx, level, "temporal layering settings\n"
223 " %*s%u\n", width, "ts_number_layers:", cfg->ts_number_layers);
225 "\n %*s", width, "ts_target_bitrate:");
226 for (i = 0; i < VPX_TS_MAX_LAYERS; i++)
227 av_log(avctx, level, "%u ", cfg->ts_target_bitrate[i]);
228 av_log(avctx, level, "\n");
230 "\n %*s", width, "ts_rate_decimator:");
231 for (i = 0; i < VPX_TS_MAX_LAYERS; i++)
232 av_log(avctx, level, "%u ", cfg->ts_rate_decimator[i]);
233 av_log(avctx, level, "\n");
235 "\n %*s%u\n", width, "ts_periodicity:", cfg->ts_periodicity);
237 "\n %*s", width, "ts_layer_id:");
238 for (i = 0; i < VPX_TS_MAX_PERIODICITY; i++)
239 av_log(avctx, level, "%u ", cfg->ts_layer_id[i]);
240 av_log(avctx, level, "\n");
241 av_log(avctx, level, "decoder buffer model\n"
242 " %*s%u\n %*s%u\n %*s%u\n",
243 width, "rc_buf_sz:", cfg->rc_buf_sz,
244 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
245 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
246 av_log(avctx, level, "2 pass rate control settings\n"
247 " %*s%u\n %*s%u\n %*s%u\n",
248 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
249 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
250 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
251 #if VPX_ENCODER_ABI_VERSION >= 14
252 av_log(avctx, level, " %*s%u\n",
253 width, "rc_2pass_vbr_corpus_complexity:", cfg->rc_2pass_vbr_corpus_complexity);
255 av_log(avctx, level, "keyframing settings\n"
256 " %*s%d\n %*s%u\n %*s%u\n",
257 width, "kf_mode:", cfg->kf_mode,
258 width, "kf_min_dist:", cfg->kf_min_dist,
259 width, "kf_max_dist:", cfg->kf_max_dist);
260 av_log(avctx, level, "\n");
263 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
265 struct FrameListData **p = list;
270 cx_frame->next = NULL;
273 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
275 av_freep(&cx_frame->buf);
276 if (cx_frame->buf_alpha)
277 av_freep(&cx_frame->buf_alpha);
281 static av_cold void free_frame_list(struct FrameListData *list)
283 struct FrameListData *p = list;
292 static av_cold int codecctl_int(AVCodecContext *avctx,
293 enum vp8e_enc_control_id id, int val)
295 VPxContext *ctx = avctx->priv_data;
300 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
301 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
303 res = vpx_codec_control(&ctx->encoder, id, val);
304 if (res != VPX_CODEC_OK) {
305 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
307 log_encoder_error(avctx, buf);
310 return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
313 #if VPX_ENCODER_ABI_VERSION >= 12
314 static av_cold int codecctl_intp(AVCodecContext *avctx,
315 enum vp8e_enc_control_id id, int *val)
317 VPxContext *ctx = avctx->priv_data;
322 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
323 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, *val);
325 res = vpx_codec_control(&ctx->encoder, id, val);
326 if (res != VPX_CODEC_OK) {
327 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
329 log_encoder_error(avctx, buf);
332 return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
336 static av_cold int vpx_free(AVCodecContext *avctx)
338 VPxContext *ctx = avctx->priv_data;
340 #if VPX_ENCODER_ABI_VERSION >= 12
341 if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->level >= 0 &&
342 !(avctx->flags & AV_CODEC_FLAG_PASS1)) {
344 if (!codecctl_intp(avctx, VP9E_GET_LEVEL, &level_out))
345 av_log(avctx, AV_LOG_INFO, "Encoded level %.1f\n", level_out * 0.1);
349 vpx_codec_destroy(&ctx->encoder);
351 vpx_codec_destroy(&ctx->encoder_alpha);
352 av_freep(&ctx->twopass_stats.buf);
353 av_freep(&avctx->stats_out);
354 free_frame_list(ctx->coded_frame_list);
358 static void vp8_ts_parse_int_array(int *dest, char *value, size_t value_len, int max_entries)
361 char *saveptr = NULL;
362 char *token = av_strtok(value, ",", &saveptr);
364 while (token && dest_idx < max_entries) {
365 dest[dest_idx++] = strtoul(token, NULL, 10);
366 token = av_strtok(NULL, ",", &saveptr);
370 static int vp8_ts_param_parse(struct vpx_codec_enc_cfg *enccfg, char *key, char *value)
372 size_t value_len = strlen(value);
377 if (!strcmp(key, "ts_number_layers"))
378 enccfg->ts_number_layers = strtoul(value, &value, 10);
379 else if (!strcmp(key, "ts_target_bitrate"))
380 vp8_ts_parse_int_array(enccfg->ts_target_bitrate, value, value_len, VPX_TS_MAX_LAYERS);
381 else if (!strcmp(key, "ts_rate_decimator"))
382 vp8_ts_parse_int_array(enccfg->ts_rate_decimator, value, value_len, VPX_TS_MAX_LAYERS);
383 else if (!strcmp(key, "ts_periodicity"))
384 enccfg->ts_periodicity = strtoul(value, &value, 10);
385 else if (!strcmp(key, "ts_layer_id"))
386 vp8_ts_parse_int_array(enccfg->ts_layer_id, value, value_len, VPX_TS_MAX_PERIODICITY);
391 #if CONFIG_LIBVPX_VP9_ENCODER
392 static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
393 struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
394 vpx_img_fmt_t *img_fmt)
396 VPxContext av_unused *ctx = avctx->priv_data;
397 enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
398 switch (avctx->pix_fmt) {
399 case AV_PIX_FMT_YUV420P:
400 case AV_PIX_FMT_YUVA420P:
401 enccfg->g_profile = 0;
402 *img_fmt = VPX_IMG_FMT_I420;
404 case AV_PIX_FMT_YUV422P:
405 enccfg->g_profile = 1;
406 *img_fmt = VPX_IMG_FMT_I422;
408 case AV_PIX_FMT_YUV440P:
409 enccfg->g_profile = 1;
410 *img_fmt = VPX_IMG_FMT_I440;
412 case AV_PIX_FMT_GBRP:
413 ctx->vpx_cs = VPX_CS_SRGB;
414 case AV_PIX_FMT_YUV444P:
415 enccfg->g_profile = 1;
416 *img_fmt = VPX_IMG_FMT_I444;
418 case AV_PIX_FMT_YUV420P10:
419 case AV_PIX_FMT_YUV420P12:
420 if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
421 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
422 avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
423 enccfg->g_profile = 2;
424 *img_fmt = VPX_IMG_FMT_I42016;
425 *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
429 case AV_PIX_FMT_YUV422P10:
430 case AV_PIX_FMT_YUV422P12:
431 if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
432 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
433 avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
434 enccfg->g_profile = 3;
435 *img_fmt = VPX_IMG_FMT_I42216;
436 *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
440 case AV_PIX_FMT_YUV440P10:
441 case AV_PIX_FMT_YUV440P12:
442 if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
443 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
444 avctx->pix_fmt == AV_PIX_FMT_YUV440P10 ? 10 : 12;
445 enccfg->g_profile = 3;
446 *img_fmt = VPX_IMG_FMT_I44016;
447 *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
451 case AV_PIX_FMT_GBRP10:
452 case AV_PIX_FMT_GBRP12:
453 ctx->vpx_cs = VPX_CS_SRGB;
454 case AV_PIX_FMT_YUV444P10:
455 case AV_PIX_FMT_YUV444P12:
456 if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
457 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
458 avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ||
459 avctx->pix_fmt == AV_PIX_FMT_GBRP10 ? 10 : 12;
460 enccfg->g_profile = 3;
461 *img_fmt = VPX_IMG_FMT_I44416;
462 *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
469 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
470 return AVERROR_INVALIDDATA;
473 static void set_colorspace(AVCodecContext *avctx)
475 enum vpx_color_space vpx_cs;
476 VPxContext *ctx = avctx->priv_data;
479 vpx_cs = ctx->vpx_cs;
481 switch (avctx->colorspace) {
482 case AVCOL_SPC_RGB: vpx_cs = VPX_CS_SRGB; break;
483 case AVCOL_SPC_BT709: vpx_cs = VPX_CS_BT_709; break;
484 case AVCOL_SPC_UNSPECIFIED: vpx_cs = VPX_CS_UNKNOWN; break;
485 case AVCOL_SPC_RESERVED: vpx_cs = VPX_CS_RESERVED; break;
486 case AVCOL_SPC_BT470BG: vpx_cs = VPX_CS_BT_601; break;
487 case AVCOL_SPC_SMPTE170M: vpx_cs = VPX_CS_SMPTE_170; break;
488 case AVCOL_SPC_SMPTE240M: vpx_cs = VPX_CS_SMPTE_240; break;
489 case AVCOL_SPC_BT2020_NCL: vpx_cs = VPX_CS_BT_2020; break;
491 av_log(avctx, AV_LOG_WARNING, "Unsupported colorspace (%d)\n",
496 codecctl_int(avctx, VP9E_SET_COLOR_SPACE, vpx_cs);
499 #if VPX_ENCODER_ABI_VERSION >= 11
500 static void set_color_range(AVCodecContext *avctx)
502 enum vpx_color_range vpx_cr;
503 switch (avctx->color_range) {
504 case AVCOL_RANGE_UNSPECIFIED:
505 case AVCOL_RANGE_MPEG: vpx_cr = VPX_CR_STUDIO_RANGE; break;
506 case AVCOL_RANGE_JPEG: vpx_cr = VPX_CR_FULL_RANGE; break;
508 av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
513 codecctl_int(avctx, VP9E_SET_COLOR_RANGE, vpx_cr);
518 static av_cold int vpx_init(AVCodecContext *avctx,
519 const struct vpx_codec_iface *iface)
521 VPxContext *ctx = avctx->priv_data;
522 struct vpx_codec_enc_cfg enccfg = { 0 };
523 struct vpx_codec_enc_cfg enccfg_alpha;
524 vpx_codec_flags_t flags = (avctx->flags & AV_CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
525 AVCPBProperties *cpb_props;
527 vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
528 #if CONFIG_LIBVPX_VP9_ENCODER
529 vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
532 av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
533 av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
535 if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
538 if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
539 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
540 vpx_codec_err_to_string(res));
541 return AVERROR(EINVAL);
544 #if CONFIG_LIBVPX_VP9_ENCODER
545 if (avctx->codec_id == AV_CODEC_ID_VP9) {
546 if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
547 return AVERROR(EINVAL);
552 if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
553 av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
554 return AVERROR(EINVAL);
557 dump_enc_cfg(avctx, &enccfg);
559 enccfg.g_w = avctx->width;
560 enccfg.g_h = avctx->height;
561 enccfg.g_timebase.num = avctx->time_base.num;
562 enccfg.g_timebase.den = avctx->time_base.den;
564 FFMIN(avctx->thread_count ? avctx->thread_count : av_cpu_count(), 16);
565 enccfg.g_lag_in_frames= ctx->lag_in_frames;
567 if (avctx->flags & AV_CODEC_FLAG_PASS1)
568 enccfg.g_pass = VPX_RC_FIRST_PASS;
569 else if (avctx->flags & AV_CODEC_FLAG_PASS2)
570 enccfg.g_pass = VPX_RC_LAST_PASS;
572 enccfg.g_pass = VPX_RC_ONE_PASS;
574 if (avctx->rc_min_rate == avctx->rc_max_rate &&
575 avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
576 enccfg.rc_end_usage = VPX_CBR;
577 } else if (ctx->crf >= 0) {
578 enccfg.rc_end_usage = VPX_CQ;
579 #if CONFIG_LIBVPX_VP9_ENCODER
580 if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
581 enccfg.rc_end_usage = VPX_Q;
585 if (avctx->bit_rate) {
586 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
588 #if CONFIG_LIBVPX_VP9_ENCODER
589 } else if (enccfg.rc_end_usage == VPX_Q) {
592 if (enccfg.rc_end_usage == VPX_CQ) {
593 enccfg.rc_target_bitrate = 1000000;
595 avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
596 av_log(avctx, AV_LOG_WARNING,
597 "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
598 enccfg.rc_target_bitrate);
602 if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
603 enccfg.rc_min_quantizer =
604 enccfg.rc_max_quantizer = 0;
606 if (avctx->qmin >= 0)
607 enccfg.rc_min_quantizer = avctx->qmin;
608 if (avctx->qmax >= 0)
609 enccfg.rc_max_quantizer = avctx->qmax;
612 if (enccfg.rc_end_usage == VPX_CQ
613 #if CONFIG_LIBVPX_VP9_ENCODER
614 || enccfg.rc_end_usage == VPX_Q
617 if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
618 av_log(avctx, AV_LOG_ERROR,
619 "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
620 ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
621 return AVERROR(EINVAL);
625 #if FF_API_PRIVATE_OPT
626 FF_DISABLE_DEPRECATION_WARNINGS
627 if (avctx->frame_skip_threshold)
628 ctx->drop_threshold = avctx->frame_skip_threshold;
629 FF_ENABLE_DEPRECATION_WARNINGS
631 enccfg.rc_dropframe_thresh = ctx->drop_threshold;
633 //0-100 (0 => CBR, 100 => VBR)
634 enccfg.rc_2pass_vbr_bias_pct = lrint(avctx->qcompress * 100);
636 enccfg.rc_2pass_vbr_minsection_pct =
637 avctx->rc_min_rate * 100LL / avctx->bit_rate;
638 if (avctx->rc_max_rate)
639 enccfg.rc_2pass_vbr_maxsection_pct =
640 avctx->rc_max_rate * 100LL / avctx->bit_rate;
641 #if CONFIG_LIBVPX_VP9_ENCODER
642 if (avctx->codec_id == AV_CODEC_ID_VP9) {
643 #if VPX_ENCODER_ABI_VERSION >= 14
644 if (ctx->corpus_complexity >= 0)
645 enccfg.rc_2pass_vbr_corpus_complexity = ctx->corpus_complexity;
650 if (avctx->rc_buffer_size)
652 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
653 if (avctx->rc_initial_buffer_occupancy)
654 enccfg.rc_buf_initial_sz =
655 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
656 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
657 if (ctx->rc_undershoot_pct >= 0)
658 enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
659 if (ctx->rc_overshoot_pct >= 0)
660 enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
662 //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
663 if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
664 enccfg.kf_min_dist = avctx->keyint_min;
665 if (avctx->gop_size >= 0)
666 enccfg.kf_max_dist = avctx->gop_size;
668 if (enccfg.g_pass == VPX_RC_FIRST_PASS)
669 enccfg.g_lag_in_frames = 0;
670 else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
671 int decode_size, ret;
673 if (!avctx->stats_in) {
674 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
675 return AVERROR_INVALIDDATA;
678 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
679 ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
681 av_log(avctx, AV_LOG_ERROR,
682 "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
683 ctx->twopass_stats.sz);
684 ctx->twopass_stats.sz = 0;
687 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
688 ctx->twopass_stats.sz);
689 if (decode_size < 0) {
690 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
691 return AVERROR_INVALIDDATA;
694 ctx->twopass_stats.sz = decode_size;
695 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
698 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
699 complexity playback on low powered devices at the expense of encode
701 if (avctx->profile != FF_PROFILE_UNKNOWN)
702 enccfg.g_profile = avctx->profile;
704 enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
706 if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8 && ctx->vp8_ts_parameters) {
707 AVDictionary *dict = NULL;
708 AVDictionaryEntry* en = NULL;
710 if (!av_dict_parse_string(&dict, ctx->vp8_ts_parameters, "=", ":", 0)) {
711 while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
712 if (vp8_ts_param_parse(&enccfg, en->key, en->value) < 0)
713 av_log(avctx, AV_LOG_WARNING,
714 "Error parsing option '%s = %s'.\n",
722 dump_enc_cfg(avctx, &enccfg);
723 /* Construct Encoder Context */
724 res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
725 if (res != VPX_CODEC_OK) {
726 log_encoder_error(avctx, "Failed to initialize encoder");
727 return AVERROR(EINVAL);
731 enccfg_alpha = enccfg;
732 res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
733 if (res != VPX_CODEC_OK) {
734 log_encoder_error(avctx, "Failed to initialize alpha encoder");
735 return AVERROR(EINVAL);
739 //codec control failures are currently treated only as warnings
740 av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
741 codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
742 if (ctx->flags & VP8F_AUTO_ALT_REF)
743 ctx->auto_alt_ref = 1;
744 if (ctx->auto_alt_ref >= 0)
745 codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF,
746 avctx->codec_id == AV_CODEC_ID_VP8 ? !!ctx->auto_alt_ref : ctx->auto_alt_ref);
747 if (ctx->arnr_max_frames >= 0)
748 codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
749 if (ctx->arnr_strength >= 0)
750 codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
751 if (ctx->arnr_type >= 0)
752 codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
754 codecctl_int(avctx, VP8E_SET_TUNING, ctx->tune);
756 if (ctx->auto_alt_ref && ctx->is_alpha && avctx->codec_id == AV_CODEC_ID_VP8) {
757 av_log(avctx, AV_LOG_ERROR, "Transparency encoding with auto_alt_ref does not work\n");
758 return AVERROR(EINVAL);
761 if (ctx->sharpness >= 0)
762 codecctl_int(avctx, VP8E_SET_SHARPNESS, ctx->sharpness);
764 if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
765 #if FF_API_PRIVATE_OPT
766 FF_DISABLE_DEPRECATION_WARNINGS
767 if (avctx->noise_reduction)
768 ctx->noise_sensitivity = avctx->noise_reduction;
769 FF_ENABLE_DEPRECATION_WARNINGS
771 codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, ctx->noise_sensitivity);
772 codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
774 codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
776 codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
777 if (ctx->max_intra_rate >= 0)
778 codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
780 #if CONFIG_LIBVPX_VP9_ENCODER
781 if (avctx->codec_id == AV_CODEC_ID_VP9) {
782 if (ctx->lossless >= 0)
783 codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
784 if (ctx->tile_columns >= 0)
785 codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
786 if (ctx->tile_rows >= 0)
787 codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
788 if (ctx->frame_parallel >= 0)
789 codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
790 if (ctx->aq_mode >= 0)
791 codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
792 set_colorspace(avctx);
793 #if VPX_ENCODER_ABI_VERSION >= 11
794 set_color_range(avctx);
796 #if VPX_ENCODER_ABI_VERSION >= 12
797 codecctl_int(avctx, VP9E_SET_TARGET_LEVEL, ctx->level < 0 ? 255 : lrint(ctx->level * 10));
799 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
800 if (ctx->row_mt >= 0)
801 codecctl_int(avctx, VP9E_SET_ROW_MT, ctx->row_mt);
803 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
804 if (ctx->tune_content >= 0)
805 codecctl_int(avctx, VP9E_SET_TUNE_CONTENT, ctx->tune_content);
807 #ifdef VPX_CTRL_VP9E_SET_TPL
808 if (ctx->tpl_model >= 0)
809 codecctl_int(avctx, VP9E_SET_TPL, ctx->tpl_model);
814 av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
816 //provide dummy value to initialize wrapper, values will be updated each _encode()
817 vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
819 #if CONFIG_LIBVPX_VP9_ENCODER
820 if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
821 ctx->rawimg.bit_depth = enccfg.g_bit_depth;
825 vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
828 cpb_props = ff_add_cpb_side_data(avctx);
830 return AVERROR(ENOMEM);
832 if (enccfg.rc_end_usage == VPX_CBR ||
833 enccfg.g_pass != VPX_RC_ONE_PASS) {
834 cpb_props->max_bitrate = avctx->rc_max_rate;
835 cpb_props->min_bitrate = avctx->rc_min_rate;
836 cpb_props->avg_bitrate = avctx->bit_rate;
838 cpb_props->buffer_size = avctx->rc_buffer_size;
843 static inline void cx_pktcpy(struct FrameListData *dst,
844 const struct vpx_codec_cx_pkt *src,
845 const struct vpx_codec_cx_pkt *src_alpha,
848 dst->pts = src->data.frame.pts;
849 dst->duration = src->data.frame.duration;
850 dst->flags = src->data.frame.flags;
851 dst->sz = src->data.frame.sz;
852 dst->buf = src->data.frame.buf;
854 /* For alt-ref frame, don't store PSNR or increment frame_number */
855 if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
856 dst->frame_number = ++ctx->frame_number;
857 dst->have_sse = ctx->have_sse;
859 /* associate last-seen SSE to the frame. */
860 /* Transfers ownership from ctx to dst. */
861 /* WARNING! This makes the assumption that PSNR_PKT comes
862 just before the frame it refers to! */
863 memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
867 dst->frame_number = -1; /* sanity marker */
870 dst->buf_alpha = src_alpha->data.frame.buf;
871 dst->sz_alpha = src_alpha->data.frame.sz;
873 dst->buf_alpha = NULL;
879 * Store coded frame information in format suitable for return from encode2().
881 * Write information from @a cx_frame to @a pkt
882 * @return packet data size on success
883 * @return a negative AVERROR on error
885 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
888 int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
892 memcpy(pkt->data, cx_frame->buf, pkt->size);
893 pkt->pts = pkt->dts = cx_frame->pts;
894 #if FF_API_CODED_FRAME
895 FF_DISABLE_DEPRECATION_WARNINGS
896 avctx->coded_frame->pts = cx_frame->pts;
897 avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
898 FF_ENABLE_DEPRECATION_WARNINGS
901 if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
902 pict_type = AV_PICTURE_TYPE_I;
903 #if FF_API_CODED_FRAME
904 FF_DISABLE_DEPRECATION_WARNINGS
905 avctx->coded_frame->pict_type = pict_type;
906 FF_ENABLE_DEPRECATION_WARNINGS
908 pkt->flags |= AV_PKT_FLAG_KEY;
910 pict_type = AV_PICTURE_TYPE_P;
911 #if FF_API_CODED_FRAME
912 FF_DISABLE_DEPRECATION_WARNINGS
913 avctx->coded_frame->pict_type = pict_type;
914 FF_ENABLE_DEPRECATION_WARNINGS
918 ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
919 cx_frame->have_sse ? 3 : 0, pict_type);
921 if (cx_frame->have_sse) {
923 /* Beware of the Y/U/V/all order! */
924 #if FF_API_CODED_FRAME
925 FF_DISABLE_DEPRECATION_WARNINGS
926 avctx->coded_frame->error[0] = cx_frame->sse[1];
927 avctx->coded_frame->error[1] = cx_frame->sse[2];
928 avctx->coded_frame->error[2] = cx_frame->sse[3];
929 avctx->coded_frame->error[3] = 0; // alpha
930 FF_ENABLE_DEPRECATION_WARNINGS
932 for (i = 0; i < 3; ++i) {
933 avctx->error[i] += cx_frame->sse[i + 1];
935 cx_frame->have_sse = 0;
937 if (cx_frame->sz_alpha > 0) {
938 side_data = av_packet_new_side_data(pkt,
939 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
940 cx_frame->sz_alpha + 8);
942 av_packet_unref(pkt);
944 return AVERROR(ENOMEM);
946 AV_WB64(side_data, 1);
947 memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
956 * Queue multiple output frames from the encoder, returning the front-most.
957 * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
958 * the frame queue. Return the head frame if available.
959 * @return Stored frame size
960 * @return AVERROR(EINVAL) on output size error
961 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
963 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
965 VPxContext *ctx = avctx->priv_data;
966 const struct vpx_codec_cx_pkt *pkt;
967 const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
968 const void *iter = NULL;
969 const void *iter_alpha = NULL;
972 if (ctx->coded_frame_list) {
973 struct FrameListData *cx_frame = ctx->coded_frame_list;
974 /* return the leading frame if we've already begun queueing */
975 size = storeframe(avctx, cx_frame, pkt_out);
978 ctx->coded_frame_list = cx_frame->next;
979 free_coded_frame(cx_frame);
982 /* consume all available output from the encoder before returning. buffers
983 are only good through the next vpx_codec call */
984 while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
986 (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha)))) {
988 case VPX_CODEC_CX_FRAME_PKT:
990 struct FrameListData cx_frame;
992 /* avoid storing the frame when the list is empty and we haven't yet
993 provided a frame for output */
994 av_assert0(!ctx->coded_frame_list);
995 cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
996 size = storeframe(avctx, &cx_frame, pkt_out);
1000 struct FrameListData *cx_frame =
1001 av_malloc(sizeof(struct FrameListData));
1004 av_log(avctx, AV_LOG_ERROR,
1005 "Frame queue element alloc failed\n");
1006 return AVERROR(ENOMEM);
1008 cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
1009 cx_frame->buf = av_malloc(cx_frame->sz);
1011 if (!cx_frame->buf) {
1012 av_log(avctx, AV_LOG_ERROR,
1013 "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
1015 av_freep(&cx_frame);
1016 return AVERROR(ENOMEM);
1018 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
1019 if (ctx->is_alpha) {
1020 cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
1021 if (!cx_frame->buf_alpha) {
1022 av_log(avctx, AV_LOG_ERROR,
1023 "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
1024 cx_frame->sz_alpha);
1026 return AVERROR(ENOMEM);
1028 memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
1030 coded_frame_add(&ctx->coded_frame_list, cx_frame);
1033 case VPX_CODEC_STATS_PKT: {
1034 struct vpx_fixed_buf *stats = &ctx->twopass_stats;
1036 if ((err = av_reallocp(&stats->buf,
1038 pkt->data.twopass_stats.sz)) < 0) {
1040 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
1043 memcpy((uint8_t*)stats->buf + stats->sz,
1044 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
1045 stats->sz += pkt->data.twopass_stats.sz;
1048 case VPX_CODEC_PSNR_PKT:
1049 av_assert0(!ctx->have_sse);
1050 ctx->sse[0] = pkt->data.psnr.sse[0];
1051 ctx->sse[1] = pkt->data.psnr.sse[1];
1052 ctx->sse[2] = pkt->data.psnr.sse[2];
1053 ctx->sse[3] = pkt->data.psnr.sse[3];
1056 case VPX_CODEC_CUSTOM_PKT:
1057 //ignore unsupported/unrecognized packet types
1065 static int set_roi_map(AVCodecContext *avctx, const AVFrameSideData *sd, int frame_width, int frame_height,
1066 vpx_roi_map_t *roi_map, int block_size, int segment_cnt)
1069 * range of vpx_roi_map_t.delta_q[i] is [-63, 63]
1071 #define MAX_DELTA_Q 63
1073 const AVRegionOfInterest *roi = NULL;
1078 /* record the mapping from delta_q to "segment id + 1" in segment_mapping[].
1079 * the range of delta_q is [-MAX_DELTA_Q, MAX_DELTA_Q],
1080 * and its corresponding array index is [0, 2 * MAX_DELTA_Q],
1081 * and so the length of the mapping array is 2 * MAX_DELTA_Q + 1.
1082 * "segment id + 1", so we can say there's no mapping if the value of array element is zero.
1084 int segment_mapping[2 * MAX_DELTA_Q + 1] = { 0 };
1086 memset(roi_map, 0, sizeof(*roi_map));
1088 /* segment id 0 in roi_map is reserved for the areas not covered by AVRegionOfInterest.
1089 * segment id 0 in roi_map is also for the areas with AVRegionOfInterest.qoffset near 0.
1090 * (delta_q of segment id 0 is 0).
1092 segment_mapping[MAX_DELTA_Q] = 1;
1095 roi = (const AVRegionOfInterest*)sd->data;
1096 self_size = roi->self_size;
1097 if (!self_size || sd->size % self_size) {
1098 av_log(avctx, AV_LOG_ERROR, "Invalid AVRegionOfInterest.self_size.\n");
1099 return AVERROR(EINVAL);
1101 nb_rois = sd->size / self_size;
1103 /* This list must be iterated from zero because regions are
1104 * defined in order of decreasing importance. So discard less
1105 * important areas if they exceed the segment count.
1107 for (int i = 0; i < nb_rois; i++) {
1111 roi = (const AVRegionOfInterest*)(sd->data + self_size * i);
1112 if (!roi->qoffset.den) {
1113 av_log(avctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n");
1114 return AVERROR(EINVAL);
1117 delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q);
1118 delta_q = av_clip(delta_q, -MAX_DELTA_Q, MAX_DELTA_Q);
1120 mapping_index = delta_q + MAX_DELTA_Q;
1121 if (!segment_mapping[mapping_index]) {
1122 if (segment_id == segment_cnt) {
1123 av_log(avctx, AV_LOG_WARNING,
1124 "ROI only supports %d segments (and segment 0 is reserved for non-ROIs), skipping the left ones.\n",
1129 segment_mapping[mapping_index] = segment_id + 1;
1130 roi_map->delta_q[segment_id] = delta_q;
1135 roi_map->rows = (frame_height + block_size - 1) / block_size;
1136 roi_map->cols = (frame_width + block_size - 1) / block_size;
1137 roi_map->roi_map = av_mallocz_array(roi_map->rows * roi_map->cols, sizeof(*roi_map->roi_map));
1138 if (!roi_map->roi_map) {
1139 av_log(avctx, AV_LOG_ERROR, "roi_map alloc failed.\n");
1140 return AVERROR(ENOMEM);
1143 /* This list must be iterated in reverse, so for the case that
1144 * two regions are overlapping, the more important area takes effect.
1146 for (int i = nb_rois - 1; i >= 0; i--) {
1149 int starty, endy, startx, endx;
1151 roi = (const AVRegionOfInterest*)(sd->data + self_size * i);
1153 starty = av_clip(roi->top / block_size, 0, roi_map->rows);
1154 endy = av_clip((roi->bottom + block_size - 1) / block_size, 0, roi_map->rows);
1155 startx = av_clip(roi->left / block_size, 0, roi_map->cols);
1156 endx = av_clip((roi->right + block_size - 1) / block_size, 0, roi_map->cols);
1158 delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q);
1159 delta_q = av_clip(delta_q, -MAX_DELTA_Q, MAX_DELTA_Q);
1161 mapping_value = segment_mapping[delta_q + MAX_DELTA_Q];
1162 if (mapping_value) {
1163 for (int y = starty; y < endy; y++)
1164 for (int x = startx; x < endx; x++)
1165 roi_map->roi_map[x + y * roi_map->cols] = mapping_value - 1;
1172 static int vp9_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
1174 VPxContext *ctx = avctx->priv_data;
1176 #ifdef VPX_CTRL_VP9E_SET_ROI_MAP
1177 int version = vpx_codec_version();
1178 int major = VPX_VERSION_MAJOR(version);
1179 int minor = VPX_VERSION_MINOR(version);
1180 int patch = VPX_VERSION_PATCH(version);
1182 if (major > 1 || (major == 1 && minor > 8) || (major == 1 && minor == 8 && patch >= 1)) {
1183 vpx_roi_map_t roi_map;
1184 const int segment_cnt = 8;
1185 const int block_size = 8;
1188 if (ctx->aq_mode > 0 || ctx->cpu_used < 5 || ctx->deadline != VPX_DL_REALTIME) {
1189 if (!ctx->roi_warned) {
1190 ctx->roi_warned = 1;
1191 av_log(avctx, AV_LOG_WARNING, "ROI is only enabled when aq_mode is 0, cpu_used >= 5 "
1192 "and deadline is REALTIME, so skipping ROI.\n");
1193 return AVERROR(EINVAL);
1197 ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt);
1199 log_encoder_error(avctx, "Failed to set_roi_map.\n");
1203 memset(roi_map.ref_frame, -1, sizeof(roi_map.ref_frame));
1205 if (vpx_codec_control(&ctx->encoder, VP9E_SET_ROI_MAP, &roi_map)) {
1206 log_encoder_error(avctx, "Failed to set VP9E_SET_ROI_MAP codec control.\n");
1207 ret = AVERROR_INVALIDDATA;
1209 av_freep(&roi_map.roi_map);
1214 if (!ctx->roi_warned) {
1215 ctx->roi_warned = 1;
1216 av_log(avctx, AV_LOG_WARNING, "ROI is not supported, please upgrade libvpx to version >= 1.8.1. "
1217 "You may need to rebuild ffmpeg.\n");
1222 static int vp8_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
1224 vpx_roi_map_t roi_map;
1225 const int segment_cnt = 4;
1226 const int block_size = 16;
1227 VPxContext *ctx = avctx->priv_data;
1229 int ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt);
1231 log_encoder_error(avctx, "Failed to set_roi_map.\n");
1235 if (vpx_codec_control(&ctx->encoder, VP8E_SET_ROI_MAP, &roi_map)) {
1236 log_encoder_error(avctx, "Failed to set VP8E_SET_ROI_MAP codec control.\n");
1237 ret = AVERROR_INVALIDDATA;
1240 av_freep(&roi_map.roi_map);
1244 static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt,
1245 const AVFrame *frame, int *got_packet)
1247 VPxContext *ctx = avctx->priv_data;
1248 struct vpx_image *rawimg = NULL;
1249 struct vpx_image *rawimg_alpha = NULL;
1250 int64_t timestamp = 0;
1251 int res, coded_size;
1252 vpx_enc_frame_flags_t flags = 0;
1255 const AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1256 rawimg = &ctx->rawimg;
1257 rawimg->planes[VPX_PLANE_Y] = frame->data[0];
1258 rawimg->planes[VPX_PLANE_U] = frame->data[1];
1259 rawimg->planes[VPX_PLANE_V] = frame->data[2];
1260 rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
1261 rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
1262 rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
1263 if (ctx->is_alpha) {
1264 uint8_t *u_plane, *v_plane;
1265 rawimg_alpha = &ctx->rawimg_alpha;
1266 rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
1267 u_plane = av_malloc(frame->linesize[1] * frame->height);
1268 v_plane = av_malloc(frame->linesize[2] * frame->height);
1269 if (!u_plane || !v_plane) {
1272 return AVERROR(ENOMEM);
1274 memset(u_plane, 0x80, frame->linesize[1] * frame->height);
1275 rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
1276 memset(v_plane, 0x80, frame->linesize[2] * frame->height);
1277 rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
1278 rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
1279 rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
1280 rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
1282 timestamp = frame->pts;
1283 #if VPX_IMAGE_ABI_VERSION >= 4
1284 switch (frame->color_range) {
1285 case AVCOL_RANGE_MPEG:
1286 rawimg->range = VPX_CR_STUDIO_RANGE;
1288 case AVCOL_RANGE_JPEG:
1289 rawimg->range = VPX_CR_FULL_RANGE;
1293 if (frame->pict_type == AV_PICTURE_TYPE_I)
1294 flags |= VPX_EFLAG_FORCE_KF;
1295 if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8 && frame->metadata) {
1296 AVDictionaryEntry* en = av_dict_get(frame->metadata, "vp8-flags", NULL, 0);
1298 flags |= strtoul(en->value, NULL, 10);
1303 if (avctx->codec_id == AV_CODEC_ID_VP8) {
1304 vp8_encode_set_roi(avctx, frame->width, frame->height, sd);
1306 vp9_encode_set_roi(avctx, frame->width, frame->height, sd);
1311 res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
1312 avctx->ticks_per_frame, flags, ctx->deadline);
1313 if (res != VPX_CODEC_OK) {
1314 log_encoder_error(avctx, "Error encoding frame");
1315 return AVERROR_INVALIDDATA;
1318 if (ctx->is_alpha) {
1319 res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
1320 avctx->ticks_per_frame, flags, ctx->deadline);
1321 if (res != VPX_CODEC_OK) {
1322 log_encoder_error(avctx, "Error encoding alpha frame");
1323 return AVERROR_INVALIDDATA;
1327 coded_size = queue_frames(avctx, pkt);
1329 if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
1330 unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
1332 avctx->stats_out = av_malloc(b64_size);
1333 if (!avctx->stats_out) {
1334 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
1336 return AVERROR(ENOMEM);
1338 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
1339 ctx->twopass_stats.sz);
1343 av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
1344 av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
1347 *got_packet = !!coded_size;
1351 #define OFFSET(x) offsetof(VPxContext, x)
1352 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1354 #define COMMON_OPTIONS \
1355 { "lag-in-frames", "Number of frames to look ahead for " \
1356 "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1357 { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1358 { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1359 { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
1360 { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
1361 { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
1362 { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
1363 { "tune", "Tune the encoding to a specific scenario", OFFSET(tune), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "tune"}, \
1364 { "psnr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_PSNR}, 0, 0, VE, "tune"}, \
1365 { "ssim", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_SSIM}, 0, 0, VE, "tune"}, \
1366 { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
1367 { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
1368 { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
1369 { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
1370 { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
1371 { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1372 { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
1373 { "partitions", "The frame partitions are independently decodable " \
1374 "by the bool decoder, meaning that partitions can be decoded even " \
1375 "though earlier partitions have been lost. Note that intra predicition" \
1376 " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
1377 { "crf", "Select the quality for constant quality mode", offsetof(VPxContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
1378 { "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 }, \
1379 { "drop-threshold", "Frame drop threshold", offsetof(VPxContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE }, \
1380 { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE}, \
1381 { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
1382 { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
1384 #define LEGACY_OPTIONS \
1385 {"speed", "", offsetof(VPxContext, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
1386 {"quality", "", offsetof(VPxContext, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
1387 {"vp8flags", "", offsetof(VPxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
1388 {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
1389 {"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"}, \
1390 {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VPxContext, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
1391 {"arnr_strength", "altref noise reduction filter strength", offsetof(VPxContext, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
1392 {"arnr_type", "altref noise reduction filter type", offsetof(VPxContext, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
1393 {"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}, \
1394 {"sharpness", "Increase sharpness at the expense of lower PSNR", offsetof(VPxContext, sharpness), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, VE},
1396 #if CONFIG_LIBVPX_VP8_ENCODER
1397 static const AVOption vp8_options[] = {
1399 { "auto-alt-ref", "Enable use of alternate reference "
1400 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1401 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE},
1402 { "ts-parameters", "Temporal scaling configuration using a "
1403 ":-separated list of key=value parameters", OFFSET(vp8_ts_parameters), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE},
1409 #if CONFIG_LIBVPX_VP9_ENCODER
1410 static const AVOption vp9_options[] = {
1412 { "auto-alt-ref", "Enable use of alternate reference "
1413 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1414 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
1415 { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1416 { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1417 { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1418 { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_BOOL,{.i64 = -1}, -1, 1, VE},
1419 #if VPX_ENCODER_ABI_VERSION >= 12
1420 { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 4, VE, "aq_mode"},
1422 { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
1424 { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
1425 { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
1426 { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
1427 { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
1428 #if VPX_ENCODER_ABI_VERSION >= 12
1429 { "equator360", "360 video Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 4}, 0, 0, VE, "aq_mode" },
1430 {"level", "Specify level", OFFSET(level), AV_OPT_TYPE_FLOAT, {.dbl=-1}, -1, 6.2, VE},
1432 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
1433 {"row-mt", "Row based multi-threading", OFFSET(row_mt), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE},
1435 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
1436 #if VPX_ENCODER_ABI_VERSION >= 14
1437 { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE, "tune_content" },
1439 { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE, "tune_content" },
1441 { "default", "Regular video content", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "tune_content" },
1442 { "screen", "Screen capture content", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "tune_content" },
1443 #if VPX_ENCODER_ABI_VERSION >= 14
1444 { "film", "Film content; improves grain retention", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "tune_content" },
1447 #if VPX_ENCODER_ABI_VERSION >= 14
1448 { "corpus-complexity", "corpus vbr complexity midpoint", OFFSET(corpus_complexity), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 10000, VE },
1450 #ifdef VPX_CTRL_VP9E_SET_TPL
1451 { "enable-tpl", "Enable temporal dependency model", OFFSET(tpl_model), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE },
1458 #undef COMMON_OPTIONS
1459 #undef LEGACY_OPTIONS
1461 static const AVCodecDefault defaults[] = {
1465 { "keyint_min", "-1" },
1469 #if CONFIG_LIBVPX_VP8_ENCODER
1470 static av_cold int vp8_init(AVCodecContext *avctx)
1472 return vpx_init(avctx, vpx_codec_vp8_cx());
1475 static const AVClass class_vp8 = {
1476 .class_name = "libvpx-vp8 encoder",
1477 .item_name = av_default_item_name,
1478 .option = vp8_options,
1479 .version = LIBAVUTIL_VERSION_INT,
1482 AVCodec ff_libvpx_vp8_encoder = {
1484 .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
1485 .type = AVMEDIA_TYPE_VIDEO,
1486 .id = AV_CODEC_ID_VP8,
1487 .priv_data_size = sizeof(VPxContext),
1489 .encode2 = vpx_encode,
1491 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
1492 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
1493 .priv_class = &class_vp8,
1494 .defaults = defaults,
1495 .wrapper_name = "libvpx",
1497 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
1499 #if CONFIG_LIBVPX_VP9_ENCODER
1500 static av_cold int vp9_init(AVCodecContext *avctx)
1502 return vpx_init(avctx, vpx_codec_vp9_cx());
1505 static const AVClass class_vp9 = {
1506 .class_name = "libvpx-vp9 encoder",
1507 .item_name = av_default_item_name,
1508 .option = vp9_options,
1509 .version = LIBAVUTIL_VERSION_INT,
1512 AVCodec ff_libvpx_vp9_encoder = {
1513 .name = "libvpx-vp9",
1514 .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
1515 .type = AVMEDIA_TYPE_VIDEO,
1516 .id = AV_CODEC_ID_VP9,
1517 .priv_data_size = sizeof(VPxContext),
1519 .encode2 = vpx_encode,
1521 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
1522 .profiles = NULL_IF_CONFIG_SMALL(ff_vp9_profiles),
1523 .priv_class = &class_vp9,
1524 .defaults = defaults,
1525 .init_static_data = ff_vp9_init_static,
1526 .wrapper_name = "libvpx",
1528 #endif /* CONFIG_LIBVPX_VP9_ENCODER */