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 * AV1 encoder support via libaom
26 #define AOM_DISABLE_CTRL_TYPECHECKS 1
27 #include <aom/aom_encoder.h>
28 #include <aom/aomcx.h>
30 #include "libavutil/avassert.h"
31 #include "libavutil/base64.h"
32 #include "libavutil/common.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/pixdesc.h"
43 * Portion of struct aom_codec_cx_pkt from aom_encoder.h.
44 * One encoded frame returned from the library.
46 struct FrameListData {
47 void *buf; /**< compressed data buffer */
48 size_t sz; /**< length of compressed data */
49 int64_t pts; /**< time stamp to show frame
50 (in timebase units) */
51 unsigned long duration; /**< duration to show frame
52 (in timebase units) */
53 uint32_t flags; /**< flags for this frame */
55 int have_sse; /**< true if we have pending sse[] */
56 uint64_t frame_number;
57 struct FrameListData *next;
60 typedef struct AOMEncoderContext {
63 struct aom_codec_ctx encoder;
64 struct aom_image rawimg;
65 struct aom_fixed_buf twopass_stats;
66 struct FrameListData *coded_frame_list;
75 int have_sse; /**< true if we have pending sse[] */
76 uint64_t frame_number;
77 int tile_cols, tile_rows;
78 int tile_cols_log2, tile_rows_log2;
79 aom_superblock_size_t superblock_size;
84 static const char *const ctlidstr[] = {
85 [AOME_SET_CPUUSED] = "AOME_SET_CPUUSED",
86 [AOME_SET_CQ_LEVEL] = "AOME_SET_CQ_LEVEL",
87 [AOME_SET_ENABLEAUTOALTREF] = "AOME_SET_ENABLEAUTOALTREF",
88 [AOME_SET_STATIC_THRESHOLD] = "AOME_SET_STATIC_THRESHOLD",
89 [AV1E_SET_COLOR_RANGE] = "AV1E_SET_COLOR_RANGE",
90 [AV1E_SET_COLOR_PRIMARIES] = "AV1E_SET_COLOR_PRIMARIES",
91 [AV1E_SET_MATRIX_COEFFICIENTS] = "AV1E_SET_MATRIX_COEFFICIENTS",
92 [AV1E_SET_TRANSFER_CHARACTERISTICS] = "AV1E_SET_TRANSFER_CHARACTERISTICS",
93 [AV1E_SET_SUPERBLOCK_SIZE] = "AV1E_SET_SUPERBLOCK_SIZE",
94 [AV1E_SET_TILE_COLUMNS] = "AV1E_SET_TILE_COLUMNS",
95 [AV1E_SET_TILE_ROWS] = "AV1E_SET_TILE_ROWS",
96 #ifdef AOM_CTRL_AV1E_SET_ROW_MT
97 [AV1E_SET_ROW_MT] = "AV1E_SET_ROW_MT",
101 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
103 AOMContext *ctx = avctx->priv_data;
104 const char *error = aom_codec_error(&ctx->encoder);
105 const char *detail = aom_codec_error_detail(&ctx->encoder);
107 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
109 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
112 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
113 const struct aom_codec_enc_cfg *cfg)
116 int level = AV_LOG_DEBUG;
118 av_log(avctx, level, "aom_codec_enc_cfg\n");
119 av_log(avctx, level, "generic settings\n"
120 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
122 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
123 width, "g_usage:", cfg->g_usage,
124 width, "g_threads:", cfg->g_threads,
125 width, "g_profile:", cfg->g_profile,
126 width, "g_w:", cfg->g_w,
127 width, "g_h:", cfg->g_h,
128 width, "g_bit_depth:", cfg->g_bit_depth,
129 width, "g_input_bit_depth:", cfg->g_input_bit_depth,
130 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
131 width, "g_error_resilient:", cfg->g_error_resilient,
132 width, "g_pass:", cfg->g_pass,
133 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
134 av_log(avctx, level, "rate control settings\n"
135 " %*s%u\n %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
136 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
137 width, "rc_end_usage:", cfg->rc_end_usage,
138 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
139 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
140 av_log(avctx, level, "quantizer settings\n"
142 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
143 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
144 av_log(avctx, level, "bitrate tolerance\n"
146 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
147 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
148 av_log(avctx, level, "decoder buffer model\n"
149 " %*s%u\n %*s%u\n %*s%u\n",
150 width, "rc_buf_sz:", cfg->rc_buf_sz,
151 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
152 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
153 av_log(avctx, level, "2 pass rate control settings\n"
154 " %*s%u\n %*s%u\n %*s%u\n",
155 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
156 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
157 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
158 av_log(avctx, level, "keyframing settings\n"
159 " %*s%d\n %*s%u\n %*s%u\n",
160 width, "kf_mode:", cfg->kf_mode,
161 width, "kf_min_dist:", cfg->kf_min_dist,
162 width, "kf_max_dist:", cfg->kf_max_dist);
163 av_log(avctx, level, "tile settings\n"
165 width, "tile_width_count:", cfg->tile_width_count,
166 width, "tile_height_count:", cfg->tile_height_count);
167 av_log(avctx, level, "\n");
170 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
172 struct FrameListData **p = list;
177 cx_frame->next = NULL;
180 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
182 av_freep(&cx_frame->buf);
186 static av_cold void free_frame_list(struct FrameListData *list)
188 struct FrameListData *p = list;
197 static av_cold int codecctl_int(AVCodecContext *avctx,
199 aome_enc_control_id id,
201 enum aome_enc_control_id id,
205 AOMContext *ctx = avctx->priv_data;
210 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
211 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
213 res = aom_codec_control(&ctx->encoder, id, val);
214 if (res != AOM_CODEC_OK) {
215 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
217 log_encoder_error(avctx, buf);
218 return AVERROR(EINVAL);
224 static av_cold int aom_free(AVCodecContext *avctx)
226 AOMContext *ctx = avctx->priv_data;
228 aom_codec_destroy(&ctx->encoder);
229 av_freep(&ctx->twopass_stats.buf);
230 av_freep(&avctx->stats_out);
231 free_frame_list(ctx->coded_frame_list);
232 av_bsf_free(&ctx->bsf);
236 static int set_pix_fmt(AVCodecContext *avctx, aom_codec_caps_t codec_caps,
237 struct aom_codec_enc_cfg *enccfg, aom_codec_flags_t *flags,
238 aom_img_fmt_t *img_fmt)
240 AOMContext av_unused *ctx = avctx->priv_data;
241 enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
242 switch (avctx->pix_fmt) {
243 case AV_PIX_FMT_YUV420P:
244 enccfg->g_profile = FF_PROFILE_AV1_MAIN;
245 *img_fmt = AOM_IMG_FMT_I420;
247 case AV_PIX_FMT_YUV422P:
248 enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
249 *img_fmt = AOM_IMG_FMT_I422;
251 case AV_PIX_FMT_YUV444P:
252 enccfg->g_profile = FF_PROFILE_AV1_HIGH;
253 *img_fmt = AOM_IMG_FMT_I444;
255 case AV_PIX_FMT_YUV420P10:
256 case AV_PIX_FMT_YUV420P12:
257 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
258 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
259 avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
261 enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_MAIN : FF_PROFILE_AV1_PROFESSIONAL;
262 *img_fmt = AOM_IMG_FMT_I42016;
263 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
267 case AV_PIX_FMT_YUV422P10:
268 case AV_PIX_FMT_YUV422P12:
269 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
270 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
271 avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
272 enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
273 *img_fmt = AOM_IMG_FMT_I42216;
274 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
278 case AV_PIX_FMT_YUV444P10:
279 case AV_PIX_FMT_YUV444P12:
280 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
281 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
282 avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ? 10 : 12;
284 enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_HIGH : FF_PROFILE_AV1_PROFESSIONAL;
285 *img_fmt = AOM_IMG_FMT_I44416;
286 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
293 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
294 return AVERROR_INVALIDDATA;
297 static void set_color_range(AVCodecContext *avctx)
299 aom_color_range_t aom_cr;
300 switch (avctx->color_range) {
301 case AVCOL_RANGE_UNSPECIFIED:
302 case AVCOL_RANGE_MPEG: aom_cr = AOM_CR_STUDIO_RANGE; break;
303 case AVCOL_RANGE_JPEG: aom_cr = AOM_CR_FULL_RANGE; break;
305 av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
310 codecctl_int(avctx, AV1E_SET_COLOR_RANGE, aom_cr);
313 static int count_uniform_tiling(int dim, int sb_size, int tiles_log2)
315 int sb_dim = (dim + sb_size - 1) / sb_size;
316 int tile_dim = (sb_dim + (1 << tiles_log2) - 1) >> tiles_log2;
317 av_assert0(tile_dim > 0);
318 return (sb_dim + tile_dim - 1) / tile_dim;
321 static int choose_tiling(AVCodecContext *avctx,
322 struct aom_codec_enc_cfg *enccfg)
324 AOMContext *ctx = avctx->priv_data;
325 int sb_128x128_possible, sb_size, sb_width, sb_height;
326 int uniform_rows, uniform_cols;
327 int uniform_64x64_possible, uniform_128x128_possible;
328 int tile_size, rounding, i;
330 if (ctx->tile_cols_log2 >= 0)
331 ctx->tile_cols = 1 << ctx->tile_cols_log2;
332 if (ctx->tile_rows_log2 >= 0)
333 ctx->tile_rows = 1 << ctx->tile_rows_log2;
335 if (ctx->tile_cols == 0) {
336 ctx->tile_cols = (avctx->width + AV1_MAX_TILE_WIDTH - 1) /
338 if (ctx->tile_cols > 1) {
339 av_log(avctx, AV_LOG_DEBUG, "Automatically using %d tile "
340 "columns to fill width.\n", ctx->tile_cols);
343 av_assert0(ctx->tile_cols > 0);
344 if (ctx->tile_rows == 0) {
346 FFALIGN((FFALIGN(avctx->width, 128) +
347 ctx->tile_cols - 1) / ctx->tile_cols, 128);
349 (max_tile_width * FFALIGN(avctx->height, 128) +
350 AV1_MAX_TILE_AREA - 1) / AV1_MAX_TILE_AREA;
351 if (ctx->tile_rows > 1) {
352 av_log(avctx, AV_LOG_DEBUG, "Automatically using %d tile "
353 "rows to fill area.\n", ctx->tile_rows);
356 av_assert0(ctx->tile_rows > 0);
358 if ((avctx->width + 63) / 64 < ctx->tile_cols ||
359 (avctx->height + 63) / 64 < ctx->tile_rows) {
360 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: frame not "
361 "large enough to fit specified tile arrangement.\n");
362 return AVERROR(EINVAL);
364 if (ctx->tile_cols > AV1_MAX_TILE_COLS ||
365 ctx->tile_rows > AV1_MAX_TILE_ROWS) {
366 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: AV1 does "
367 "not allow more than %dx%d tiles.\n",
368 AV1_MAX_TILE_COLS, AV1_MAX_TILE_ROWS);
369 return AVERROR(EINVAL);
371 if (avctx->width / ctx->tile_cols > AV1_MAX_TILE_WIDTH) {
372 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: AV1 does "
373 "not allow tiles of width greater than %d.\n",
375 return AVERROR(EINVAL);
378 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_DYNAMIC;
380 if (ctx->tile_cols == 1 && ctx->tile_rows == 1) {
381 av_log(avctx, AV_LOG_DEBUG, "Using a single tile.\n");
385 sb_128x128_possible =
386 (avctx->width + 127) / 128 >= ctx->tile_cols &&
387 (avctx->height + 127) / 128 >= ctx->tile_rows;
389 ctx->tile_cols_log2 = ctx->tile_cols == 1 ? 0 :
390 av_log2(ctx->tile_cols - 1) + 1;
391 ctx->tile_rows_log2 = ctx->tile_rows == 1 ? 0 :
392 av_log2(ctx->tile_rows - 1) + 1;
394 uniform_cols = count_uniform_tiling(avctx->width,
395 64, ctx->tile_cols_log2);
396 uniform_rows = count_uniform_tiling(avctx->height,
397 64, ctx->tile_rows_log2);
398 av_log(avctx, AV_LOG_DEBUG, "Uniform with 64x64 superblocks "
399 "-> %dx%d tiles.\n", uniform_cols, uniform_rows);
400 uniform_64x64_possible = uniform_cols == ctx->tile_cols &&
401 uniform_rows == ctx->tile_rows;
403 if (sb_128x128_possible) {
404 uniform_cols = count_uniform_tiling(avctx->width,
405 128, ctx->tile_cols_log2);
406 uniform_rows = count_uniform_tiling(avctx->height,
407 128, ctx->tile_rows_log2);
408 av_log(avctx, AV_LOG_DEBUG, "Uniform with 128x128 superblocks "
409 "-> %dx%d tiles.\n", uniform_cols, uniform_rows);
410 uniform_128x128_possible = uniform_cols == ctx->tile_cols &&
411 uniform_rows == ctx->tile_rows;
413 av_log(avctx, AV_LOG_DEBUG, "128x128 superblocks not possible.\n");
414 uniform_128x128_possible = 0;
417 ctx->uniform_tiles = 1;
418 if (uniform_64x64_possible && uniform_128x128_possible) {
419 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with dynamic "
420 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
421 ctx->tile_cols_log2, ctx->tile_rows_log2);
424 if (uniform_64x64_possible && !sb_128x128_possible) {
425 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with 64x64 "
426 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
427 ctx->tile_cols_log2, ctx->tile_rows_log2);
428 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_64X64;
431 if (uniform_128x128_possible) {
432 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with 128x128 "
433 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
434 ctx->tile_cols_log2, ctx->tile_rows_log2);
435 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_128X128;
438 ctx->uniform_tiles = 0;
440 if (sb_128x128_possible) {
442 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_128X128;
445 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_64X64;
447 av_log(avctx, AV_LOG_DEBUG, "Using fixed tiling with %dx%d "
448 "superblocks (tile_cols = %d, tile_rows = %d).\n",
449 sb_size, sb_size, ctx->tile_cols, ctx->tile_rows);
451 enccfg->tile_width_count = ctx->tile_cols;
452 enccfg->tile_height_count = ctx->tile_rows;
454 sb_width = (avctx->width + sb_size - 1) / sb_size;
455 sb_height = (avctx->height + sb_size - 1) / sb_size;
457 tile_size = sb_width / ctx->tile_cols;
458 rounding = sb_width % ctx->tile_cols;
459 for (i = 0; i < ctx->tile_cols; i++) {
460 enccfg->tile_widths[i] = tile_size +
462 i > ctx->tile_cols - 1 - (rounding + 1) / 2);
465 tile_size = sb_height / ctx->tile_rows;
466 rounding = sb_height % ctx->tile_rows;
467 for (i = 0; i < ctx->tile_rows; i++) {
468 enccfg->tile_heights[i] = tile_size +
470 i > ctx->tile_rows - 1 - (rounding + 1) / 2);
476 static av_cold int aom_init(AVCodecContext *avctx,
477 const struct aom_codec_iface *iface)
479 AOMContext *ctx = avctx->priv_data;
480 struct aom_codec_enc_cfg enccfg = { 0 };
481 #ifdef AOM_FRAME_IS_INTRAONLY
482 aom_codec_flags_t flags =
483 (avctx->flags & AV_CODEC_FLAG_PSNR) ? AOM_CODEC_USE_PSNR : 0;
485 aom_codec_flags_t flags = 0;
487 AVCPBProperties *cpb_props;
489 aom_img_fmt_t img_fmt;
490 aom_codec_caps_t codec_caps = aom_codec_get_caps(iface);
492 av_log(avctx, AV_LOG_INFO, "%s\n", aom_codec_version_str());
493 av_log(avctx, AV_LOG_VERBOSE, "%s\n", aom_codec_build_config());
495 if ((res = aom_codec_enc_config_default(iface, &enccfg, 0)) != AOM_CODEC_OK) {
496 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
497 aom_codec_err_to_string(res));
498 return AVERROR(EINVAL);
501 if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
502 return AVERROR(EINVAL);
505 if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
506 av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
507 return AVERROR(EINVAL);
510 dump_enc_cfg(avctx, &enccfg);
512 enccfg.g_w = avctx->width;
513 enccfg.g_h = avctx->height;
514 enccfg.g_timebase.num = avctx->time_base.num;
515 enccfg.g_timebase.den = avctx->time_base.den;
517 FFMIN(avctx->thread_count ? avctx->thread_count : av_cpu_count(), 64);
519 if (ctx->lag_in_frames >= 0)
520 enccfg.g_lag_in_frames = ctx->lag_in_frames;
522 if (avctx->flags & AV_CODEC_FLAG_PASS1)
523 enccfg.g_pass = AOM_RC_FIRST_PASS;
524 else if (avctx->flags & AV_CODEC_FLAG_PASS2)
525 enccfg.g_pass = AOM_RC_LAST_PASS;
527 enccfg.g_pass = AOM_RC_ONE_PASS;
529 if (avctx->rc_min_rate == avctx->rc_max_rate &&
530 avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
531 enccfg.rc_end_usage = AOM_CBR;
532 } else if (ctx->crf >= 0) {
533 enccfg.rc_end_usage = AOM_CQ;
534 if (!avctx->bit_rate)
535 enccfg.rc_end_usage = AOM_Q;
538 if (avctx->bit_rate) {
539 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
541 } else if (enccfg.rc_end_usage != AOM_Q) {
542 if (enccfg.rc_end_usage == AOM_CQ) {
543 enccfg.rc_target_bitrate = 1000000;
545 avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
546 av_log(avctx, AV_LOG_WARNING,
547 "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
548 enccfg.rc_target_bitrate);
552 if (avctx->qmin >= 0)
553 enccfg.rc_min_quantizer = avctx->qmin;
554 if (avctx->qmax >= 0)
555 enccfg.rc_max_quantizer = avctx->qmax;
557 if (enccfg.rc_end_usage == AOM_CQ || enccfg.rc_end_usage == AOM_Q) {
558 if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
559 av_log(avctx, AV_LOG_ERROR,
560 "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
561 ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
562 return AVERROR(EINVAL);
566 enccfg.rc_dropframe_thresh = ctx->drop_threshold;
568 // 0-100 (0 => CBR, 100 => VBR)
569 enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
571 enccfg.rc_2pass_vbr_minsection_pct =
572 avctx->rc_min_rate * 100LL / avctx->bit_rate;
573 if (avctx->rc_max_rate)
574 enccfg.rc_2pass_vbr_maxsection_pct =
575 avctx->rc_max_rate * 100LL / avctx->bit_rate;
577 if (avctx->rc_buffer_size)
579 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
580 if (avctx->rc_initial_buffer_occupancy)
581 enccfg.rc_buf_initial_sz =
582 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
583 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
585 // _enc_init() will balk if kf_min_dist differs from max w/AOM_KF_AUTO
586 if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
587 enccfg.kf_min_dist = avctx->keyint_min;
588 if (avctx->gop_size >= 0)
589 enccfg.kf_max_dist = avctx->gop_size;
591 if (enccfg.g_pass == AOM_RC_FIRST_PASS)
592 enccfg.g_lag_in_frames = 0;
593 else if (enccfg.g_pass == AOM_RC_LAST_PASS) {
594 int decode_size, ret;
596 if (!avctx->stats_in) {
597 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
598 return AVERROR_INVALIDDATA;
601 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
602 ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
604 av_log(avctx, AV_LOG_ERROR,
605 "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
606 ctx->twopass_stats.sz);
607 ctx->twopass_stats.sz = 0;
610 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
611 ctx->twopass_stats.sz);
612 if (decode_size < 0) {
613 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
614 return AVERROR_INVALIDDATA;
617 ctx->twopass_stats.sz = decode_size;
618 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
621 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
622 * complexity playback on low powered devices at the expense of encode
624 if (avctx->profile != FF_PROFILE_UNKNOWN)
625 enccfg.g_profile = avctx->profile;
627 enccfg.g_error_resilient = ctx->error_resilient;
629 res = choose_tiling(avctx, &enccfg);
633 dump_enc_cfg(avctx, &enccfg);
634 /* Construct Encoder Context */
635 res = aom_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
636 if (res != AOM_CODEC_OK) {
637 log_encoder_error(avctx, "Failed to initialize encoder");
638 return AVERROR(EINVAL);
641 // codec control failures are currently treated only as warnings
642 av_log(avctx, AV_LOG_DEBUG, "aom_codec_control\n");
643 codecctl_int(avctx, AOME_SET_CPUUSED, ctx->cpu_used);
644 if (ctx->auto_alt_ref >= 0)
645 codecctl_int(avctx, AOME_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
647 codecctl_int(avctx, AOME_SET_STATIC_THRESHOLD, ctx->static_thresh);
649 codecctl_int(avctx, AOME_SET_CQ_LEVEL, ctx->crf);
651 codecctl_int(avctx, AV1E_SET_COLOR_PRIMARIES, avctx->color_primaries);
652 codecctl_int(avctx, AV1E_SET_MATRIX_COEFFICIENTS, avctx->colorspace);
653 codecctl_int(avctx, AV1E_SET_TRANSFER_CHARACTERISTICS, avctx->color_trc);
654 set_color_range(avctx);
656 codecctl_int(avctx, AV1E_SET_SUPERBLOCK_SIZE, ctx->superblock_size);
657 if (ctx->uniform_tiles) {
658 codecctl_int(avctx, AV1E_SET_TILE_COLUMNS, ctx->tile_cols_log2);
659 codecctl_int(avctx, AV1E_SET_TILE_ROWS, ctx->tile_rows_log2);
662 #ifdef AOM_CTRL_AV1E_SET_ROW_MT
663 codecctl_int(avctx, AV1E_SET_ROW_MT, ctx->row_mt);
666 // provide dummy value to initialize wrapper, values will be updated each _encode()
667 aom_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
670 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
671 ctx->rawimg.bit_depth = enccfg.g_bit_depth;
673 cpb_props = ff_add_cpb_side_data(avctx);
675 return AVERROR(ENOMEM);
677 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
678 const AVBitStreamFilter *filter = av_bsf_get_by_name("extract_extradata");
682 av_log(avctx, AV_LOG_ERROR, "extract_extradata bitstream filter "
683 "not found. This is a bug, please report it.\n");
686 ret = av_bsf_alloc(filter, &ctx->bsf);
690 ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx);
694 ret = av_bsf_init(ctx->bsf);
699 if (enccfg.rc_end_usage == AOM_CBR ||
700 enccfg.g_pass != AOM_RC_ONE_PASS) {
701 cpb_props->max_bitrate = avctx->rc_max_rate;
702 cpb_props->min_bitrate = avctx->rc_min_rate;
703 cpb_props->avg_bitrate = avctx->bit_rate;
705 cpb_props->buffer_size = avctx->rc_buffer_size;
710 static inline void cx_pktcpy(AOMContext *ctx,
711 struct FrameListData *dst,
712 const struct aom_codec_cx_pkt *src)
714 dst->pts = src->data.frame.pts;
715 dst->duration = src->data.frame.duration;
716 dst->flags = src->data.frame.flags;
717 dst->sz = src->data.frame.sz;
718 dst->buf = src->data.frame.buf;
719 #ifdef AOM_FRAME_IS_INTRAONLY
721 dst->frame_number = ++ctx->frame_number;
722 dst->have_sse = ctx->have_sse;
724 /* associate last-seen SSE to the frame. */
725 /* Transfers ownership from ctx to dst. */
726 memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
733 * Store coded frame information in format suitable for return from encode2().
735 * Write information from @a cx_frame to @a pkt
736 * @return packet data size on success
737 * @return a negative AVERROR on error
739 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
742 AOMContext *ctx = avctx->priv_data;
744 int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
746 av_log(avctx, AV_LOG_ERROR,
747 "Error getting output packet of size %"SIZE_SPECIFIER".\n", cx_frame->sz);
750 memcpy(pkt->data, cx_frame->buf, pkt->size);
751 pkt->pts = pkt->dts = cx_frame->pts;
753 if (!!(cx_frame->flags & AOM_FRAME_IS_KEY)) {
754 pkt->flags |= AV_PKT_FLAG_KEY;
755 #ifdef AOM_FRAME_IS_INTRAONLY
756 pict_type = AV_PICTURE_TYPE_I;
757 } else if (cx_frame->flags & AOM_FRAME_IS_INTRAONLY) {
758 pict_type = AV_PICTURE_TYPE_I;
760 pict_type = AV_PICTURE_TYPE_P;
763 ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
764 cx_frame->have_sse ? 3 : 0, pict_type);
766 if (cx_frame->have_sse) {
768 for (i = 0; i < 3; ++i) {
769 avctx->error[i] += cx_frame->sse[i + 1];
771 cx_frame->have_sse = 0;
775 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
776 ret = av_bsf_send_packet(ctx->bsf, pkt);
778 av_log(avctx, AV_LOG_ERROR, "extract_extradata filter "
779 "failed to send input packet\n");
782 ret = av_bsf_receive_packet(ctx->bsf, pkt);
785 av_log(avctx, AV_LOG_ERROR, "extract_extradata filter "
786 "failed to receive output packet\n");
794 * Queue multiple output frames from the encoder, returning the front-most.
795 * In cases where aom_codec_get_cx_data() returns more than 1 frame append
796 * the frame queue. Return the head frame if available.
797 * @return Stored frame size
798 * @return AVERROR(EINVAL) on output size error
799 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
801 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
803 AOMContext *ctx = avctx->priv_data;
804 const struct aom_codec_cx_pkt *pkt;
805 const void *iter = NULL;
808 if (ctx->coded_frame_list) {
809 struct FrameListData *cx_frame = ctx->coded_frame_list;
810 /* return the leading frame if we've already begun queueing */
811 size = storeframe(avctx, cx_frame, pkt_out);
814 ctx->coded_frame_list = cx_frame->next;
815 free_coded_frame(cx_frame);
818 /* consume all available output from the encoder before returning. buffers
819 * are only good through the next aom_codec call */
820 while ((pkt = aom_codec_get_cx_data(&ctx->encoder, &iter))) {
822 case AOM_CODEC_CX_FRAME_PKT:
824 struct FrameListData cx_frame;
826 /* avoid storing the frame when the list is empty and we haven't yet
827 * provided a frame for output */
828 av_assert0(!ctx->coded_frame_list);
829 cx_pktcpy(ctx, &cx_frame, pkt);
830 size = storeframe(avctx, &cx_frame, pkt_out);
834 struct FrameListData *cx_frame =
835 av_malloc(sizeof(struct FrameListData));
838 av_log(avctx, AV_LOG_ERROR,
839 "Frame queue element alloc failed\n");
840 return AVERROR(ENOMEM);
842 cx_pktcpy(ctx, cx_frame, pkt);
843 cx_frame->buf = av_malloc(cx_frame->sz);
845 if (!cx_frame->buf) {
846 av_log(avctx, AV_LOG_ERROR,
847 "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
850 return AVERROR(ENOMEM);
852 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
853 coded_frame_add(&ctx->coded_frame_list, cx_frame);
856 case AOM_CODEC_STATS_PKT:
858 struct aom_fixed_buf *stats = &ctx->twopass_stats;
860 if ((err = av_reallocp(&stats->buf,
862 pkt->data.twopass_stats.sz)) < 0) {
864 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
867 memcpy((uint8_t *)stats->buf + stats->sz,
868 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
869 stats->sz += pkt->data.twopass_stats.sz;
872 #ifdef AOM_FRAME_IS_INTRAONLY
873 case AOM_CODEC_PSNR_PKT:
875 av_assert0(!ctx->have_sse);
876 ctx->sse[0] = pkt->data.psnr.sse[0];
877 ctx->sse[1] = pkt->data.psnr.sse[1];
878 ctx->sse[2] = pkt->data.psnr.sse[2];
879 ctx->sse[3] = pkt->data.psnr.sse[3];
884 case AOM_CODEC_CUSTOM_PKT:
885 // ignore unsupported/unrecognized packet types
893 static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
894 const AVFrame *frame, int *got_packet)
896 AOMContext *ctx = avctx->priv_data;
897 struct aom_image *rawimg = NULL;
898 int64_t timestamp = 0;
900 aom_enc_frame_flags_t flags = 0;
903 rawimg = &ctx->rawimg;
904 rawimg->planes[AOM_PLANE_Y] = frame->data[0];
905 rawimg->planes[AOM_PLANE_U] = frame->data[1];
906 rawimg->planes[AOM_PLANE_V] = frame->data[2];
907 rawimg->stride[AOM_PLANE_Y] = frame->linesize[0];
908 rawimg->stride[AOM_PLANE_U] = frame->linesize[1];
909 rawimg->stride[AOM_PLANE_V] = frame->linesize[2];
910 timestamp = frame->pts;
911 switch (frame->color_range) {
912 case AVCOL_RANGE_MPEG:
913 rawimg->range = AOM_CR_STUDIO_RANGE;
915 case AVCOL_RANGE_JPEG:
916 rawimg->range = AOM_CR_FULL_RANGE;
920 if (frame->pict_type == AV_PICTURE_TYPE_I)
921 flags |= AOM_EFLAG_FORCE_KF;
924 res = aom_codec_encode(&ctx->encoder, rawimg, timestamp,
925 avctx->ticks_per_frame, flags);
926 if (res != AOM_CODEC_OK) {
927 log_encoder_error(avctx, "Error encoding frame");
928 return AVERROR_INVALIDDATA;
930 coded_size = queue_frames(avctx, pkt);
932 if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
933 size_t b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
935 avctx->stats_out = av_malloc(b64_size);
936 if (!avctx->stats_out) {
937 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
939 return AVERROR(ENOMEM);
941 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
942 ctx->twopass_stats.sz);
945 *got_packet = !!coded_size;
949 static const enum AVPixelFormat av1_pix_fmts[] = {
956 static const enum AVPixelFormat av1_pix_fmts_highbd[] = {
960 AV_PIX_FMT_YUV420P10,
961 AV_PIX_FMT_YUV422P10,
962 AV_PIX_FMT_YUV444P10,
963 AV_PIX_FMT_YUV420P12,
964 AV_PIX_FMT_YUV422P12,
965 AV_PIX_FMT_YUV444P12,
969 static av_cold void av1_init_static(AVCodec *codec)
971 aom_codec_caps_t codec_caps = aom_codec_get_caps(aom_codec_av1_cx());
972 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
973 codec->pix_fmts = av1_pix_fmts_highbd;
975 codec->pix_fmts = av1_pix_fmts;
978 static av_cold int av1_init(AVCodecContext *avctx)
980 return aom_init(avctx, aom_codec_av1_cx());
983 #define OFFSET(x) offsetof(AOMContext, x)
984 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
985 static const AVOption options[] = {
986 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 8, VE},
987 { "auto-alt-ref", "Enable use of alternate reference "
988 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
989 { "lag-in-frames", "Number of frames to look ahead at for "
990 "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
991 { "error-resilience", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
992 { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
993 { "crf", "Select the quality for constant quality mode", offsetof(AOMContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE },
994 { "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 },
995 { "drop-threshold", "Frame drop threshold", offsetof(AOMContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
996 { "tiles", "Tile columns x rows", OFFSET(tile_cols), AV_OPT_TYPE_IMAGE_SIZE, { .str = NULL }, 0, 0, VE },
997 { "tile-columns", "Log2 of number of tile columns to use", OFFSET(tile_cols_log2), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
998 { "tile-rows", "Log2 of number of tile rows to use", OFFSET(tile_rows_log2), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
999 { "row-mt", "Enable row based multi-threading", OFFSET(row_mt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, VE},
1003 static const AVCodecDefault defaults[] = {
1004 { "b", "256*1000" },
1008 { "keyint_min", "-1" },
1012 static const AVClass class_aom = {
1013 .class_name = "libaom-av1 encoder",
1014 .item_name = av_default_item_name,
1016 .version = LIBAVUTIL_VERSION_INT,
1019 AVCodec ff_libaom_av1_encoder = {
1020 .name = "libaom-av1",
1021 .long_name = NULL_IF_CONFIG_SMALL("libaom AV1"),
1022 .type = AVMEDIA_TYPE_VIDEO,
1023 .id = AV_CODEC_ID_AV1,
1024 .priv_data_size = sizeof(AOMContext),
1026 .encode2 = aom_encode,
1028 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS | AV_CODEC_CAP_EXPERIMENTAL,
1029 .profiles = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
1030 .priv_class = &class_aom,
1031 .defaults = defaults,
1032 .init_static_data = av1_init_static,
1033 .wrapper_name = "libaom",