2 * Copyright (c) 2010, Google, Inc.
4 * This file is part of Libav.
6 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #define AOM_DISABLE_CTRL_TYPECHECKS 1
22 #include <aom/aom_encoder.h>
23 #include <aom/aomcx.h>
25 #include "libavutil/base64.h"
26 #include "libavutil/common.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
36 * Portion of struct aom_codec_cx_pkt from aom_encoder.h.
37 * One encoded frame returned from the library.
39 struct FrameListData {
40 void *buf; /* compressed data buffer */
41 size_t sz; /* length of compressed data */
42 int64_t pts; /* time stamp to show frame
43 * (in timebase units) */
44 unsigned long duration; /* duration to show frame
45 * (in timebase units) */
46 uint32_t flags; /* flags for this frame */
47 struct FrameListData *next;
50 typedef struct AOMEncoderContext {
52 struct aom_codec_ctx encoder;
53 struct aom_image rawimg;
54 struct aom_fixed_buf twopass_stats;
55 struct FrameListData *coded_frame_list;
63 int noise_sensitivity;
66 static const char *const ctlidstr[] = {
67 [AOME_SET_CPUUSED] = "AOME_SET_CPUUSED",
68 [AOME_SET_CQ_LEVEL] = "AOME_SET_CQ_LEVEL",
69 [AOME_SET_ENABLEAUTOALTREF] = "AOME_SET_ENABLEAUTOALTREF",
70 [AOME_SET_STATIC_THRESHOLD] = "AOME_SET_STATIC_THRESHOLD",
73 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
75 AOMContext *ctx = avctx->priv_data;
76 const char *error = aom_codec_error(&ctx->encoder);
77 const char *detail = aom_codec_error_detail(&ctx->encoder);
79 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
81 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
84 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
85 const struct aom_codec_enc_cfg *cfg)
88 int level = AV_LOG_DEBUG;
90 av_log(avctx, level, "aom_codec_enc_cfg\n");
91 av_log(avctx, level, "generic settings\n"
92 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
93 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
94 width, "g_usage:", cfg->g_usage,
95 width, "g_threads:", cfg->g_threads,
96 width, "g_profile:", cfg->g_profile,
97 width, "g_w:", cfg->g_w,
98 width, "g_h:", cfg->g_h,
99 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
100 width, "g_error_resilient:", cfg->g_error_resilient,
101 width, "g_pass:", cfg->g_pass,
102 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
103 av_log(avctx, level, "rate control settings\n"
104 " %*s%u\n %*s%d\n %*s%p(%zu)\n %*s%u\n",
105 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
106 width, "rc_end_usage:", cfg->rc_end_usage,
107 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
108 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
109 av_log(avctx, level, "quantizer settings\n"
111 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
112 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
113 av_log(avctx, level, "bitrate tolerance\n"
115 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
116 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
117 av_log(avctx, level, "decoder buffer model\n"
118 " %*s%u\n %*s%u\n %*s%u\n",
119 width, "rc_buf_sz:", cfg->rc_buf_sz,
120 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
121 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
122 av_log(avctx, level, "2 pass rate control settings\n"
123 " %*s%u\n %*s%u\n %*s%u\n",
124 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
125 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
126 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
127 av_log(avctx, level, "keyframing settings\n"
128 " %*s%d\n %*s%u\n %*s%u\n",
129 width, "kf_mode:", cfg->kf_mode,
130 width, "kf_min_dist:", cfg->kf_min_dist,
131 width, "kf_max_dist:", cfg->kf_max_dist);
132 av_log(avctx, level, "\n");
135 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
137 struct FrameListData **p = list;
142 cx_frame->next = NULL;
145 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
147 av_freep(&cx_frame->buf);
151 static av_cold void free_frame_list(struct FrameListData *list)
153 struct FrameListData *p = list;
162 static av_cold int codecctl_int(AVCodecContext *avctx,
163 enum aome_enc_control_id id, int val)
165 AOMContext *ctx = avctx->priv_data;
170 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
171 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
173 res = aom_codec_control(&ctx->encoder, id, val);
174 if (res != AOM_CODEC_OK) {
175 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
177 log_encoder_error(avctx, buf);
178 return AVERROR(EINVAL);
184 static av_cold int aom_free(AVCodecContext *avctx)
186 AOMContext *ctx = avctx->priv_data;
188 aom_codec_destroy(&ctx->encoder);
189 av_freep(&ctx->twopass_stats.buf);
190 av_freep(&avctx->stats_out);
191 free_frame_list(ctx->coded_frame_list);
195 static av_cold int aom_init(AVCodecContext *avctx)
197 AOMContext *ctx = avctx->priv_data;
198 struct aom_codec_enc_cfg enccfg = { 0 };
199 AVCPBProperties *cpb_props;
201 const struct aom_codec_iface *iface = &aom_codec_av1_cx_algo;
203 av_log(avctx, AV_LOG_INFO, "%s\n", aom_codec_version_str());
204 av_log(avctx, AV_LOG_VERBOSE, "%s\n", aom_codec_build_config());
206 if ((res = aom_codec_enc_config_default(iface, &enccfg, 0)) != AOM_CODEC_OK) {
207 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
208 aom_codec_err_to_string(res));
209 return AVERROR(EINVAL);
211 dump_enc_cfg(avctx, &enccfg);
213 enccfg.g_w = avctx->width;
214 enccfg.g_h = avctx->height;
215 enccfg.g_timebase.num = avctx->time_base.num;
216 enccfg.g_timebase.den = avctx->time_base.den;
217 enccfg.g_threads = avctx->thread_count;
219 if (ctx->lag_in_frames >= 0)
220 enccfg.g_lag_in_frames = ctx->lag_in_frames;
222 if (avctx->flags & AV_CODEC_FLAG_PASS1)
223 enccfg.g_pass = AOM_RC_FIRST_PASS;
224 else if (avctx->flags & AV_CODEC_FLAG_PASS2)
225 enccfg.g_pass = AOM_RC_LAST_PASS;
227 enccfg.g_pass = AOM_RC_ONE_PASS;
229 if (!avctx->bit_rate)
230 avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
232 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
236 enccfg.rc_end_usage = AOM_CQ;
237 else if (avctx->rc_min_rate == avctx->rc_max_rate &&
238 avctx->rc_min_rate == avctx->bit_rate)
239 enccfg.rc_end_usage = AOM_CBR;
242 enccfg.rc_min_quantizer = avctx->qmin;
244 enccfg.rc_max_quantizer = avctx->qmax;
246 enccfg.rc_dropframe_thresh = ctx->drop_threshold;
248 // 0-100 (0 => CBR, 100 => VBR)
249 enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
250 enccfg.rc_2pass_vbr_minsection_pct =
251 avctx->rc_min_rate * 100LL / avctx->bit_rate;
252 if (avctx->rc_max_rate)
253 enccfg.rc_2pass_vbr_maxsection_pct =
254 avctx->rc_max_rate * 100LL / avctx->bit_rate;
256 if (avctx->rc_buffer_size)
258 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
259 if (avctx->rc_initial_buffer_occupancy)
260 enccfg.rc_buf_initial_sz =
261 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
262 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
264 // _enc_init() will balk if kf_min_dist differs from max w/AOM_KF_AUTO
265 if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
266 enccfg.kf_min_dist = avctx->keyint_min;
267 if (avctx->gop_size >= 0)
268 enccfg.kf_max_dist = avctx->gop_size;
270 if (enccfg.g_pass == AOM_RC_FIRST_PASS)
271 enccfg.g_lag_in_frames = 0;
272 else if (enccfg.g_pass == AOM_RC_LAST_PASS) {
273 int decode_size, ret;
275 if (!avctx->stats_in) {
276 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
277 return AVERROR_INVALIDDATA;
280 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
281 ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
283 av_log(avctx, AV_LOG_ERROR,
284 "Stat buffer alloc (%zu bytes) failed\n",
285 ctx->twopass_stats.sz);
288 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
289 ctx->twopass_stats.sz);
290 if (decode_size < 0) {
291 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
292 return AVERROR_INVALIDDATA;
295 ctx->twopass_stats.sz = decode_size;
296 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
299 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
300 * complexity playback on low powered devices at the expense of encode
302 if (avctx->profile != FF_PROFILE_UNKNOWN)
303 enccfg.g_profile = avctx->profile;
304 else if (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
305 avctx->pix_fmt == AV_PIX_FMT_YUV420P10)
306 avctx->profile = enccfg.g_profile = FF_PROFILE_AV1_MAIN;
307 else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
308 avctx->pix_fmt == AV_PIX_FMT_YUV444P10)
309 avctx->profile = enccfg.g_profile = FF_PROFILE_AV1_HIGH;
311 avctx->profile = enccfg.g_profile = FF_PROFILE_AV1_PROFESSIONAL;
315 enccfg.g_error_resilient = ctx->error_resilient;
317 dump_enc_cfg(avctx, &enccfg);
318 /* Construct Encoder Context */
319 res = aom_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
320 if (res != AOM_CODEC_OK) {
321 log_encoder_error(avctx, "Failed to initialize encoder");
322 return AVERROR(EINVAL);
325 // codec control failures are currently treated only as warnings
326 av_log(avctx, AV_LOG_DEBUG, "aom_codec_control\n");
327 if (ctx->cpu_used != INT_MIN)
328 codecctl_int(avctx, AOME_SET_CPUUSED, ctx->cpu_used);
329 if (ctx->auto_alt_ref >= 0)
330 codecctl_int(avctx, AOME_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
332 codecctl_int(avctx, AOME_SET_STATIC_THRESHOLD, ctx->static_thresh);
333 codecctl_int(avctx, AOME_SET_CQ_LEVEL, ctx->crf);
335 // provide dummy value to initialize wrapper, values will be updated each _encode()
336 aom_img_wrap(&ctx->rawimg, ff_aom_pixfmt_to_imgfmt(avctx->pix_fmt),
337 avctx->width, avctx->height, 1, (unsigned char *)1);
339 cpb_props = ff_add_cpb_side_data(avctx);
341 return AVERROR(ENOMEM);
343 if (enccfg.rc_end_usage == AOM_CBR ||
344 enccfg.g_pass != AOM_RC_ONE_PASS) {
345 cpb_props->max_bitrate = avctx->rc_max_rate;
346 cpb_props->min_bitrate = avctx->rc_min_rate;
347 cpb_props->avg_bitrate = avctx->bit_rate;
349 cpb_props->buffer_size = avctx->rc_buffer_size;
354 static inline void cx_pktcpy(struct FrameListData *dst,
355 const struct aom_codec_cx_pkt *src)
357 dst->pts = src->data.frame.pts;
358 dst->duration = src->data.frame.duration;
359 dst->flags = src->data.frame.flags;
360 dst->sz = src->data.frame.sz;
361 dst->buf = src->data.frame.buf;
365 * Store coded frame information in format suitable for return from encode2().
367 * Write information from @a cx_frame to @a pkt
368 * @return packet data size on success
369 * @return a negative AVERROR on error
371 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
374 int ret = ff_alloc_packet(pkt, cx_frame->sz);
376 av_log(avctx, AV_LOG_ERROR,
377 "Error getting output packet of size %zu.\n", cx_frame->sz);
380 memcpy(pkt->data, cx_frame->buf, pkt->size);
381 pkt->pts = pkt->dts = cx_frame->pts;
383 if (!!(cx_frame->flags & AOM_FRAME_IS_KEY))
384 pkt->flags |= AV_PKT_FLAG_KEY;
389 * Queue multiple output frames from the encoder, returning the front-most.
390 * In cases where aom_codec_get_cx_data() returns more than 1 frame append
391 * the frame queue. Return the head frame if available.
392 * @return Stored frame size
393 * @return AVERROR(EINVAL) on output size error
394 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
396 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
398 AOMContext *ctx = avctx->priv_data;
399 const struct aom_codec_cx_pkt *pkt;
400 const void *iter = NULL;
403 if (ctx->coded_frame_list) {
404 struct FrameListData *cx_frame = ctx->coded_frame_list;
405 /* return the leading frame if we've already begun queueing */
406 size = storeframe(avctx, cx_frame, pkt_out);
409 ctx->coded_frame_list = cx_frame->next;
410 free_coded_frame(cx_frame);
413 /* consume all available output from the encoder before returning. buffers
414 * are only good through the next aom_codec call */
415 while ((pkt = aom_codec_get_cx_data(&ctx->encoder, &iter))) {
417 case AOM_CODEC_CX_FRAME_PKT:
419 struct FrameListData cx_frame;
421 /* avoid storing the frame when the list is empty and we haven't yet
422 * provided a frame for output */
423 assert(!ctx->coded_frame_list);
424 cx_pktcpy(&cx_frame, pkt);
425 size = storeframe(avctx, &cx_frame, pkt_out);
429 struct FrameListData *cx_frame =
430 av_malloc(sizeof(struct FrameListData));
433 av_log(avctx, AV_LOG_ERROR,
434 "Frame queue element alloc failed\n");
435 return AVERROR(ENOMEM);
437 cx_pktcpy(cx_frame, pkt);
438 cx_frame->buf = av_malloc(cx_frame->sz);
440 if (!cx_frame->buf) {
441 av_log(avctx, AV_LOG_ERROR,
442 "Data buffer alloc (%zu bytes) failed\n",
445 return AVERROR(ENOMEM);
447 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
448 coded_frame_add(&ctx->coded_frame_list, cx_frame);
451 case AOM_CODEC_STATS_PKT:
453 struct aom_fixed_buf *stats = &ctx->twopass_stats;
455 if ((err = av_reallocp(&stats->buf,
457 pkt->data.twopass_stats.sz)) < 0) {
459 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
462 memcpy((uint8_t *)stats->buf + stats->sz,
463 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
464 stats->sz += pkt->data.twopass_stats.sz;
467 case AOM_CODEC_PSNR_PKT: // FIXME add support for AV_CODEC_FLAG_PSNR
468 case AOM_CODEC_CUSTOM_PKT:
469 // ignore unsupported/unrecognized packet types
477 static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
478 const AVFrame *frame, int *got_packet)
480 AOMContext *ctx = avctx->priv_data;
481 struct aom_image *rawimg = NULL;
482 int64_t timestamp = 0;
484 aom_enc_frame_flags_t flags = 0;
487 rawimg = &ctx->rawimg;
488 rawimg->planes[AOM_PLANE_Y] = frame->data[0];
489 rawimg->planes[AOM_PLANE_U] = frame->data[1];
490 rawimg->planes[AOM_PLANE_V] = frame->data[2];
491 rawimg->stride[AOM_PLANE_Y] = frame->linesize[0];
492 rawimg->stride[AOM_PLANE_U] = frame->linesize[1];
493 rawimg->stride[AOM_PLANE_V] = frame->linesize[2];
494 timestamp = frame->pts;
495 switch (frame->color_range) {
496 case AVCOL_RANGE_MPEG:
497 rawimg->range = AOM_CR_STUDIO_RANGE;
499 case AVCOL_RANGE_JPEG:
500 rawimg->range = AOM_CR_FULL_RANGE;
504 if (frame->pict_type == AV_PICTURE_TYPE_I)
505 flags |= AOM_EFLAG_FORCE_KF;
508 res = aom_codec_encode(&ctx->encoder, rawimg, timestamp,
509 avctx->ticks_per_frame, flags);
510 if (res != AOM_CODEC_OK) {
511 log_encoder_error(avctx, "Error encoding frame");
512 return AVERROR_INVALIDDATA;
514 coded_size = queue_frames(avctx, pkt);
516 if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
517 size_t b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
519 avctx->stats_out = av_malloc(b64_size);
520 if (!avctx->stats_out) {
521 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%zu bytes) failed\n",
523 return AVERROR(ENOMEM);
525 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
526 ctx->twopass_stats.sz);
529 *got_packet = !!coded_size;
533 #define OFFSET(x) offsetof(AOMContext, x)
534 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
535 static const AVOption options[] = {
536 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, INT_MIN, INT_MAX, VE},
537 { "auto-alt-ref", "Enable use of alternate reference "
538 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
539 { "lag-in-frames", "Number of frames to look ahead at for "
540 "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
541 { "error-resilience", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
542 { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
543 { "partitions", "The frame partitions are independently decodable "
544 "by the bool decoder, meaning that partitions can be decoded even "
545 "though earlier partitions have been lost. Note that intra predicition"
546 " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
547 { "crf", "Select the quality for constant quality mode", offsetof(AOMContext, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE },
548 { "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 },
549 { "drop-threshold", "Frame drop threshold", offsetof(AOMContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
550 { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE},
554 static const AVCodecDefault defaults[] = {
558 { "keyint_min", "-1" },
562 static const AVClass class_aom = {
563 .class_name = "libaom encoder",
564 .item_name = av_default_item_name,
566 .version = LIBAVUTIL_VERSION_INT,
569 AVCodec ff_libaom_av1_encoder = {
570 .name = "libaom-av1",
571 .long_name = NULL_IF_CONFIG_SMALL("libaom AV1"),
572 .type = AVMEDIA_TYPE_VIDEO,
573 .id = AV_CODEC_ID_AV1,
574 .priv_data_size = sizeof(AOMContext),
576 .encode2 = aom_encode,
578 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS | AV_CODEC_CAP_EXPERIMENTAL,
579 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
580 .priv_class = &class_aom,
581 .defaults = defaults,
582 .wrapper_name = "libaom",