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;
83 static const char *const ctlidstr[] = {
84 [AOME_SET_CPUUSED] = "AOME_SET_CPUUSED",
85 [AOME_SET_CQ_LEVEL] = "AOME_SET_CQ_LEVEL",
86 [AOME_SET_ENABLEAUTOALTREF] = "AOME_SET_ENABLEAUTOALTREF",
87 [AOME_SET_STATIC_THRESHOLD] = "AOME_SET_STATIC_THRESHOLD",
88 [AV1E_SET_COLOR_RANGE] = "AV1E_SET_COLOR_RANGE",
89 [AV1E_SET_COLOR_PRIMARIES] = "AV1E_SET_COLOR_PRIMARIES",
90 [AV1E_SET_MATRIX_COEFFICIENTS] = "AV1E_SET_MATRIX_COEFFICIENTS",
91 [AV1E_SET_TRANSFER_CHARACTERISTICS] = "AV1E_SET_TRANSFER_CHARACTERISTICS",
92 [AV1E_SET_SUPERBLOCK_SIZE] = "AV1E_SET_SUPERBLOCK_SIZE",
93 [AV1E_SET_TILE_COLUMNS] = "AV1E_SET_TILE_COLUMNS",
94 [AV1E_SET_TILE_ROWS] = "AV1E_SET_TILE_ROWS",
97 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
99 AOMContext *ctx = avctx->priv_data;
100 const char *error = aom_codec_error(&ctx->encoder);
101 const char *detail = aom_codec_error_detail(&ctx->encoder);
103 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
105 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
108 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
109 const struct aom_codec_enc_cfg *cfg)
112 int level = AV_LOG_DEBUG;
114 av_log(avctx, level, "aom_codec_enc_cfg\n");
115 av_log(avctx, level, "generic settings\n"
116 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
118 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
119 width, "g_usage:", cfg->g_usage,
120 width, "g_threads:", cfg->g_threads,
121 width, "g_profile:", cfg->g_profile,
122 width, "g_w:", cfg->g_w,
123 width, "g_h:", cfg->g_h,
124 width, "g_bit_depth:", cfg->g_bit_depth,
125 width, "g_input_bit_depth:", cfg->g_input_bit_depth,
126 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
127 width, "g_error_resilient:", cfg->g_error_resilient,
128 width, "g_pass:", cfg->g_pass,
129 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
130 av_log(avctx, level, "rate control settings\n"
131 " %*s%u\n %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
132 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
133 width, "rc_end_usage:", cfg->rc_end_usage,
134 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
135 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
136 av_log(avctx, level, "quantizer settings\n"
138 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
139 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
140 av_log(avctx, level, "bitrate tolerance\n"
142 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
143 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
144 av_log(avctx, level, "decoder buffer model\n"
145 " %*s%u\n %*s%u\n %*s%u\n",
146 width, "rc_buf_sz:", cfg->rc_buf_sz,
147 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
148 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
149 av_log(avctx, level, "2 pass rate control settings\n"
150 " %*s%u\n %*s%u\n %*s%u\n",
151 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
152 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
153 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
154 av_log(avctx, level, "keyframing settings\n"
155 " %*s%d\n %*s%u\n %*s%u\n",
156 width, "kf_mode:", cfg->kf_mode,
157 width, "kf_min_dist:", cfg->kf_min_dist,
158 width, "kf_max_dist:", cfg->kf_max_dist);
159 av_log(avctx, level, "tile settings\n"
161 width, "tile_width_count:", cfg->tile_width_count,
162 width, "tile_height_count:", cfg->tile_height_count);
163 av_log(avctx, level, "\n");
166 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
168 struct FrameListData **p = list;
173 cx_frame->next = NULL;
176 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
178 av_freep(&cx_frame->buf);
182 static av_cold void free_frame_list(struct FrameListData *list)
184 struct FrameListData *p = list;
193 static av_cold int codecctl_int(AVCodecContext *avctx,
194 enum aome_enc_control_id id, int val)
196 AOMContext *ctx = avctx->priv_data;
201 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
202 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
204 res = aom_codec_control(&ctx->encoder, id, val);
205 if (res != AOM_CODEC_OK) {
206 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
208 log_encoder_error(avctx, buf);
209 return AVERROR(EINVAL);
215 static av_cold int aom_free(AVCodecContext *avctx)
217 AOMContext *ctx = avctx->priv_data;
219 aom_codec_destroy(&ctx->encoder);
220 av_freep(&ctx->twopass_stats.buf);
221 av_freep(&avctx->stats_out);
222 free_frame_list(ctx->coded_frame_list);
223 av_bsf_free(&ctx->bsf);
227 static int set_pix_fmt(AVCodecContext *avctx, aom_codec_caps_t codec_caps,
228 struct aom_codec_enc_cfg *enccfg, aom_codec_flags_t *flags,
229 aom_img_fmt_t *img_fmt)
231 AOMContext av_unused *ctx = avctx->priv_data;
232 enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
233 switch (avctx->pix_fmt) {
234 case AV_PIX_FMT_YUV420P:
235 enccfg->g_profile = FF_PROFILE_AV1_MAIN;
236 *img_fmt = AOM_IMG_FMT_I420;
238 case AV_PIX_FMT_YUV422P:
239 enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
240 *img_fmt = AOM_IMG_FMT_I422;
242 case AV_PIX_FMT_YUV444P:
243 enccfg->g_profile = FF_PROFILE_AV1_HIGH;
244 *img_fmt = AOM_IMG_FMT_I444;
246 case AV_PIX_FMT_YUV420P10:
247 case AV_PIX_FMT_YUV420P12:
248 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
249 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
250 avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
252 enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_MAIN : FF_PROFILE_AV1_PROFESSIONAL;
253 *img_fmt = AOM_IMG_FMT_I42016;
254 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
258 case AV_PIX_FMT_YUV422P10:
259 case AV_PIX_FMT_YUV422P12:
260 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
261 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
262 avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
263 enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
264 *img_fmt = AOM_IMG_FMT_I42216;
265 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
269 case AV_PIX_FMT_YUV444P10:
270 case AV_PIX_FMT_YUV444P12:
271 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
272 enccfg->g_bit_depth = enccfg->g_input_bit_depth =
273 avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ? 10 : 12;
275 enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_HIGH : FF_PROFILE_AV1_PROFESSIONAL;
276 *img_fmt = AOM_IMG_FMT_I44416;
277 *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
284 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
285 return AVERROR_INVALIDDATA;
288 static void set_color_range(AVCodecContext *avctx)
290 enum aom_color_range aom_cr;
291 switch (avctx->color_range) {
292 case AVCOL_RANGE_UNSPECIFIED:
293 case AVCOL_RANGE_MPEG: aom_cr = AOM_CR_STUDIO_RANGE; break;
294 case AVCOL_RANGE_JPEG: aom_cr = AOM_CR_FULL_RANGE; break;
296 av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
301 codecctl_int(avctx, AV1E_SET_COLOR_RANGE, aom_cr);
304 static int count_uniform_tiling(int dim, int sb_size, int tiles_log2)
306 int sb_dim = (dim + sb_size - 1) / sb_size;
307 int tile_dim = (sb_dim + (1 << tiles_log2) - 1) >> tiles_log2;
308 av_assert0(tile_dim > 0);
309 return (sb_dim + tile_dim - 1) / tile_dim;
312 static int choose_tiling(AVCodecContext *avctx,
313 struct aom_codec_enc_cfg *enccfg)
315 AOMContext *ctx = avctx->priv_data;
316 int sb_128x128_possible, sb_size, sb_width, sb_height;
317 int uniform_rows, uniform_cols;
318 int uniform_64x64_possible, uniform_128x128_possible;
319 int tile_size, rounding, i;
321 if (ctx->tile_cols_log2 >= 0)
322 ctx->tile_cols = 1 << ctx->tile_cols_log2;
323 if (ctx->tile_rows_log2 >= 0)
324 ctx->tile_rows = 1 << ctx->tile_rows_log2;
326 if (ctx->tile_cols == 0) {
327 ctx->tile_cols = (avctx->width + AV1_MAX_TILE_WIDTH - 1) /
329 if (ctx->tile_cols > 1) {
330 av_log(avctx, AV_LOG_DEBUG, "Automatically using %d tile "
331 "columns to fill width.\n", ctx->tile_cols);
334 av_assert0(ctx->tile_cols > 0);
335 if (ctx->tile_rows == 0) {
337 FFALIGN((FFALIGN(avctx->width, 128) +
338 ctx->tile_cols - 1) / ctx->tile_cols, 128);
340 (max_tile_width * FFALIGN(avctx->height, 128) +
341 AV1_MAX_TILE_AREA - 1) / AV1_MAX_TILE_AREA;
342 if (ctx->tile_rows > 1) {
343 av_log(avctx, AV_LOG_DEBUG, "Automatically using %d tile "
344 "rows to fill area.\n", ctx->tile_rows);
347 av_assert0(ctx->tile_rows > 0);
349 if ((avctx->width + 63) / 64 < ctx->tile_cols ||
350 (avctx->height + 63) / 64 < ctx->tile_rows) {
351 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: frame not "
352 "large enough to fit specified tile arrangement.\n");
353 return AVERROR(EINVAL);
355 if (ctx->tile_cols > AV1_MAX_TILE_COLS ||
356 ctx->tile_rows > AV1_MAX_TILE_ROWS) {
357 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: AV1 does "
358 "not allow more than %dx%d tiles.\n",
359 AV1_MAX_TILE_COLS, AV1_MAX_TILE_ROWS);
360 return AVERROR(EINVAL);
362 if (avctx->width / ctx->tile_cols > AV1_MAX_TILE_WIDTH) {
363 av_log(avctx, AV_LOG_ERROR, "Invalid tile sizing: AV1 does "
364 "not allow tiles of width greater than %d.\n",
366 return AVERROR(EINVAL);
369 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_DYNAMIC;
371 if (ctx->tile_cols == 1 && ctx->tile_rows == 1) {
372 av_log(avctx, AV_LOG_DEBUG, "Using a single tile.\n");
376 sb_128x128_possible =
377 (avctx->width + 127) / 128 >= ctx->tile_cols &&
378 (avctx->height + 127) / 128 >= ctx->tile_rows;
380 ctx->tile_cols_log2 = ctx->tile_cols == 1 ? 0 :
381 av_log2(ctx->tile_cols - 1) + 1;
382 ctx->tile_rows_log2 = ctx->tile_rows == 1 ? 0 :
383 av_log2(ctx->tile_rows - 1) + 1;
385 uniform_cols = count_uniform_tiling(avctx->width,
386 64, ctx->tile_cols_log2);
387 uniform_rows = count_uniform_tiling(avctx->height,
388 64, ctx->tile_rows_log2);
389 av_log(avctx, AV_LOG_DEBUG, "Uniform with 64x64 superblocks "
390 "-> %dx%d tiles.\n", uniform_cols, uniform_rows);
391 uniform_64x64_possible = uniform_cols == ctx->tile_cols &&
392 uniform_rows == ctx->tile_rows;
394 if (sb_128x128_possible) {
395 uniform_cols = count_uniform_tiling(avctx->width,
396 128, ctx->tile_cols_log2);
397 uniform_rows = count_uniform_tiling(avctx->height,
398 128, ctx->tile_rows_log2);
399 av_log(avctx, AV_LOG_DEBUG, "Uniform with 128x128 superblocks "
400 "-> %dx%d tiles.\n", uniform_cols, uniform_rows);
401 uniform_128x128_possible = uniform_cols == ctx->tile_cols &&
402 uniform_rows == ctx->tile_rows;
404 av_log(avctx, AV_LOG_DEBUG, "128x128 superblocks not possible.\n");
405 uniform_128x128_possible = 0;
408 ctx->uniform_tiles = 1;
409 if (uniform_64x64_possible && uniform_128x128_possible) {
410 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with dynamic "
411 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
412 ctx->tile_cols_log2, ctx->tile_rows_log2);
415 if (uniform_64x64_possible && !sb_128x128_possible) {
416 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with 64x64 "
417 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
418 ctx->tile_cols_log2, ctx->tile_rows_log2);
419 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_64X64;
422 if (uniform_128x128_possible) {
423 av_log(avctx, AV_LOG_DEBUG, "Using uniform tiling with 128x128 "
424 "superblocks (tile_cols_log2 = %d, tile_rows_log2 = %d).\n",
425 ctx->tile_cols_log2, ctx->tile_rows_log2);
426 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_128X128;
429 ctx->uniform_tiles = 0;
431 if (sb_128x128_possible) {
433 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_128X128;
436 ctx->superblock_size = AOM_SUPERBLOCK_SIZE_64X64;
438 av_log(avctx, AV_LOG_DEBUG, "Using fixed tiling with %dx%d "
439 "superblocks (tile_cols = %d, tile_rows = %d).\n",
440 sb_size, sb_size, ctx->tile_cols, ctx->tile_rows);
442 enccfg->tile_width_count = ctx->tile_cols;
443 enccfg->tile_height_count = ctx->tile_rows;
445 sb_width = (avctx->width + sb_size - 1) / sb_size;
446 sb_height = (avctx->height + sb_size - 1) / sb_size;
448 tile_size = sb_width / ctx->tile_cols;
449 rounding = sb_width % ctx->tile_cols;
450 for (i = 0; i < ctx->tile_cols; i++) {
451 enccfg->tile_widths[i] = tile_size +
453 i > ctx->tile_cols - 1 - (rounding + 1) / 2);
456 tile_size = sb_height / ctx->tile_rows;
457 rounding = sb_height % ctx->tile_rows;
458 for (i = 0; i < ctx->tile_rows; i++) {
459 enccfg->tile_heights[i] = tile_size +
461 i > ctx->tile_rows - 1 - (rounding + 1) / 2);
467 static av_cold int aom_init(AVCodecContext *avctx,
468 const struct aom_codec_iface *iface)
470 AOMContext *ctx = avctx->priv_data;
471 struct aom_codec_enc_cfg enccfg = { 0 };
472 #ifdef AOM_FRAME_IS_INTRAONLY
473 aom_codec_flags_t flags =
474 (avctx->flags & AV_CODEC_FLAG_PSNR) ? AOM_CODEC_USE_PSNR : 0;
476 aom_codec_flags_t flags = 0;
478 AVCPBProperties *cpb_props;
480 aom_img_fmt_t img_fmt;
481 aom_codec_caps_t codec_caps = aom_codec_get_caps(iface);
483 av_log(avctx, AV_LOG_INFO, "%s\n", aom_codec_version_str());
484 av_log(avctx, AV_LOG_VERBOSE, "%s\n", aom_codec_build_config());
486 if ((res = aom_codec_enc_config_default(iface, &enccfg, 0)) != AOM_CODEC_OK) {
487 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
488 aom_codec_err_to_string(res));
489 return AVERROR(EINVAL);
492 if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
493 return AVERROR(EINVAL);
496 if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
497 av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
498 return AVERROR(EINVAL);
501 dump_enc_cfg(avctx, &enccfg);
503 enccfg.g_w = avctx->width;
504 enccfg.g_h = avctx->height;
505 enccfg.g_timebase.num = avctx->time_base.num;
506 enccfg.g_timebase.den = avctx->time_base.den;
508 FFMIN(avctx->thread_count ? avctx->thread_count : av_cpu_count(), 64);
510 if (ctx->lag_in_frames >= 0)
511 enccfg.g_lag_in_frames = ctx->lag_in_frames;
513 if (avctx->flags & AV_CODEC_FLAG_PASS1)
514 enccfg.g_pass = AOM_RC_FIRST_PASS;
515 else if (avctx->flags & AV_CODEC_FLAG_PASS2)
516 enccfg.g_pass = AOM_RC_LAST_PASS;
518 enccfg.g_pass = AOM_RC_ONE_PASS;
520 if (avctx->rc_min_rate == avctx->rc_max_rate &&
521 avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
522 enccfg.rc_end_usage = AOM_CBR;
523 } else if (ctx->crf >= 0) {
524 enccfg.rc_end_usage = AOM_CQ;
525 if (!avctx->bit_rate)
526 enccfg.rc_end_usage = AOM_Q;
529 if (avctx->bit_rate) {
530 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
532 } else if (enccfg.rc_end_usage != AOM_Q) {
533 if (enccfg.rc_end_usage == AOM_CQ) {
534 enccfg.rc_target_bitrate = 1000000;
536 avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
537 av_log(avctx, AV_LOG_WARNING,
538 "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
539 enccfg.rc_target_bitrate);
543 if (avctx->qmin >= 0)
544 enccfg.rc_min_quantizer = avctx->qmin;
545 if (avctx->qmax >= 0)
546 enccfg.rc_max_quantizer = avctx->qmax;
548 if (enccfg.rc_end_usage == AOM_CQ || enccfg.rc_end_usage == AOM_Q) {
549 if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
550 av_log(avctx, AV_LOG_ERROR,
551 "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
552 ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
553 return AVERROR(EINVAL);
557 enccfg.rc_dropframe_thresh = ctx->drop_threshold;
559 // 0-100 (0 => CBR, 100 => VBR)
560 enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
562 enccfg.rc_2pass_vbr_minsection_pct =
563 avctx->rc_min_rate * 100LL / avctx->bit_rate;
564 if (avctx->rc_max_rate)
565 enccfg.rc_2pass_vbr_maxsection_pct =
566 avctx->rc_max_rate * 100LL / avctx->bit_rate;
568 if (avctx->rc_buffer_size)
570 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
571 if (avctx->rc_initial_buffer_occupancy)
572 enccfg.rc_buf_initial_sz =
573 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
574 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
576 // _enc_init() will balk if kf_min_dist differs from max w/AOM_KF_AUTO
577 if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
578 enccfg.kf_min_dist = avctx->keyint_min;
579 if (avctx->gop_size >= 0)
580 enccfg.kf_max_dist = avctx->gop_size;
582 if (enccfg.g_pass == AOM_RC_FIRST_PASS)
583 enccfg.g_lag_in_frames = 0;
584 else if (enccfg.g_pass == AOM_RC_LAST_PASS) {
585 int decode_size, ret;
587 if (!avctx->stats_in) {
588 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
589 return AVERROR_INVALIDDATA;
592 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
593 ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
595 av_log(avctx, AV_LOG_ERROR,
596 "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
597 ctx->twopass_stats.sz);
598 ctx->twopass_stats.sz = 0;
601 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
602 ctx->twopass_stats.sz);
603 if (decode_size < 0) {
604 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
605 return AVERROR_INVALIDDATA;
608 ctx->twopass_stats.sz = decode_size;
609 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
612 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
613 * complexity playback on low powered devices at the expense of encode
615 if (avctx->profile != FF_PROFILE_UNKNOWN)
616 enccfg.g_profile = avctx->profile;
618 enccfg.g_error_resilient = ctx->error_resilient;
620 res = choose_tiling(avctx, &enccfg);
624 dump_enc_cfg(avctx, &enccfg);
625 /* Construct Encoder Context */
626 res = aom_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
627 if (res != AOM_CODEC_OK) {
628 log_encoder_error(avctx, "Failed to initialize encoder");
629 return AVERROR(EINVAL);
632 // codec control failures are currently treated only as warnings
633 av_log(avctx, AV_LOG_DEBUG, "aom_codec_control\n");
634 codecctl_int(avctx, AOME_SET_CPUUSED, ctx->cpu_used);
635 if (ctx->auto_alt_ref >= 0)
636 codecctl_int(avctx, AOME_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
638 codecctl_int(avctx, AOME_SET_STATIC_THRESHOLD, ctx->static_thresh);
640 codecctl_int(avctx, AOME_SET_CQ_LEVEL, ctx->crf);
642 codecctl_int(avctx, AV1E_SET_COLOR_PRIMARIES, avctx->color_primaries);
643 codecctl_int(avctx, AV1E_SET_MATRIX_COEFFICIENTS, avctx->colorspace);
644 codecctl_int(avctx, AV1E_SET_TRANSFER_CHARACTERISTICS, avctx->color_trc);
645 set_color_range(avctx);
647 codecctl_int(avctx, AV1E_SET_SUPERBLOCK_SIZE, ctx->superblock_size);
648 if (ctx->uniform_tiles) {
649 codecctl_int(avctx, AV1E_SET_TILE_COLUMNS, ctx->tile_cols_log2);
650 codecctl_int(avctx, AV1E_SET_TILE_ROWS, ctx->tile_rows_log2);
653 // provide dummy value to initialize wrapper, values will be updated each _encode()
654 aom_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
657 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
658 ctx->rawimg.bit_depth = enccfg.g_bit_depth;
660 cpb_props = ff_add_cpb_side_data(avctx);
662 return AVERROR(ENOMEM);
664 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
665 const AVBitStreamFilter *filter = av_bsf_get_by_name("extract_extradata");
669 av_log(avctx, AV_LOG_ERROR, "extract_extradata bitstream filter "
670 "not found. This is a bug, please report it.\n");
673 ret = av_bsf_alloc(filter, &ctx->bsf);
677 ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx);
681 ret = av_bsf_init(ctx->bsf);
686 if (enccfg.rc_end_usage == AOM_CBR ||
687 enccfg.g_pass != AOM_RC_ONE_PASS) {
688 cpb_props->max_bitrate = avctx->rc_max_rate;
689 cpb_props->min_bitrate = avctx->rc_min_rate;
690 cpb_props->avg_bitrate = avctx->bit_rate;
692 cpb_props->buffer_size = avctx->rc_buffer_size;
697 static inline void cx_pktcpy(AOMContext *ctx,
698 struct FrameListData *dst,
699 const struct aom_codec_cx_pkt *src)
701 dst->pts = src->data.frame.pts;
702 dst->duration = src->data.frame.duration;
703 dst->flags = src->data.frame.flags;
704 dst->sz = src->data.frame.sz;
705 dst->buf = src->data.frame.buf;
706 #ifdef AOM_FRAME_IS_INTRAONLY
708 dst->frame_number = ++ctx->frame_number;
709 dst->have_sse = ctx->have_sse;
711 /* associate last-seen SSE to the frame. */
712 /* Transfers ownership from ctx to dst. */
713 memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
720 * Store coded frame information in format suitable for return from encode2().
722 * Write information from @a cx_frame to @a pkt
723 * @return packet data size on success
724 * @return a negative AVERROR on error
726 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
729 AOMContext *ctx = avctx->priv_data;
731 int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
733 av_log(avctx, AV_LOG_ERROR,
734 "Error getting output packet of size %"SIZE_SPECIFIER".\n", cx_frame->sz);
737 memcpy(pkt->data, cx_frame->buf, pkt->size);
738 pkt->pts = pkt->dts = cx_frame->pts;
740 if (!!(cx_frame->flags & AOM_FRAME_IS_KEY)) {
741 pkt->flags |= AV_PKT_FLAG_KEY;
742 #ifdef AOM_FRAME_IS_INTRAONLY
743 pict_type = AV_PICTURE_TYPE_I;
744 } else if (cx_frame->flags & AOM_FRAME_IS_INTRAONLY) {
745 pict_type = AV_PICTURE_TYPE_I;
747 pict_type = AV_PICTURE_TYPE_P;
750 ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
751 cx_frame->have_sse ? 3 : 0, pict_type);
753 if (cx_frame->have_sse) {
755 for (i = 0; i < 3; ++i) {
756 avctx->error[i] += cx_frame->sse[i + 1];
758 cx_frame->have_sse = 0;
762 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
763 ret = av_bsf_send_packet(ctx->bsf, pkt);
765 av_log(avctx, AV_LOG_ERROR, "extract_extradata filter "
766 "failed to send input packet\n");
769 ret = av_bsf_receive_packet(ctx->bsf, pkt);
772 av_log(avctx, AV_LOG_ERROR, "extract_extradata filter "
773 "failed to receive output packet\n");
781 * Queue multiple output frames from the encoder, returning the front-most.
782 * In cases where aom_codec_get_cx_data() returns more than 1 frame append
783 * the frame queue. Return the head frame if available.
784 * @return Stored frame size
785 * @return AVERROR(EINVAL) on output size error
786 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
788 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
790 AOMContext *ctx = avctx->priv_data;
791 const struct aom_codec_cx_pkt *pkt;
792 const void *iter = NULL;
795 if (ctx->coded_frame_list) {
796 struct FrameListData *cx_frame = ctx->coded_frame_list;
797 /* return the leading frame if we've already begun queueing */
798 size = storeframe(avctx, cx_frame, pkt_out);
801 ctx->coded_frame_list = cx_frame->next;
802 free_coded_frame(cx_frame);
805 /* consume all available output from the encoder before returning. buffers
806 * are only good through the next aom_codec call */
807 while ((pkt = aom_codec_get_cx_data(&ctx->encoder, &iter))) {
809 case AOM_CODEC_CX_FRAME_PKT:
811 struct FrameListData cx_frame;
813 /* avoid storing the frame when the list is empty and we haven't yet
814 * provided a frame for output */
815 av_assert0(!ctx->coded_frame_list);
816 cx_pktcpy(ctx, &cx_frame, pkt);
817 size = storeframe(avctx, &cx_frame, pkt_out);
821 struct FrameListData *cx_frame =
822 av_malloc(sizeof(struct FrameListData));
825 av_log(avctx, AV_LOG_ERROR,
826 "Frame queue element alloc failed\n");
827 return AVERROR(ENOMEM);
829 cx_pktcpy(ctx, cx_frame, pkt);
830 cx_frame->buf = av_malloc(cx_frame->sz);
832 if (!cx_frame->buf) {
833 av_log(avctx, AV_LOG_ERROR,
834 "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
837 return AVERROR(ENOMEM);
839 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
840 coded_frame_add(&ctx->coded_frame_list, cx_frame);
843 case AOM_CODEC_STATS_PKT:
845 struct aom_fixed_buf *stats = &ctx->twopass_stats;
847 if ((err = av_reallocp(&stats->buf,
849 pkt->data.twopass_stats.sz)) < 0) {
851 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
854 memcpy((uint8_t *)stats->buf + stats->sz,
855 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
856 stats->sz += pkt->data.twopass_stats.sz;
859 #ifdef AOM_FRAME_IS_INTRAONLY
860 case AOM_CODEC_PSNR_PKT:
862 av_assert0(!ctx->have_sse);
863 ctx->sse[0] = pkt->data.psnr.sse[0];
864 ctx->sse[1] = pkt->data.psnr.sse[1];
865 ctx->sse[2] = pkt->data.psnr.sse[2];
866 ctx->sse[3] = pkt->data.psnr.sse[3];
871 case AOM_CODEC_CUSTOM_PKT:
872 // ignore unsupported/unrecognized packet types
880 static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
881 const AVFrame *frame, int *got_packet)
883 AOMContext *ctx = avctx->priv_data;
884 struct aom_image *rawimg = NULL;
885 int64_t timestamp = 0;
887 aom_enc_frame_flags_t flags = 0;
890 rawimg = &ctx->rawimg;
891 rawimg->planes[AOM_PLANE_Y] = frame->data[0];
892 rawimg->planes[AOM_PLANE_U] = frame->data[1];
893 rawimg->planes[AOM_PLANE_V] = frame->data[2];
894 rawimg->stride[AOM_PLANE_Y] = frame->linesize[0];
895 rawimg->stride[AOM_PLANE_U] = frame->linesize[1];
896 rawimg->stride[AOM_PLANE_V] = frame->linesize[2];
897 timestamp = frame->pts;
898 switch (frame->color_range) {
899 case AVCOL_RANGE_MPEG:
900 rawimg->range = AOM_CR_STUDIO_RANGE;
902 case AVCOL_RANGE_JPEG:
903 rawimg->range = AOM_CR_FULL_RANGE;
907 if (frame->pict_type == AV_PICTURE_TYPE_I)
908 flags |= AOM_EFLAG_FORCE_KF;
911 res = aom_codec_encode(&ctx->encoder, rawimg, timestamp,
912 avctx->ticks_per_frame, flags);
913 if (res != AOM_CODEC_OK) {
914 log_encoder_error(avctx, "Error encoding frame");
915 return AVERROR_INVALIDDATA;
917 coded_size = queue_frames(avctx, pkt);
919 if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
920 size_t b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
922 avctx->stats_out = av_malloc(b64_size);
923 if (!avctx->stats_out) {
924 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
926 return AVERROR(ENOMEM);
928 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
929 ctx->twopass_stats.sz);
932 *got_packet = !!coded_size;
936 static const enum AVPixelFormat av1_pix_fmts[] = {
943 static const enum AVPixelFormat av1_pix_fmts_highbd[] = {
947 AV_PIX_FMT_YUV420P10,
948 AV_PIX_FMT_YUV422P10,
949 AV_PIX_FMT_YUV444P10,
950 AV_PIX_FMT_YUV420P12,
951 AV_PIX_FMT_YUV422P12,
952 AV_PIX_FMT_YUV444P12,
956 static av_cold void av1_init_static(AVCodec *codec)
958 aom_codec_caps_t codec_caps = aom_codec_get_caps(aom_codec_av1_cx());
959 if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
960 codec->pix_fmts = av1_pix_fmts_highbd;
962 codec->pix_fmts = av1_pix_fmts;
965 static av_cold int av1_init(AVCodecContext *avctx)
967 return aom_init(avctx, aom_codec_av1_cx());
970 #define OFFSET(x) offsetof(AOMContext, x)
971 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
972 static const AVOption options[] = {
973 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 8, VE},
974 { "auto-alt-ref", "Enable use of alternate reference "
975 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
976 { "lag-in-frames", "Number of frames to look ahead at for "
977 "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
978 { "error-resilience", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
979 { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
980 { "crf", "Select the quality for constant quality mode", offsetof(AOMContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE },
981 { "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 },
982 { "drop-threshold", "Frame drop threshold", offsetof(AOMContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
983 { "tiles", "Tile columns x rows", OFFSET(tile_cols), AV_OPT_TYPE_IMAGE_SIZE, { .str = NULL }, 0, 0, VE },
984 { "tile-columns", "Log2 of number of tile columns to use", OFFSET(tile_cols_log2), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
985 { "tile-rows", "Log2 of number of tile rows to use", OFFSET(tile_rows_log2), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
989 static const AVCodecDefault defaults[] = {
994 { "keyint_min", "-1" },
998 static const AVClass class_aom = {
999 .class_name = "libaom-av1 encoder",
1000 .item_name = av_default_item_name,
1002 .version = LIBAVUTIL_VERSION_INT,
1005 AVCodec ff_libaom_av1_encoder = {
1006 .name = "libaom-av1",
1007 .long_name = NULL_IF_CONFIG_SMALL("libaom AV1"),
1008 .type = AVMEDIA_TYPE_VIDEO,
1009 .id = AV_CODEC_ID_AV1,
1010 .priv_data_size = sizeof(AOMContext),
1012 .encode2 = aom_encode,
1014 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS | AV_CODEC_CAP_EXPERIMENTAL,
1015 .profiles = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
1016 .priv_class = &class_aom,
1017 .defaults = defaults,
1018 .init_static_data = av1_init_static,
1019 .wrapper_name = "libaom",