You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

742 lines
27KB

  1. /*
  2. * Copyright (c) 2010, Google, Inc.
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * AV1 encoder support via libaom
  23. */
  24. #define AOM_DISABLE_CTRL_TYPECHECKS 1
  25. #include <aom/aom_encoder.h>
  26. #include <aom/aomcx.h>
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/base64.h"
  29. #include "libavutil/common.h"
  30. #include "libavutil/mathematics.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/pixdesc.h"
  33. #include "avcodec.h"
  34. #include "internal.h"
  35. #include "profiles.h"
  36. /*
  37. * Portion of struct aom_codec_cx_pkt from aom_encoder.h.
  38. * One encoded frame returned from the library.
  39. */
  40. struct FrameListData {
  41. void *buf; /**< compressed data buffer */
  42. size_t sz; /**< length of compressed data */
  43. int64_t pts; /**< time stamp to show frame
  44. (in timebase units) */
  45. unsigned long duration; /**< duration to show frame
  46. (in timebase units) */
  47. uint32_t flags; /**< flags for this frame */
  48. struct FrameListData *next;
  49. };
  50. typedef struct AOMEncoderContext {
  51. AVClass *class;
  52. struct aom_codec_ctx encoder;
  53. struct aom_image rawimg;
  54. struct aom_fixed_buf twopass_stats;
  55. struct FrameListData *coded_frame_list;
  56. int cpu_used;
  57. int auto_alt_ref;
  58. int lag_in_frames;
  59. int error_resilient;
  60. int crf;
  61. int static_thresh;
  62. int drop_threshold;
  63. int noise_sensitivity;
  64. } AOMContext;
  65. static const char *const ctlidstr[] = {
  66. [AOME_SET_CPUUSED] = "AOME_SET_CPUUSED",
  67. [AOME_SET_CQ_LEVEL] = "AOME_SET_CQ_LEVEL",
  68. [AOME_SET_ENABLEAUTOALTREF] = "AOME_SET_ENABLEAUTOALTREF",
  69. [AOME_SET_STATIC_THRESHOLD] = "AOME_SET_STATIC_THRESHOLD",
  70. [AV1E_SET_COLOR_RANGE] = "AV1E_SET_COLOR_RANGE",
  71. [AV1E_SET_COLOR_PRIMARIES] = "AV1E_SET_COLOR_PRIMARIES",
  72. [AV1E_SET_MATRIX_COEFFICIENTS] = "AV1E_SET_MATRIX_COEFFICIENTS",
  73. [AV1E_SET_TRANSFER_CHARACTERISTICS] = "AV1E_SET_TRANSFER_CHARACTERISTICS",
  74. };
  75. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  76. {
  77. AOMContext *ctx = avctx->priv_data;
  78. const char *error = aom_codec_error(&ctx->encoder);
  79. const char *detail = aom_codec_error_detail(&ctx->encoder);
  80. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  81. if (detail)
  82. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  83. }
  84. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  85. const struct aom_codec_enc_cfg *cfg)
  86. {
  87. int width = -30;
  88. int level = AV_LOG_DEBUG;
  89. av_log(avctx, level, "aom_codec_enc_cfg\n");
  90. av_log(avctx, level, "generic settings\n"
  91. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  92. " %*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_bit_depth:", cfg->g_bit_depth,
  100. width, "g_input_bit_depth:", cfg->g_input_bit_depth,
  101. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  102. width, "g_error_resilient:", cfg->g_error_resilient,
  103. width, "g_pass:", cfg->g_pass,
  104. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  105. av_log(avctx, level, "rate control settings\n"
  106. " %*s%u\n %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
  107. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  108. width, "rc_end_usage:", cfg->rc_end_usage,
  109. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  110. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  111. av_log(avctx, level, "quantizer settings\n"
  112. " %*s%u\n %*s%u\n",
  113. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  114. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  115. av_log(avctx, level, "bitrate tolerance\n"
  116. " %*s%u\n %*s%u\n",
  117. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  118. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  119. av_log(avctx, level, "decoder buffer model\n"
  120. " %*s%u\n %*s%u\n %*s%u\n",
  121. width, "rc_buf_sz:", cfg->rc_buf_sz,
  122. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  123. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  124. av_log(avctx, level, "2 pass rate control settings\n"
  125. " %*s%u\n %*s%u\n %*s%u\n",
  126. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  127. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  128. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  129. av_log(avctx, level, "keyframing settings\n"
  130. " %*s%d\n %*s%u\n %*s%u\n",
  131. width, "kf_mode:", cfg->kf_mode,
  132. width, "kf_min_dist:", cfg->kf_min_dist,
  133. width, "kf_max_dist:", cfg->kf_max_dist);
  134. av_log(avctx, level, "\n");
  135. }
  136. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  137. {
  138. struct FrameListData **p = list;
  139. while (*p)
  140. p = &(*p)->next;
  141. *p = cx_frame;
  142. cx_frame->next = NULL;
  143. }
  144. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  145. {
  146. av_freep(&cx_frame->buf);
  147. av_freep(&cx_frame);
  148. }
  149. static av_cold void free_frame_list(struct FrameListData *list)
  150. {
  151. struct FrameListData *p = list;
  152. while (p) {
  153. list = list->next;
  154. free_coded_frame(p);
  155. p = list;
  156. }
  157. }
  158. static av_cold int codecctl_int(AVCodecContext *avctx,
  159. enum aome_enc_control_id id, int val)
  160. {
  161. AOMContext *ctx = avctx->priv_data;
  162. char buf[80];
  163. int width = -30;
  164. int res;
  165. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  166. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  167. res = aom_codec_control(&ctx->encoder, id, val);
  168. if (res != AOM_CODEC_OK) {
  169. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  170. ctlidstr[id]);
  171. log_encoder_error(avctx, buf);
  172. return AVERROR(EINVAL);
  173. }
  174. return 0;
  175. }
  176. static av_cold int aom_free(AVCodecContext *avctx)
  177. {
  178. AOMContext *ctx = avctx->priv_data;
  179. aom_codec_destroy(&ctx->encoder);
  180. av_freep(&ctx->twopass_stats.buf);
  181. av_freep(&avctx->stats_out);
  182. free_frame_list(ctx->coded_frame_list);
  183. return 0;
  184. }
  185. static int set_pix_fmt(AVCodecContext *avctx, aom_codec_caps_t codec_caps,
  186. struct aom_codec_enc_cfg *enccfg, aom_codec_flags_t *flags,
  187. aom_img_fmt_t *img_fmt)
  188. {
  189. AOMContext av_unused *ctx = avctx->priv_data;
  190. enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
  191. switch (avctx->pix_fmt) {
  192. case AV_PIX_FMT_YUV420P:
  193. enccfg->g_profile = FF_PROFILE_AV1_MAIN;
  194. *img_fmt = AOM_IMG_FMT_I420;
  195. return 0;
  196. case AV_PIX_FMT_YUV422P:
  197. enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
  198. *img_fmt = AOM_IMG_FMT_I422;
  199. return 0;
  200. case AV_PIX_FMT_YUV444P:
  201. enccfg->g_profile = FF_PROFILE_AV1_HIGH;
  202. *img_fmt = AOM_IMG_FMT_I444;
  203. return 0;
  204. case AV_PIX_FMT_YUV420P10:
  205. case AV_PIX_FMT_YUV420P12:
  206. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  207. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  208. avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
  209. enccfg->g_profile =
  210. enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_MAIN : FF_PROFILE_AV1_PROFESSIONAL;
  211. *img_fmt = AOM_IMG_FMT_I42016;
  212. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  213. return 0;
  214. }
  215. break;
  216. case AV_PIX_FMT_YUV422P10:
  217. case AV_PIX_FMT_YUV422P12:
  218. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  219. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  220. avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
  221. enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
  222. *img_fmt = AOM_IMG_FMT_I42216;
  223. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  224. return 0;
  225. }
  226. break;
  227. case AV_PIX_FMT_YUV444P10:
  228. case AV_PIX_FMT_YUV444P12:
  229. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  230. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  231. avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ? 10 : 12;
  232. enccfg->g_profile =
  233. enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_HIGH : FF_PROFILE_AV1_PROFESSIONAL;
  234. *img_fmt = AOM_IMG_FMT_I44416;
  235. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  236. return 0;
  237. }
  238. break;
  239. default:
  240. break;
  241. }
  242. av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
  243. return AVERROR_INVALIDDATA;
  244. }
  245. static void set_color_range(AVCodecContext *avctx)
  246. {
  247. enum aom_color_range aom_cr;
  248. switch (avctx->color_range) {
  249. case AVCOL_RANGE_UNSPECIFIED:
  250. case AVCOL_RANGE_MPEG: aom_cr = AOM_CR_STUDIO_RANGE; break;
  251. case AVCOL_RANGE_JPEG: aom_cr = AOM_CR_FULL_RANGE; break;
  252. default:
  253. av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
  254. avctx->color_range);
  255. return;
  256. }
  257. codecctl_int(avctx, AV1E_SET_COLOR_RANGE, aom_cr);
  258. }
  259. static av_cold int aom_init(AVCodecContext *avctx,
  260. const struct aom_codec_iface *iface)
  261. {
  262. AOMContext *ctx = avctx->priv_data;
  263. struct aom_codec_enc_cfg enccfg = { 0 };
  264. aom_codec_flags_t flags = 0;
  265. AVCPBProperties *cpb_props;
  266. int res;
  267. aom_img_fmt_t img_fmt;
  268. aom_codec_caps_t codec_caps = aom_codec_get_caps(iface);
  269. av_log(avctx, AV_LOG_INFO, "%s\n", aom_codec_version_str());
  270. av_log(avctx, AV_LOG_VERBOSE, "%s\n", aom_codec_build_config());
  271. if ((res = aom_codec_enc_config_default(iface, &enccfg, 0)) != AOM_CODEC_OK) {
  272. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  273. aom_codec_err_to_string(res));
  274. return AVERROR(EINVAL);
  275. }
  276. if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
  277. return AVERROR(EINVAL);
  278. if(!avctx->bit_rate)
  279. if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  280. av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
  281. return AVERROR(EINVAL);
  282. }
  283. dump_enc_cfg(avctx, &enccfg);
  284. enccfg.g_w = avctx->width;
  285. enccfg.g_h = avctx->height;
  286. enccfg.g_timebase.num = avctx->time_base.num;
  287. enccfg.g_timebase.den = avctx->time_base.den;
  288. enccfg.g_threads = avctx->thread_count;
  289. if (ctx->lag_in_frames >= 0)
  290. enccfg.g_lag_in_frames = ctx->lag_in_frames;
  291. if (avctx->flags & AV_CODEC_FLAG_PASS1)
  292. enccfg.g_pass = AOM_RC_FIRST_PASS;
  293. else if (avctx->flags & AV_CODEC_FLAG_PASS2)
  294. enccfg.g_pass = AOM_RC_LAST_PASS;
  295. else
  296. enccfg.g_pass = AOM_RC_ONE_PASS;
  297. if (avctx->rc_min_rate == avctx->rc_max_rate &&
  298. avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
  299. enccfg.rc_end_usage = AOM_CBR;
  300. } else if (ctx->crf >= 0) {
  301. enccfg.rc_end_usage = AOM_CQ;
  302. if (!avctx->bit_rate)
  303. enccfg.rc_end_usage = AOM_Q;
  304. }
  305. if (avctx->bit_rate) {
  306. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  307. AV_ROUND_NEAR_INF);
  308. } else if (enccfg.rc_end_usage != AOM_Q) {
  309. if (enccfg.rc_end_usage == AOM_CQ) {
  310. enccfg.rc_target_bitrate = 1000000;
  311. } else {
  312. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  313. av_log(avctx, AV_LOG_WARNING,
  314. "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
  315. enccfg.rc_target_bitrate);
  316. }
  317. }
  318. if (avctx->qmin >= 0)
  319. enccfg.rc_min_quantizer = avctx->qmin;
  320. if (avctx->qmax >= 0)
  321. enccfg.rc_max_quantizer = avctx->qmax;
  322. if (enccfg.rc_end_usage == AOM_CQ || enccfg.rc_end_usage == AOM_Q) {
  323. if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
  324. av_log(avctx, AV_LOG_ERROR,
  325. "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
  326. ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
  327. return AVERROR(EINVAL);
  328. }
  329. }
  330. enccfg.rc_dropframe_thresh = ctx->drop_threshold;
  331. // 0-100 (0 => CBR, 100 => VBR)
  332. enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
  333. if (avctx->bit_rate)
  334. enccfg.rc_2pass_vbr_minsection_pct =
  335. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  336. if (avctx->rc_max_rate)
  337. enccfg.rc_2pass_vbr_maxsection_pct =
  338. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  339. if (avctx->rc_buffer_size)
  340. enccfg.rc_buf_sz =
  341. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  342. if (avctx->rc_initial_buffer_occupancy)
  343. enccfg.rc_buf_initial_sz =
  344. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  345. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  346. // _enc_init() will balk if kf_min_dist differs from max w/AOM_KF_AUTO
  347. if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
  348. enccfg.kf_min_dist = avctx->keyint_min;
  349. if (avctx->gop_size >= 0)
  350. enccfg.kf_max_dist = avctx->gop_size;
  351. if (enccfg.g_pass == AOM_RC_FIRST_PASS)
  352. enccfg.g_lag_in_frames = 0;
  353. else if (enccfg.g_pass == AOM_RC_LAST_PASS) {
  354. int decode_size, ret;
  355. if (!avctx->stats_in) {
  356. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  357. return AVERROR_INVALIDDATA;
  358. }
  359. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  360. ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
  361. if (ret < 0) {
  362. av_log(avctx, AV_LOG_ERROR,
  363. "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  364. ctx->twopass_stats.sz);
  365. ctx->twopass_stats.sz = 0;
  366. return ret;
  367. }
  368. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  369. ctx->twopass_stats.sz);
  370. if (decode_size < 0) {
  371. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  372. return AVERROR_INVALIDDATA;
  373. }
  374. ctx->twopass_stats.sz = decode_size;
  375. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  376. }
  377. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  378. * complexity playback on low powered devices at the expense of encode
  379. * quality. */
  380. if (avctx->profile != FF_PROFILE_UNKNOWN)
  381. enccfg.g_profile = avctx->profile;
  382. enccfg.g_error_resilient = ctx->error_resilient;
  383. dump_enc_cfg(avctx, &enccfg);
  384. /* Construct Encoder Context */
  385. res = aom_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
  386. if (res != AOM_CODEC_OK) {
  387. log_encoder_error(avctx, "Failed to initialize encoder");
  388. return AVERROR(EINVAL);
  389. }
  390. // codec control failures are currently treated only as warnings
  391. av_log(avctx, AV_LOG_DEBUG, "aom_codec_control\n");
  392. codecctl_int(avctx, AOME_SET_CPUUSED, ctx->cpu_used);
  393. if (ctx->auto_alt_ref >= 0)
  394. codecctl_int(avctx, AOME_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
  395. codecctl_int(avctx, AOME_SET_STATIC_THRESHOLD, ctx->static_thresh);
  396. if (ctx->crf >= 0)
  397. codecctl_int(avctx, AOME_SET_CQ_LEVEL, ctx->crf);
  398. codecctl_int(avctx, AV1E_SET_COLOR_PRIMARIES, avctx->color_primaries);
  399. codecctl_int(avctx, AV1E_SET_MATRIX_COEFFICIENTS, avctx->colorspace);
  400. codecctl_int(avctx, AV1E_SET_TRANSFER_CHARACTERISTICS, avctx->color_trc);
  401. set_color_range(avctx);
  402. // provide dummy value to initialize wrapper, values will be updated each _encode()
  403. aom_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
  404. (unsigned char*)1);
  405. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
  406. ctx->rawimg.bit_depth = enccfg.g_bit_depth;
  407. cpb_props = ff_add_cpb_side_data(avctx);
  408. if (!cpb_props)
  409. return AVERROR(ENOMEM);
  410. if (enccfg.rc_end_usage == AOM_CBR ||
  411. enccfg.g_pass != AOM_RC_ONE_PASS) {
  412. cpb_props->max_bitrate = avctx->rc_max_rate;
  413. cpb_props->min_bitrate = avctx->rc_min_rate;
  414. cpb_props->avg_bitrate = avctx->bit_rate;
  415. }
  416. cpb_props->buffer_size = avctx->rc_buffer_size;
  417. return 0;
  418. }
  419. static inline void cx_pktcpy(struct FrameListData *dst,
  420. const struct aom_codec_cx_pkt *src)
  421. {
  422. dst->pts = src->data.frame.pts;
  423. dst->duration = src->data.frame.duration;
  424. dst->flags = src->data.frame.flags;
  425. dst->sz = src->data.frame.sz;
  426. dst->buf = src->data.frame.buf;
  427. }
  428. /**
  429. * Store coded frame information in format suitable for return from encode2().
  430. *
  431. * Write information from @a cx_frame to @a pkt
  432. * @return packet data size on success
  433. * @return a negative AVERROR on error
  434. */
  435. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  436. AVPacket *pkt)
  437. {
  438. int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
  439. if (ret < 0) {
  440. av_log(avctx, AV_LOG_ERROR,
  441. "Error getting output packet of size %"SIZE_SPECIFIER".\n", cx_frame->sz);
  442. return ret;
  443. }
  444. memcpy(pkt->data, cx_frame->buf, pkt->size);
  445. pkt->pts = pkt->dts = cx_frame->pts;
  446. if (!!(cx_frame->flags & AOM_FRAME_IS_KEY))
  447. pkt->flags |= AV_PKT_FLAG_KEY;
  448. return pkt->size;
  449. }
  450. /**
  451. * Queue multiple output frames from the encoder, returning the front-most.
  452. * In cases where aom_codec_get_cx_data() returns more than 1 frame append
  453. * the frame queue. Return the head frame if available.
  454. * @return Stored frame size
  455. * @return AVERROR(EINVAL) on output size error
  456. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  457. */
  458. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
  459. {
  460. AOMContext *ctx = avctx->priv_data;
  461. const struct aom_codec_cx_pkt *pkt;
  462. const void *iter = NULL;
  463. int size = 0;
  464. if (ctx->coded_frame_list) {
  465. struct FrameListData *cx_frame = ctx->coded_frame_list;
  466. /* return the leading frame if we've already begun queueing */
  467. size = storeframe(avctx, cx_frame, pkt_out);
  468. if (size < 0)
  469. return size;
  470. ctx->coded_frame_list = cx_frame->next;
  471. free_coded_frame(cx_frame);
  472. }
  473. /* consume all available output from the encoder before returning. buffers
  474. * are only good through the next aom_codec call */
  475. while ((pkt = aom_codec_get_cx_data(&ctx->encoder, &iter))) {
  476. switch (pkt->kind) {
  477. case AOM_CODEC_CX_FRAME_PKT:
  478. if (!size) {
  479. struct FrameListData cx_frame;
  480. /* avoid storing the frame when the list is empty and we haven't yet
  481. * provided a frame for output */
  482. av_assert0(!ctx->coded_frame_list);
  483. cx_pktcpy(&cx_frame, pkt);
  484. size = storeframe(avctx, &cx_frame, pkt_out);
  485. if (size < 0)
  486. return size;
  487. } else {
  488. struct FrameListData *cx_frame =
  489. av_malloc(sizeof(struct FrameListData));
  490. if (!cx_frame) {
  491. av_log(avctx, AV_LOG_ERROR,
  492. "Frame queue element alloc failed\n");
  493. return AVERROR(ENOMEM);
  494. }
  495. cx_pktcpy(cx_frame, pkt);
  496. cx_frame->buf = av_malloc(cx_frame->sz);
  497. if (!cx_frame->buf) {
  498. av_log(avctx, AV_LOG_ERROR,
  499. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  500. cx_frame->sz);
  501. av_freep(&cx_frame);
  502. return AVERROR(ENOMEM);
  503. }
  504. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  505. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  506. }
  507. break;
  508. case AOM_CODEC_STATS_PKT:
  509. {
  510. struct aom_fixed_buf *stats = &ctx->twopass_stats;
  511. int err;
  512. if ((err = av_reallocp(&stats->buf,
  513. stats->sz +
  514. pkt->data.twopass_stats.sz)) < 0) {
  515. stats->sz = 0;
  516. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  517. return err;
  518. }
  519. memcpy((uint8_t *)stats->buf + stats->sz,
  520. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  521. stats->sz += pkt->data.twopass_stats.sz;
  522. break;
  523. }
  524. case AOM_CODEC_PSNR_PKT: // FIXME add support for AV_CODEC_FLAG_PSNR
  525. case AOM_CODEC_CUSTOM_PKT:
  526. // ignore unsupported/unrecognized packet types
  527. break;
  528. }
  529. }
  530. return size;
  531. }
  532. static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
  533. const AVFrame *frame, int *got_packet)
  534. {
  535. AOMContext *ctx = avctx->priv_data;
  536. struct aom_image *rawimg = NULL;
  537. int64_t timestamp = 0;
  538. int res, coded_size;
  539. aom_enc_frame_flags_t flags = 0;
  540. if (frame) {
  541. rawimg = &ctx->rawimg;
  542. rawimg->planes[AOM_PLANE_Y] = frame->data[0];
  543. rawimg->planes[AOM_PLANE_U] = frame->data[1];
  544. rawimg->planes[AOM_PLANE_V] = frame->data[2];
  545. rawimg->stride[AOM_PLANE_Y] = frame->linesize[0];
  546. rawimg->stride[AOM_PLANE_U] = frame->linesize[1];
  547. rawimg->stride[AOM_PLANE_V] = frame->linesize[2];
  548. timestamp = frame->pts;
  549. switch (frame->color_range) {
  550. case AVCOL_RANGE_MPEG:
  551. rawimg->range = AOM_CR_STUDIO_RANGE;
  552. break;
  553. case AVCOL_RANGE_JPEG:
  554. rawimg->range = AOM_CR_FULL_RANGE;
  555. break;
  556. }
  557. if (frame->pict_type == AV_PICTURE_TYPE_I)
  558. flags |= AOM_EFLAG_FORCE_KF;
  559. }
  560. res = aom_codec_encode(&ctx->encoder, rawimg, timestamp,
  561. avctx->ticks_per_frame, flags);
  562. if (res != AOM_CODEC_OK) {
  563. log_encoder_error(avctx, "Error encoding frame");
  564. return AVERROR_INVALIDDATA;
  565. }
  566. coded_size = queue_frames(avctx, pkt);
  567. if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
  568. size_t b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  569. avctx->stats_out = av_malloc(b64_size);
  570. if (!avctx->stats_out) {
  571. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  572. b64_size);
  573. return AVERROR(ENOMEM);
  574. }
  575. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  576. ctx->twopass_stats.sz);
  577. }
  578. *got_packet = !!coded_size;
  579. return 0;
  580. }
  581. static const enum AVPixelFormat av1_pix_fmts[] = {
  582. AV_PIX_FMT_YUV420P,
  583. AV_PIX_FMT_YUV422P,
  584. AV_PIX_FMT_YUV444P,
  585. AV_PIX_FMT_NONE
  586. };
  587. static const enum AVPixelFormat av1_pix_fmts_highbd[] = {
  588. AV_PIX_FMT_YUV420P,
  589. AV_PIX_FMT_YUV422P,
  590. AV_PIX_FMT_YUV444P,
  591. AV_PIX_FMT_YUV420P10,
  592. AV_PIX_FMT_YUV422P10,
  593. AV_PIX_FMT_YUV444P10,
  594. AV_PIX_FMT_YUV420P12,
  595. AV_PIX_FMT_YUV422P12,
  596. AV_PIX_FMT_YUV444P12,
  597. AV_PIX_FMT_NONE
  598. };
  599. static av_cold void av1_init_static(AVCodec *codec)
  600. {
  601. aom_codec_caps_t codec_caps = aom_codec_get_caps(aom_codec_av1_cx());
  602. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
  603. codec->pix_fmts = av1_pix_fmts_highbd;
  604. else
  605. codec->pix_fmts = av1_pix_fmts;
  606. }
  607. static av_cold int av1_init(AVCodecContext *avctx)
  608. {
  609. return aom_init(avctx, aom_codec_av1_cx());
  610. }
  611. #define OFFSET(x) offsetof(AOMContext, x)
  612. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  613. static const AVOption options[] = {
  614. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
  615. { "auto-alt-ref", "Enable use of alternate reference "
  616. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
  617. { "lag-in-frames", "Number of frames to look ahead at for "
  618. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  619. { "error-resilience", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
  620. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
  621. { "partitions", "The frame partitions are independently decodable "
  622. "by the bool decoder, meaning that partitions can be decoded even "
  623. "though earlier partitions have been lost. Note that intra predicition"
  624. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
  625. { "crf", "Select the quality for constant quality mode", offsetof(AOMContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE },
  626. { "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 },
  627. { "drop-threshold", "Frame drop threshold", offsetof(AOMContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
  628. { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE},
  629. { NULL }
  630. };
  631. static const AVCodecDefault defaults[] = {
  632. { "qmin", "-1" },
  633. { "qmax", "-1" },
  634. { "g", "-1" },
  635. { "keyint_min", "-1" },
  636. { NULL },
  637. };
  638. static const AVClass class_aom = {
  639. .class_name = "libaom-av1 encoder",
  640. .item_name = av_default_item_name,
  641. .option = options,
  642. .version = LIBAVUTIL_VERSION_INT,
  643. };
  644. AVCodec ff_libaom_av1_encoder = {
  645. .name = "libaom-av1",
  646. .long_name = NULL_IF_CONFIG_SMALL("libaom AV1"),
  647. .type = AVMEDIA_TYPE_VIDEO,
  648. .id = AV_CODEC_ID_AV1,
  649. .priv_data_size = sizeof(AOMContext),
  650. .init = av1_init,
  651. .encode2 = aom_encode,
  652. .close = aom_free,
  653. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS | AV_CODEC_CAP_EXPERIMENTAL,
  654. .profiles = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
  655. .priv_class = &class_aom,
  656. .defaults = defaults,
  657. .init_static_data = av1_init_static,
  658. .wrapper_name = "libaom",
  659. };