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.

750 lines
28KB

  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_GBRP:
  201. case AV_PIX_FMT_YUV444P:
  202. enccfg->g_profile = FF_PROFILE_AV1_HIGH;
  203. *img_fmt = AOM_IMG_FMT_I444;
  204. return 0;
  205. case AV_PIX_FMT_YUV420P10:
  206. case AV_PIX_FMT_YUV420P12:
  207. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  208. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  209. avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
  210. enccfg->g_profile =
  211. enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_MAIN : FF_PROFILE_AV1_PROFESSIONAL;
  212. *img_fmt = AOM_IMG_FMT_I42016;
  213. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  214. return 0;
  215. }
  216. break;
  217. case AV_PIX_FMT_YUV422P10:
  218. case AV_PIX_FMT_YUV422P12:
  219. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  220. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  221. avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
  222. enccfg->g_profile = FF_PROFILE_AV1_PROFESSIONAL;
  223. *img_fmt = AOM_IMG_FMT_I42216;
  224. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  225. return 0;
  226. }
  227. break;
  228. case AV_PIX_FMT_GBRP10:
  229. case AV_PIX_FMT_GBRP12:
  230. case AV_PIX_FMT_YUV444P10:
  231. case AV_PIX_FMT_YUV444P12:
  232. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH) {
  233. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  234. avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ||
  235. avctx->pix_fmt == AV_PIX_FMT_GBRP10 ? 10 : 12;
  236. enccfg->g_profile =
  237. enccfg->g_bit_depth == 10 ? FF_PROFILE_AV1_HIGH : FF_PROFILE_AV1_PROFESSIONAL;
  238. *img_fmt = AOM_IMG_FMT_I44416;
  239. *flags |= AOM_CODEC_USE_HIGHBITDEPTH;
  240. return 0;
  241. }
  242. break;
  243. default:
  244. break;
  245. }
  246. av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
  247. return AVERROR_INVALIDDATA;
  248. }
  249. static void set_color_range(AVCodecContext *avctx)
  250. {
  251. enum aom_color_range aom_cr;
  252. switch (avctx->color_range) {
  253. case AVCOL_RANGE_UNSPECIFIED:
  254. case AVCOL_RANGE_MPEG: aom_cr = AOM_CR_STUDIO_RANGE; break;
  255. case AVCOL_RANGE_JPEG: aom_cr = AOM_CR_FULL_RANGE; break;
  256. default:
  257. av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
  258. avctx->color_range);
  259. return;
  260. }
  261. codecctl_int(avctx, AV1E_SET_COLOR_RANGE, aom_cr);
  262. }
  263. static av_cold int aom_init(AVCodecContext *avctx,
  264. const struct aom_codec_iface *iface)
  265. {
  266. AOMContext *ctx = avctx->priv_data;
  267. struct aom_codec_enc_cfg enccfg = { 0 };
  268. aom_codec_flags_t flags = 0;
  269. AVCPBProperties *cpb_props;
  270. int res;
  271. aom_img_fmt_t img_fmt;
  272. aom_codec_caps_t codec_caps = aom_codec_get_caps(iface);
  273. av_log(avctx, AV_LOG_INFO, "%s\n", aom_codec_version_str());
  274. av_log(avctx, AV_LOG_VERBOSE, "%s\n", aom_codec_build_config());
  275. if ((res = aom_codec_enc_config_default(iface, &enccfg, 0)) != AOM_CODEC_OK) {
  276. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  277. aom_codec_err_to_string(res));
  278. return AVERROR(EINVAL);
  279. }
  280. if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
  281. return AVERROR(EINVAL);
  282. if(!avctx->bit_rate)
  283. if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  284. av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
  285. return AVERROR(EINVAL);
  286. }
  287. dump_enc_cfg(avctx, &enccfg);
  288. enccfg.g_w = avctx->width;
  289. enccfg.g_h = avctx->height;
  290. enccfg.g_timebase.num = avctx->time_base.num;
  291. enccfg.g_timebase.den = avctx->time_base.den;
  292. enccfg.g_threads = avctx->thread_count;
  293. if (ctx->lag_in_frames >= 0)
  294. enccfg.g_lag_in_frames = ctx->lag_in_frames;
  295. if (avctx->flags & AV_CODEC_FLAG_PASS1)
  296. enccfg.g_pass = AOM_RC_FIRST_PASS;
  297. else if (avctx->flags & AV_CODEC_FLAG_PASS2)
  298. enccfg.g_pass = AOM_RC_LAST_PASS;
  299. else
  300. enccfg.g_pass = AOM_RC_ONE_PASS;
  301. if (avctx->rc_min_rate == avctx->rc_max_rate &&
  302. avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
  303. enccfg.rc_end_usage = AOM_CBR;
  304. } else if (ctx->crf >= 0) {
  305. enccfg.rc_end_usage = AOM_CQ;
  306. if (!avctx->bit_rate)
  307. enccfg.rc_end_usage = AOM_Q;
  308. }
  309. if (avctx->bit_rate) {
  310. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  311. AV_ROUND_NEAR_INF);
  312. } else if (enccfg.rc_end_usage != AOM_Q) {
  313. if (enccfg.rc_end_usage == AOM_CQ) {
  314. enccfg.rc_target_bitrate = 1000000;
  315. } else {
  316. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  317. av_log(avctx, AV_LOG_WARNING,
  318. "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
  319. enccfg.rc_target_bitrate);
  320. }
  321. }
  322. if (avctx->qmin >= 0)
  323. enccfg.rc_min_quantizer = avctx->qmin;
  324. if (avctx->qmax >= 0)
  325. enccfg.rc_max_quantizer = avctx->qmax;
  326. if (enccfg.rc_end_usage == AOM_CQ || enccfg.rc_end_usage == AOM_Q) {
  327. if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
  328. av_log(avctx, AV_LOG_ERROR,
  329. "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
  330. ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
  331. return AVERROR(EINVAL);
  332. }
  333. }
  334. enccfg.rc_dropframe_thresh = ctx->drop_threshold;
  335. // 0-100 (0 => CBR, 100 => VBR)
  336. enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
  337. if (avctx->bit_rate)
  338. enccfg.rc_2pass_vbr_minsection_pct =
  339. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  340. if (avctx->rc_max_rate)
  341. enccfg.rc_2pass_vbr_maxsection_pct =
  342. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  343. if (avctx->rc_buffer_size)
  344. enccfg.rc_buf_sz =
  345. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  346. if (avctx->rc_initial_buffer_occupancy)
  347. enccfg.rc_buf_initial_sz =
  348. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  349. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  350. // _enc_init() will balk if kf_min_dist differs from max w/AOM_KF_AUTO
  351. if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
  352. enccfg.kf_min_dist = avctx->keyint_min;
  353. if (avctx->gop_size >= 0)
  354. enccfg.kf_max_dist = avctx->gop_size;
  355. if (enccfg.g_pass == AOM_RC_FIRST_PASS)
  356. enccfg.g_lag_in_frames = 0;
  357. else if (enccfg.g_pass == AOM_RC_LAST_PASS) {
  358. int decode_size, ret;
  359. if (!avctx->stats_in) {
  360. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  361. return AVERROR_INVALIDDATA;
  362. }
  363. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  364. ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
  365. if (ret < 0) {
  366. av_log(avctx, AV_LOG_ERROR,
  367. "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  368. ctx->twopass_stats.sz);
  369. ctx->twopass_stats.sz = 0;
  370. return ret;
  371. }
  372. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  373. ctx->twopass_stats.sz);
  374. if (decode_size < 0) {
  375. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  376. return AVERROR_INVALIDDATA;
  377. }
  378. ctx->twopass_stats.sz = decode_size;
  379. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  380. }
  381. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  382. * complexity playback on low powered devices at the expense of encode
  383. * quality. */
  384. if (avctx->profile != FF_PROFILE_UNKNOWN)
  385. enccfg.g_profile = avctx->profile;
  386. enccfg.g_error_resilient = ctx->error_resilient;
  387. dump_enc_cfg(avctx, &enccfg);
  388. /* Construct Encoder Context */
  389. res = aom_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
  390. if (res != AOM_CODEC_OK) {
  391. log_encoder_error(avctx, "Failed to initialize encoder");
  392. return AVERROR(EINVAL);
  393. }
  394. // codec control failures are currently treated only as warnings
  395. av_log(avctx, AV_LOG_DEBUG, "aom_codec_control\n");
  396. codecctl_int(avctx, AOME_SET_CPUUSED, ctx->cpu_used);
  397. if (ctx->auto_alt_ref >= 0)
  398. codecctl_int(avctx, AOME_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
  399. codecctl_int(avctx, AOME_SET_STATIC_THRESHOLD, ctx->static_thresh);
  400. if (ctx->crf >= 0)
  401. codecctl_int(avctx, AOME_SET_CQ_LEVEL, ctx->crf);
  402. codecctl_int(avctx, AV1E_SET_COLOR_PRIMARIES, avctx->color_primaries);
  403. codecctl_int(avctx, AV1E_SET_MATRIX_COEFFICIENTS, avctx->colorspace);
  404. codecctl_int(avctx, AV1E_SET_TRANSFER_CHARACTERISTICS, avctx->color_trc);
  405. set_color_range(avctx);
  406. // provide dummy value to initialize wrapper, values will be updated each _encode()
  407. aom_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
  408. (unsigned char*)1);
  409. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
  410. ctx->rawimg.bit_depth = enccfg.g_bit_depth;
  411. cpb_props = ff_add_cpb_side_data(avctx);
  412. if (!cpb_props)
  413. return AVERROR(ENOMEM);
  414. if (enccfg.rc_end_usage == AOM_CBR ||
  415. enccfg.g_pass != AOM_RC_ONE_PASS) {
  416. cpb_props->max_bitrate = avctx->rc_max_rate;
  417. cpb_props->min_bitrate = avctx->rc_min_rate;
  418. cpb_props->avg_bitrate = avctx->bit_rate;
  419. }
  420. cpb_props->buffer_size = avctx->rc_buffer_size;
  421. return 0;
  422. }
  423. static inline void cx_pktcpy(struct FrameListData *dst,
  424. const struct aom_codec_cx_pkt *src)
  425. {
  426. dst->pts = src->data.frame.pts;
  427. dst->duration = src->data.frame.duration;
  428. dst->flags = src->data.frame.flags;
  429. dst->sz = src->data.frame.sz;
  430. dst->buf = src->data.frame.buf;
  431. }
  432. /**
  433. * Store coded frame information in format suitable for return from encode2().
  434. *
  435. * Write information from @a cx_frame to @a pkt
  436. * @return packet data size on success
  437. * @return a negative AVERROR on error
  438. */
  439. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  440. AVPacket *pkt)
  441. {
  442. int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
  443. if (ret < 0) {
  444. av_log(avctx, AV_LOG_ERROR,
  445. "Error getting output packet of size %"SIZE_SPECIFIER".\n", cx_frame->sz);
  446. return ret;
  447. }
  448. memcpy(pkt->data, cx_frame->buf, pkt->size);
  449. pkt->pts = pkt->dts = cx_frame->pts;
  450. if (!!(cx_frame->flags & AOM_FRAME_IS_KEY))
  451. pkt->flags |= AV_PKT_FLAG_KEY;
  452. return pkt->size;
  453. }
  454. /**
  455. * Queue multiple output frames from the encoder, returning the front-most.
  456. * In cases where aom_codec_get_cx_data() returns more than 1 frame append
  457. * the frame queue. Return the head frame if available.
  458. * @return Stored frame size
  459. * @return AVERROR(EINVAL) on output size error
  460. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  461. */
  462. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
  463. {
  464. AOMContext *ctx = avctx->priv_data;
  465. const struct aom_codec_cx_pkt *pkt;
  466. const void *iter = NULL;
  467. int size = 0;
  468. if (ctx->coded_frame_list) {
  469. struct FrameListData *cx_frame = ctx->coded_frame_list;
  470. /* return the leading frame if we've already begun queueing */
  471. size = storeframe(avctx, cx_frame, pkt_out);
  472. if (size < 0)
  473. return size;
  474. ctx->coded_frame_list = cx_frame->next;
  475. free_coded_frame(cx_frame);
  476. }
  477. /* consume all available output from the encoder before returning. buffers
  478. * are only good through the next aom_codec call */
  479. while ((pkt = aom_codec_get_cx_data(&ctx->encoder, &iter))) {
  480. switch (pkt->kind) {
  481. case AOM_CODEC_CX_FRAME_PKT:
  482. if (!size) {
  483. struct FrameListData cx_frame;
  484. /* avoid storing the frame when the list is empty and we haven't yet
  485. * provided a frame for output */
  486. av_assert0(!ctx->coded_frame_list);
  487. cx_pktcpy(&cx_frame, pkt);
  488. size = storeframe(avctx, &cx_frame, pkt_out);
  489. if (size < 0)
  490. return size;
  491. } else {
  492. struct FrameListData *cx_frame =
  493. av_malloc(sizeof(struct FrameListData));
  494. if (!cx_frame) {
  495. av_log(avctx, AV_LOG_ERROR,
  496. "Frame queue element alloc failed\n");
  497. return AVERROR(ENOMEM);
  498. }
  499. cx_pktcpy(cx_frame, pkt);
  500. cx_frame->buf = av_malloc(cx_frame->sz);
  501. if (!cx_frame->buf) {
  502. av_log(avctx, AV_LOG_ERROR,
  503. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  504. cx_frame->sz);
  505. av_freep(&cx_frame);
  506. return AVERROR(ENOMEM);
  507. }
  508. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  509. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  510. }
  511. break;
  512. case AOM_CODEC_STATS_PKT:
  513. {
  514. struct aom_fixed_buf *stats = &ctx->twopass_stats;
  515. int err;
  516. if ((err = av_reallocp(&stats->buf,
  517. stats->sz +
  518. pkt->data.twopass_stats.sz)) < 0) {
  519. stats->sz = 0;
  520. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  521. return err;
  522. }
  523. memcpy((uint8_t *)stats->buf + stats->sz,
  524. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  525. stats->sz += pkt->data.twopass_stats.sz;
  526. break;
  527. }
  528. case AOM_CODEC_PSNR_PKT: // FIXME add support for AV_CODEC_FLAG_PSNR
  529. case AOM_CODEC_CUSTOM_PKT:
  530. // ignore unsupported/unrecognized packet types
  531. break;
  532. }
  533. }
  534. return size;
  535. }
  536. static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
  537. const AVFrame *frame, int *got_packet)
  538. {
  539. AOMContext *ctx = avctx->priv_data;
  540. struct aom_image *rawimg = NULL;
  541. int64_t timestamp = 0;
  542. int res, coded_size;
  543. aom_enc_frame_flags_t flags = 0;
  544. if (frame) {
  545. rawimg = &ctx->rawimg;
  546. rawimg->planes[AOM_PLANE_Y] = frame->data[0];
  547. rawimg->planes[AOM_PLANE_U] = frame->data[1];
  548. rawimg->planes[AOM_PLANE_V] = frame->data[2];
  549. rawimg->stride[AOM_PLANE_Y] = frame->linesize[0];
  550. rawimg->stride[AOM_PLANE_U] = frame->linesize[1];
  551. rawimg->stride[AOM_PLANE_V] = frame->linesize[2];
  552. timestamp = frame->pts;
  553. switch (frame->color_range) {
  554. case AVCOL_RANGE_MPEG:
  555. rawimg->range = AOM_CR_STUDIO_RANGE;
  556. break;
  557. case AVCOL_RANGE_JPEG:
  558. rawimg->range = AOM_CR_FULL_RANGE;
  559. break;
  560. }
  561. if (frame->pict_type == AV_PICTURE_TYPE_I)
  562. flags |= AOM_EFLAG_FORCE_KF;
  563. }
  564. res = aom_codec_encode(&ctx->encoder, rawimg, timestamp,
  565. avctx->ticks_per_frame, flags);
  566. if (res != AOM_CODEC_OK) {
  567. log_encoder_error(avctx, "Error encoding frame");
  568. return AVERROR_INVALIDDATA;
  569. }
  570. coded_size = queue_frames(avctx, pkt);
  571. if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
  572. size_t b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  573. avctx->stats_out = av_malloc(b64_size);
  574. if (!avctx->stats_out) {
  575. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  576. b64_size);
  577. return AVERROR(ENOMEM);
  578. }
  579. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  580. ctx->twopass_stats.sz);
  581. }
  582. *got_packet = !!coded_size;
  583. return 0;
  584. }
  585. static const enum AVPixelFormat av1_pix_fmts[] = {
  586. AV_PIX_FMT_YUV420P,
  587. AV_PIX_FMT_YUV422P,
  588. AV_PIX_FMT_YUV444P,
  589. AV_PIX_FMT_GBRP,
  590. AV_PIX_FMT_NONE
  591. };
  592. static const enum AVPixelFormat av1_pix_fmts_highbd[] = {
  593. AV_PIX_FMT_YUV420P,
  594. AV_PIX_FMT_YUV422P,
  595. AV_PIX_FMT_YUV444P,
  596. AV_PIX_FMT_YUV420P10,
  597. AV_PIX_FMT_YUV422P10,
  598. AV_PIX_FMT_YUV444P10,
  599. AV_PIX_FMT_YUV420P12,
  600. AV_PIX_FMT_YUV422P12,
  601. AV_PIX_FMT_YUV444P12,
  602. AV_PIX_FMT_GBRP,
  603. AV_PIX_FMT_GBRP10,
  604. AV_PIX_FMT_GBRP12,
  605. AV_PIX_FMT_NONE
  606. };
  607. static av_cold void av1_init_static(AVCodec *codec)
  608. {
  609. aom_codec_caps_t codec_caps = aom_codec_get_caps(aom_codec_av1_cx());
  610. if (codec_caps & AOM_CODEC_CAP_HIGHBITDEPTH)
  611. codec->pix_fmts = av1_pix_fmts_highbd;
  612. else
  613. codec->pix_fmts = av1_pix_fmts;
  614. }
  615. static av_cold int av1_init(AVCodecContext *avctx)
  616. {
  617. return aom_init(avctx, aom_codec_av1_cx());
  618. }
  619. #define OFFSET(x) offsetof(AOMContext, x)
  620. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  621. static const AVOption options[] = {
  622. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
  623. { "auto-alt-ref", "Enable use of alternate reference "
  624. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
  625. { "lag-in-frames", "Number of frames to look ahead at for "
  626. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  627. { "error-resilience", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
  628. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
  629. { "partitions", "The frame partitions are independently decodable "
  630. "by the bool decoder, meaning that partitions can be decoded even "
  631. "though earlier partitions have been lost. Note that intra predicition"
  632. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = AOM_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
  633. { "crf", "Select the quality for constant quality mode", offsetof(AOMContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE },
  634. { "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 },
  635. { "drop-threshold", "Frame drop threshold", offsetof(AOMContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
  636. { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE},
  637. { NULL }
  638. };
  639. static const AVCodecDefault defaults[] = {
  640. { "qmin", "-1" },
  641. { "qmax", "-1" },
  642. { "g", "-1" },
  643. { "keyint_min", "-1" },
  644. { NULL },
  645. };
  646. static const AVClass class_aom = {
  647. .class_name = "libaom-av1 encoder",
  648. .item_name = av_default_item_name,
  649. .option = options,
  650. .version = LIBAVUTIL_VERSION_INT,
  651. };
  652. AVCodec ff_libaom_av1_encoder = {
  653. .name = "libaom-av1",
  654. .long_name = NULL_IF_CONFIG_SMALL("libaom AV1"),
  655. .type = AVMEDIA_TYPE_VIDEO,
  656. .id = AV_CODEC_ID_AV1,
  657. .priv_data_size = sizeof(AOMContext),
  658. .init = av1_init,
  659. .encode2 = aom_encode,
  660. .close = aom_free,
  661. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS | AV_CODEC_CAP_EXPERIMENTAL,
  662. .profiles = NULL_IF_CONFIG_SMALL(ff_av1_profiles),
  663. .priv_class = &class_aom,
  664. .defaults = defaults,
  665. .init_static_data = av1_init_static,
  666. .wrapper_name = "libaom",
  667. };