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.

1247 lines
49KB

  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. * VP8/9 encoder support via libvpx
  23. */
  24. #define VPX_DISABLE_CTRL_TYPECHECKS 1
  25. #define VPX_CODEC_DISABLE_COMPAT 1
  26. #include <vpx/vpx_encoder.h>
  27. #include <vpx/vp8cx.h>
  28. #include "avcodec.h"
  29. #include "internal.h"
  30. #include "libavutil/avassert.h"
  31. #include "libvpx.h"
  32. #include "profiles.h"
  33. #include "libavutil/base64.h"
  34. #include "libavutil/common.h"
  35. #include "libavutil/internal.h"
  36. #include "libavutil/intreadwrite.h"
  37. #include "libavutil/mathematics.h"
  38. #include "libavutil/opt.h"
  39. /**
  40. * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
  41. * One encoded frame returned from the library.
  42. */
  43. struct FrameListData {
  44. void *buf; /**< compressed data buffer */
  45. size_t sz; /**< length of compressed data */
  46. void *buf_alpha;
  47. size_t sz_alpha;
  48. int64_t pts; /**< time stamp to show frame
  49. (in timebase units) */
  50. unsigned long duration; /**< duration to show frame
  51. (in timebase units) */
  52. uint32_t flags; /**< flags for this frame */
  53. uint64_t sse[4];
  54. int have_sse; /**< true if we have pending sse[] */
  55. uint64_t frame_number;
  56. struct FrameListData *next;
  57. };
  58. typedef struct VPxEncoderContext {
  59. AVClass *class;
  60. struct vpx_codec_ctx encoder;
  61. struct vpx_image rawimg;
  62. struct vpx_codec_ctx encoder_alpha;
  63. struct vpx_image rawimg_alpha;
  64. uint8_t is_alpha;
  65. struct vpx_fixed_buf twopass_stats;
  66. int deadline; //i.e., RT/GOOD/BEST
  67. uint64_t sse[4];
  68. int have_sse; /**< true if we have pending sse[] */
  69. uint64_t frame_number;
  70. struct FrameListData *coded_frame_list;
  71. int cpu_used;
  72. /**
  73. * VP8 specific flags, see VP8F_* below.
  74. */
  75. int flags;
  76. #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
  77. #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
  78. int auto_alt_ref;
  79. int arnr_max_frames;
  80. int arnr_strength;
  81. int arnr_type;
  82. int tune;
  83. int lag_in_frames;
  84. int error_resilient;
  85. int crf;
  86. int static_thresh;
  87. int max_intra_rate;
  88. int rc_undershoot_pct;
  89. int rc_overshoot_pct;
  90. // VP9-only
  91. int lossless;
  92. int tile_columns;
  93. int tile_rows;
  94. int frame_parallel;
  95. int aq_mode;
  96. int drop_threshold;
  97. int noise_sensitivity;
  98. int vpx_cs;
  99. float level;
  100. int row_mt;
  101. int tune_content;
  102. int corpus_complexity;
  103. int tpl_model;
  104. } VPxContext;
  105. /** String mappings for enum vp8e_enc_control_id */
  106. static const char *const ctlidstr[] = {
  107. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  108. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  109. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  110. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  111. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  112. [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
  113. [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
  114. [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
  115. [VP8E_SET_TUNING] = "VP8E_SET_TUNING",
  116. [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
  117. [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
  118. #if CONFIG_LIBVPX_VP9_ENCODER
  119. [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
  120. [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
  121. [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
  122. [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
  123. [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
  124. [VP9E_SET_COLOR_SPACE] = "VP9E_SET_COLOR_SPACE",
  125. #if VPX_ENCODER_ABI_VERSION >= 11
  126. [VP9E_SET_COLOR_RANGE] = "VP9E_SET_COLOR_RANGE",
  127. #endif
  128. #if VPX_ENCODER_ABI_VERSION >= 12
  129. [VP9E_SET_TARGET_LEVEL] = "VP9E_SET_TARGET_LEVEL",
  130. [VP9E_GET_LEVEL] = "VP9E_GET_LEVEL",
  131. #endif
  132. #ifdef VPX_CTRL_VP9E_SET_ROW_MT
  133. [VP9E_SET_ROW_MT] = "VP9E_SET_ROW_MT",
  134. #endif
  135. #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
  136. [VP9E_SET_TUNE_CONTENT] = "VP9E_SET_TUNE_CONTENT",
  137. #endif
  138. #ifdef VPX_CTRL_VP9E_SET_TPL
  139. [VP9E_SET_TPL] = "VP9E_SET_TPL",
  140. #endif
  141. #endif
  142. };
  143. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  144. {
  145. VPxContext *ctx = avctx->priv_data;
  146. const char *error = vpx_codec_error(&ctx->encoder);
  147. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  148. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  149. if (detail)
  150. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  151. }
  152. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  153. const struct vpx_codec_enc_cfg *cfg)
  154. {
  155. int width = -30;
  156. int level = AV_LOG_DEBUG;
  157. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  158. av_log(avctx, level, "generic settings\n"
  159. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  160. #if CONFIG_LIBVPX_VP9_ENCODER
  161. " %*s%u\n %*s%u\n"
  162. #endif
  163. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  164. width, "g_usage:", cfg->g_usage,
  165. width, "g_threads:", cfg->g_threads,
  166. width, "g_profile:", cfg->g_profile,
  167. width, "g_w:", cfg->g_w,
  168. width, "g_h:", cfg->g_h,
  169. #if CONFIG_LIBVPX_VP9_ENCODER
  170. width, "g_bit_depth:", cfg->g_bit_depth,
  171. width, "g_input_bit_depth:", cfg->g_input_bit_depth,
  172. #endif
  173. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  174. width, "g_error_resilient:", cfg->g_error_resilient,
  175. width, "g_pass:", cfg->g_pass,
  176. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  177. av_log(avctx, level, "rate control settings\n"
  178. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  179. " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
  180. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  181. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  182. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  183. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  184. width, "rc_end_usage:", cfg->rc_end_usage,
  185. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  186. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  187. av_log(avctx, level, "quantizer settings\n"
  188. " %*s%u\n %*s%u\n",
  189. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  190. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  191. av_log(avctx, level, "bitrate tolerance\n"
  192. " %*s%u\n %*s%u\n",
  193. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  194. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  195. av_log(avctx, level, "decoder buffer model\n"
  196. " %*s%u\n %*s%u\n %*s%u\n",
  197. width, "rc_buf_sz:", cfg->rc_buf_sz,
  198. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  199. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  200. av_log(avctx, level, "2 pass rate control settings\n"
  201. " %*s%u\n %*s%u\n %*s%u\n",
  202. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  203. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  204. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  205. #if VPX_ENCODER_ABI_VERSION >= 14
  206. av_log(avctx, level, " %*s%u\n",
  207. width, "rc_2pass_vbr_corpus_complexity:", cfg->rc_2pass_vbr_corpus_complexity);
  208. #endif
  209. av_log(avctx, level, "keyframing settings\n"
  210. " %*s%d\n %*s%u\n %*s%u\n",
  211. width, "kf_mode:", cfg->kf_mode,
  212. width, "kf_min_dist:", cfg->kf_min_dist,
  213. width, "kf_max_dist:", cfg->kf_max_dist);
  214. av_log(avctx, level, "\n");
  215. }
  216. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  217. {
  218. struct FrameListData **p = list;
  219. while (*p)
  220. p = &(*p)->next;
  221. *p = cx_frame;
  222. cx_frame->next = NULL;
  223. }
  224. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  225. {
  226. av_freep(&cx_frame->buf);
  227. if (cx_frame->buf_alpha)
  228. av_freep(&cx_frame->buf_alpha);
  229. av_freep(&cx_frame);
  230. }
  231. static av_cold void free_frame_list(struct FrameListData *list)
  232. {
  233. struct FrameListData *p = list;
  234. while (p) {
  235. list = list->next;
  236. free_coded_frame(p);
  237. p = list;
  238. }
  239. }
  240. static av_cold int codecctl_int(AVCodecContext *avctx,
  241. enum vp8e_enc_control_id id, int val)
  242. {
  243. VPxContext *ctx = avctx->priv_data;
  244. char buf[80];
  245. int width = -30;
  246. int res;
  247. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  248. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  249. res = vpx_codec_control(&ctx->encoder, id, val);
  250. if (res != VPX_CODEC_OK) {
  251. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  252. ctlidstr[id]);
  253. log_encoder_error(avctx, buf);
  254. }
  255. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  256. }
  257. #if VPX_ENCODER_ABI_VERSION >= 12
  258. static av_cold int codecctl_intp(AVCodecContext *avctx,
  259. enum vp8e_enc_control_id id, int *val)
  260. {
  261. VPxContext *ctx = avctx->priv_data;
  262. char buf[80];
  263. int width = -30;
  264. int res;
  265. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  266. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, *val);
  267. res = vpx_codec_control(&ctx->encoder, id, val);
  268. if (res != VPX_CODEC_OK) {
  269. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  270. ctlidstr[id]);
  271. log_encoder_error(avctx, buf);
  272. }
  273. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  274. }
  275. #endif
  276. static av_cold int vpx_free(AVCodecContext *avctx)
  277. {
  278. VPxContext *ctx = avctx->priv_data;
  279. #if VPX_ENCODER_ABI_VERSION >= 12
  280. if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->level >= 0 &&
  281. !(avctx->flags & AV_CODEC_FLAG_PASS1)) {
  282. int level_out = 0;
  283. if (!codecctl_intp(avctx, VP9E_GET_LEVEL, &level_out))
  284. av_log(avctx, AV_LOG_INFO, "Encoded level %.1f\n", level_out * 0.1);
  285. }
  286. #endif
  287. vpx_codec_destroy(&ctx->encoder);
  288. if (ctx->is_alpha)
  289. vpx_codec_destroy(&ctx->encoder_alpha);
  290. av_freep(&ctx->twopass_stats.buf);
  291. av_freep(&avctx->stats_out);
  292. free_frame_list(ctx->coded_frame_list);
  293. return 0;
  294. }
  295. #if CONFIG_LIBVPX_VP9_ENCODER
  296. static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
  297. struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
  298. vpx_img_fmt_t *img_fmt)
  299. {
  300. VPxContext av_unused *ctx = avctx->priv_data;
  301. enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
  302. switch (avctx->pix_fmt) {
  303. case AV_PIX_FMT_YUV420P:
  304. case AV_PIX_FMT_YUVA420P:
  305. enccfg->g_profile = 0;
  306. *img_fmt = VPX_IMG_FMT_I420;
  307. return 0;
  308. case AV_PIX_FMT_YUV422P:
  309. enccfg->g_profile = 1;
  310. *img_fmt = VPX_IMG_FMT_I422;
  311. return 0;
  312. case AV_PIX_FMT_YUV440P:
  313. enccfg->g_profile = 1;
  314. *img_fmt = VPX_IMG_FMT_I440;
  315. return 0;
  316. case AV_PIX_FMT_GBRP:
  317. ctx->vpx_cs = VPX_CS_SRGB;
  318. case AV_PIX_FMT_YUV444P:
  319. enccfg->g_profile = 1;
  320. *img_fmt = VPX_IMG_FMT_I444;
  321. return 0;
  322. case AV_PIX_FMT_YUV420P10:
  323. case AV_PIX_FMT_YUV420P12:
  324. if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
  325. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  326. avctx->pix_fmt == AV_PIX_FMT_YUV420P10 ? 10 : 12;
  327. enccfg->g_profile = 2;
  328. *img_fmt = VPX_IMG_FMT_I42016;
  329. *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
  330. return 0;
  331. }
  332. break;
  333. case AV_PIX_FMT_YUV422P10:
  334. case AV_PIX_FMT_YUV422P12:
  335. if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
  336. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  337. avctx->pix_fmt == AV_PIX_FMT_YUV422P10 ? 10 : 12;
  338. enccfg->g_profile = 3;
  339. *img_fmt = VPX_IMG_FMT_I42216;
  340. *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
  341. return 0;
  342. }
  343. break;
  344. case AV_PIX_FMT_YUV440P10:
  345. case AV_PIX_FMT_YUV440P12:
  346. if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
  347. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  348. avctx->pix_fmt == AV_PIX_FMT_YUV440P10 ? 10 : 12;
  349. enccfg->g_profile = 3;
  350. *img_fmt = VPX_IMG_FMT_I44016;
  351. *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
  352. return 0;
  353. }
  354. break;
  355. case AV_PIX_FMT_GBRP10:
  356. case AV_PIX_FMT_GBRP12:
  357. ctx->vpx_cs = VPX_CS_SRGB;
  358. case AV_PIX_FMT_YUV444P10:
  359. case AV_PIX_FMT_YUV444P12:
  360. if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
  361. enccfg->g_bit_depth = enccfg->g_input_bit_depth =
  362. avctx->pix_fmt == AV_PIX_FMT_YUV444P10 ||
  363. avctx->pix_fmt == AV_PIX_FMT_GBRP10 ? 10 : 12;
  364. enccfg->g_profile = 3;
  365. *img_fmt = VPX_IMG_FMT_I44416;
  366. *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
  367. return 0;
  368. }
  369. break;
  370. default:
  371. break;
  372. }
  373. av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
  374. return AVERROR_INVALIDDATA;
  375. }
  376. static void set_colorspace(AVCodecContext *avctx)
  377. {
  378. enum vpx_color_space vpx_cs;
  379. VPxContext *ctx = avctx->priv_data;
  380. if (ctx->vpx_cs) {
  381. vpx_cs = ctx->vpx_cs;
  382. } else {
  383. switch (avctx->colorspace) {
  384. case AVCOL_SPC_RGB: vpx_cs = VPX_CS_SRGB; break;
  385. case AVCOL_SPC_BT709: vpx_cs = VPX_CS_BT_709; break;
  386. case AVCOL_SPC_UNSPECIFIED: vpx_cs = VPX_CS_UNKNOWN; break;
  387. case AVCOL_SPC_RESERVED: vpx_cs = VPX_CS_RESERVED; break;
  388. case AVCOL_SPC_BT470BG: vpx_cs = VPX_CS_BT_601; break;
  389. case AVCOL_SPC_SMPTE170M: vpx_cs = VPX_CS_SMPTE_170; break;
  390. case AVCOL_SPC_SMPTE240M: vpx_cs = VPX_CS_SMPTE_240; break;
  391. case AVCOL_SPC_BT2020_NCL: vpx_cs = VPX_CS_BT_2020; break;
  392. default:
  393. av_log(avctx, AV_LOG_WARNING, "Unsupported colorspace (%d)\n",
  394. avctx->colorspace);
  395. return;
  396. }
  397. }
  398. codecctl_int(avctx, VP9E_SET_COLOR_SPACE, vpx_cs);
  399. }
  400. #if VPX_ENCODER_ABI_VERSION >= 11
  401. static void set_color_range(AVCodecContext *avctx)
  402. {
  403. enum vpx_color_range vpx_cr;
  404. switch (avctx->color_range) {
  405. case AVCOL_RANGE_UNSPECIFIED:
  406. case AVCOL_RANGE_MPEG: vpx_cr = VPX_CR_STUDIO_RANGE; break;
  407. case AVCOL_RANGE_JPEG: vpx_cr = VPX_CR_FULL_RANGE; break;
  408. default:
  409. av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
  410. avctx->color_range);
  411. return;
  412. }
  413. codecctl_int(avctx, VP9E_SET_COLOR_RANGE, vpx_cr);
  414. }
  415. #endif
  416. #endif
  417. static av_cold int vpx_init(AVCodecContext *avctx,
  418. const struct vpx_codec_iface *iface)
  419. {
  420. VPxContext *ctx = avctx->priv_data;
  421. struct vpx_codec_enc_cfg enccfg = { 0 };
  422. struct vpx_codec_enc_cfg enccfg_alpha;
  423. vpx_codec_flags_t flags = (avctx->flags & AV_CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
  424. AVCPBProperties *cpb_props;
  425. int res;
  426. vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
  427. #if CONFIG_LIBVPX_VP9_ENCODER
  428. vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
  429. #endif
  430. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  431. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  432. if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
  433. ctx->is_alpha = 1;
  434. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  435. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  436. vpx_codec_err_to_string(res));
  437. return AVERROR(EINVAL);
  438. }
  439. #if CONFIG_LIBVPX_VP9_ENCODER
  440. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  441. if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
  442. return AVERROR(EINVAL);
  443. }
  444. #endif
  445. if(!avctx->bit_rate)
  446. if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  447. av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
  448. return AVERROR(EINVAL);
  449. }
  450. dump_enc_cfg(avctx, &enccfg);
  451. enccfg.g_w = avctx->width;
  452. enccfg.g_h = avctx->height;
  453. enccfg.g_timebase.num = avctx->time_base.num;
  454. enccfg.g_timebase.den = avctx->time_base.den;
  455. enccfg.g_threads = avctx->thread_count ? avctx->thread_count : av_cpu_count();
  456. enccfg.g_lag_in_frames= ctx->lag_in_frames;
  457. if (avctx->flags & AV_CODEC_FLAG_PASS1)
  458. enccfg.g_pass = VPX_RC_FIRST_PASS;
  459. else if (avctx->flags & AV_CODEC_FLAG_PASS2)
  460. enccfg.g_pass = VPX_RC_LAST_PASS;
  461. else
  462. enccfg.g_pass = VPX_RC_ONE_PASS;
  463. if (avctx->rc_min_rate == avctx->rc_max_rate &&
  464. avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
  465. enccfg.rc_end_usage = VPX_CBR;
  466. } else if (ctx->crf >= 0) {
  467. enccfg.rc_end_usage = VPX_CQ;
  468. #if CONFIG_LIBVPX_VP9_ENCODER
  469. if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
  470. enccfg.rc_end_usage = VPX_Q;
  471. #endif
  472. }
  473. if (avctx->bit_rate) {
  474. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  475. AV_ROUND_NEAR_INF);
  476. #if CONFIG_LIBVPX_VP9_ENCODER
  477. } else if (enccfg.rc_end_usage == VPX_Q) {
  478. #endif
  479. } else {
  480. if (enccfg.rc_end_usage == VPX_CQ) {
  481. enccfg.rc_target_bitrate = 1000000;
  482. } else {
  483. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  484. av_log(avctx, AV_LOG_WARNING,
  485. "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
  486. enccfg.rc_target_bitrate);
  487. }
  488. }
  489. if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
  490. enccfg.rc_min_quantizer =
  491. enccfg.rc_max_quantizer = 0;
  492. } else {
  493. if (avctx->qmin >= 0)
  494. enccfg.rc_min_quantizer = avctx->qmin;
  495. if (avctx->qmax >= 0)
  496. enccfg.rc_max_quantizer = avctx->qmax;
  497. }
  498. if (enccfg.rc_end_usage == VPX_CQ
  499. #if CONFIG_LIBVPX_VP9_ENCODER
  500. || enccfg.rc_end_usage == VPX_Q
  501. #endif
  502. ) {
  503. if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
  504. av_log(avctx, AV_LOG_ERROR,
  505. "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
  506. ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
  507. return AVERROR(EINVAL);
  508. }
  509. }
  510. #if FF_API_PRIVATE_OPT
  511. FF_DISABLE_DEPRECATION_WARNINGS
  512. if (avctx->frame_skip_threshold)
  513. ctx->drop_threshold = avctx->frame_skip_threshold;
  514. FF_ENABLE_DEPRECATION_WARNINGS
  515. #endif
  516. enccfg.rc_dropframe_thresh = ctx->drop_threshold;
  517. //0-100 (0 => CBR, 100 => VBR)
  518. enccfg.rc_2pass_vbr_bias_pct = lrint(avctx->qcompress * 100);
  519. if (avctx->bit_rate)
  520. enccfg.rc_2pass_vbr_minsection_pct =
  521. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  522. if (avctx->rc_max_rate)
  523. enccfg.rc_2pass_vbr_maxsection_pct =
  524. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  525. #if CONFIG_LIBVPX_VP9_ENCODER
  526. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  527. #if VPX_ENCODER_ABI_VERSION >= 14
  528. if (ctx->corpus_complexity >= 0)
  529. enccfg.rc_2pass_vbr_corpus_complexity = ctx->corpus_complexity;
  530. #endif
  531. }
  532. #endif
  533. if (avctx->rc_buffer_size)
  534. enccfg.rc_buf_sz =
  535. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  536. if (avctx->rc_initial_buffer_occupancy)
  537. enccfg.rc_buf_initial_sz =
  538. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  539. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  540. if (ctx->rc_undershoot_pct >= 0)
  541. enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
  542. if (ctx->rc_overshoot_pct >= 0)
  543. enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
  544. //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
  545. if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
  546. enccfg.kf_min_dist = avctx->keyint_min;
  547. if (avctx->gop_size >= 0)
  548. enccfg.kf_max_dist = avctx->gop_size;
  549. if (enccfg.g_pass == VPX_RC_FIRST_PASS)
  550. enccfg.g_lag_in_frames = 0;
  551. else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
  552. int decode_size, ret;
  553. if (!avctx->stats_in) {
  554. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  555. return AVERROR_INVALIDDATA;
  556. }
  557. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  558. ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
  559. if (ret < 0) {
  560. av_log(avctx, AV_LOG_ERROR,
  561. "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  562. ctx->twopass_stats.sz);
  563. ctx->twopass_stats.sz = 0;
  564. return ret;
  565. }
  566. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  567. ctx->twopass_stats.sz);
  568. if (decode_size < 0) {
  569. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  570. return AVERROR_INVALIDDATA;
  571. }
  572. ctx->twopass_stats.sz = decode_size;
  573. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  574. }
  575. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  576. complexity playback on low powered devices at the expense of encode
  577. quality. */
  578. if (avctx->profile != FF_PROFILE_UNKNOWN)
  579. enccfg.g_profile = avctx->profile;
  580. enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
  581. dump_enc_cfg(avctx, &enccfg);
  582. /* Construct Encoder Context */
  583. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
  584. if (res != VPX_CODEC_OK) {
  585. log_encoder_error(avctx, "Failed to initialize encoder");
  586. return AVERROR(EINVAL);
  587. }
  588. if (ctx->is_alpha) {
  589. enccfg_alpha = enccfg;
  590. res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
  591. if (res != VPX_CODEC_OK) {
  592. log_encoder_error(avctx, "Failed to initialize alpha encoder");
  593. return AVERROR(EINVAL);
  594. }
  595. }
  596. //codec control failures are currently treated only as warnings
  597. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  598. codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
  599. if (ctx->flags & VP8F_AUTO_ALT_REF)
  600. ctx->auto_alt_ref = 1;
  601. if (ctx->auto_alt_ref >= 0)
  602. codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF,
  603. avctx->codec_id == AV_CODEC_ID_VP8 ? !!ctx->auto_alt_ref : ctx->auto_alt_ref);
  604. if (ctx->arnr_max_frames >= 0)
  605. codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
  606. if (ctx->arnr_strength >= 0)
  607. codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
  608. if (ctx->arnr_type >= 0)
  609. codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
  610. if (ctx->tune >= 0)
  611. codecctl_int(avctx, VP8E_SET_TUNING, ctx->tune);
  612. if (ctx->auto_alt_ref && ctx->is_alpha && avctx->codec_id == AV_CODEC_ID_VP8) {
  613. av_log(avctx, AV_LOG_ERROR, "Transparency encoding with auto_alt_ref does not work\n");
  614. return AVERROR(EINVAL);
  615. }
  616. if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
  617. #if FF_API_PRIVATE_OPT
  618. FF_DISABLE_DEPRECATION_WARNINGS
  619. if (avctx->noise_reduction)
  620. ctx->noise_sensitivity = avctx->noise_reduction;
  621. FF_ENABLE_DEPRECATION_WARNINGS
  622. #endif
  623. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, ctx->noise_sensitivity);
  624. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  625. }
  626. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
  627. if (ctx->crf >= 0)
  628. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  629. if (ctx->max_intra_rate >= 0)
  630. codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
  631. #if CONFIG_LIBVPX_VP9_ENCODER
  632. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  633. if (ctx->lossless >= 0)
  634. codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
  635. if (ctx->tile_columns >= 0)
  636. codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
  637. if (ctx->tile_rows >= 0)
  638. codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
  639. if (ctx->frame_parallel >= 0)
  640. codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
  641. if (ctx->aq_mode >= 0)
  642. codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
  643. set_colorspace(avctx);
  644. #if VPX_ENCODER_ABI_VERSION >= 11
  645. set_color_range(avctx);
  646. #endif
  647. #if VPX_ENCODER_ABI_VERSION >= 12
  648. codecctl_int(avctx, VP9E_SET_TARGET_LEVEL, ctx->level < 0 ? 255 : lrint(ctx->level * 10));
  649. #endif
  650. #ifdef VPX_CTRL_VP9E_SET_ROW_MT
  651. if (ctx->row_mt >= 0)
  652. codecctl_int(avctx, VP9E_SET_ROW_MT, ctx->row_mt);
  653. #endif
  654. #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
  655. if (ctx->tune_content >= 0)
  656. codecctl_int(avctx, VP9E_SET_TUNE_CONTENT, ctx->tune_content);
  657. #endif
  658. #ifdef VPX_CTRL_VP9E_SET_TPL
  659. if (ctx->tpl_model >= 0)
  660. codecctl_int(avctx, VP9E_SET_TPL, ctx->tpl_model);
  661. #endif
  662. }
  663. #endif
  664. av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
  665. //provide dummy value to initialize wrapper, values will be updated each _encode()
  666. vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
  667. (unsigned char*)1);
  668. #if CONFIG_LIBVPX_VP9_ENCODER
  669. if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
  670. ctx->rawimg.bit_depth = enccfg.g_bit_depth;
  671. #endif
  672. if (ctx->is_alpha)
  673. vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  674. (unsigned char*)1);
  675. cpb_props = ff_add_cpb_side_data(avctx);
  676. if (!cpb_props)
  677. return AVERROR(ENOMEM);
  678. if (enccfg.rc_end_usage == VPX_CBR ||
  679. enccfg.g_pass != VPX_RC_ONE_PASS) {
  680. cpb_props->max_bitrate = avctx->rc_max_rate;
  681. cpb_props->min_bitrate = avctx->rc_min_rate;
  682. cpb_props->avg_bitrate = avctx->bit_rate;
  683. }
  684. cpb_props->buffer_size = avctx->rc_buffer_size;
  685. return 0;
  686. }
  687. static inline void cx_pktcpy(struct FrameListData *dst,
  688. const struct vpx_codec_cx_pkt *src,
  689. const struct vpx_codec_cx_pkt *src_alpha,
  690. VPxContext *ctx)
  691. {
  692. dst->pts = src->data.frame.pts;
  693. dst->duration = src->data.frame.duration;
  694. dst->flags = src->data.frame.flags;
  695. dst->sz = src->data.frame.sz;
  696. dst->buf = src->data.frame.buf;
  697. dst->have_sse = 0;
  698. /* For alt-ref frame, don't store PSNR or increment frame_number */
  699. if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
  700. dst->frame_number = ++ctx->frame_number;
  701. dst->have_sse = ctx->have_sse;
  702. if (ctx->have_sse) {
  703. /* associate last-seen SSE to the frame. */
  704. /* Transfers ownership from ctx to dst. */
  705. /* WARNING! This makes the assumption that PSNR_PKT comes
  706. just before the frame it refers to! */
  707. memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
  708. ctx->have_sse = 0;
  709. }
  710. } else {
  711. dst->frame_number = -1; /* sanity marker */
  712. }
  713. if (src_alpha) {
  714. dst->buf_alpha = src_alpha->data.frame.buf;
  715. dst->sz_alpha = src_alpha->data.frame.sz;
  716. } else {
  717. dst->buf_alpha = NULL;
  718. dst->sz_alpha = 0;
  719. }
  720. }
  721. /**
  722. * Store coded frame information in format suitable for return from encode2().
  723. *
  724. * Write information from @a cx_frame to @a pkt
  725. * @return packet data size on success
  726. * @return a negative AVERROR on error
  727. */
  728. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  729. AVPacket *pkt)
  730. {
  731. int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
  732. uint8_t *side_data;
  733. if (ret >= 0) {
  734. int pict_type;
  735. memcpy(pkt->data, cx_frame->buf, pkt->size);
  736. pkt->pts = pkt->dts = cx_frame->pts;
  737. #if FF_API_CODED_FRAME
  738. FF_DISABLE_DEPRECATION_WARNINGS
  739. avctx->coded_frame->pts = cx_frame->pts;
  740. avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  741. FF_ENABLE_DEPRECATION_WARNINGS
  742. #endif
  743. if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
  744. pict_type = AV_PICTURE_TYPE_I;
  745. #if FF_API_CODED_FRAME
  746. FF_DISABLE_DEPRECATION_WARNINGS
  747. avctx->coded_frame->pict_type = pict_type;
  748. FF_ENABLE_DEPRECATION_WARNINGS
  749. #endif
  750. pkt->flags |= AV_PKT_FLAG_KEY;
  751. } else {
  752. pict_type = AV_PICTURE_TYPE_P;
  753. #if FF_API_CODED_FRAME
  754. FF_DISABLE_DEPRECATION_WARNINGS
  755. avctx->coded_frame->pict_type = pict_type;
  756. FF_ENABLE_DEPRECATION_WARNINGS
  757. #endif
  758. }
  759. ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
  760. cx_frame->have_sse ? 3 : 0, pict_type);
  761. if (cx_frame->have_sse) {
  762. int i;
  763. /* Beware of the Y/U/V/all order! */
  764. #if FF_API_CODED_FRAME
  765. FF_DISABLE_DEPRECATION_WARNINGS
  766. avctx->coded_frame->error[0] = cx_frame->sse[1];
  767. avctx->coded_frame->error[1] = cx_frame->sse[2];
  768. avctx->coded_frame->error[2] = cx_frame->sse[3];
  769. avctx->coded_frame->error[3] = 0; // alpha
  770. FF_ENABLE_DEPRECATION_WARNINGS
  771. #endif
  772. for (i = 0; i < 3; ++i) {
  773. avctx->error[i] += cx_frame->sse[i + 1];
  774. }
  775. cx_frame->have_sse = 0;
  776. }
  777. if (cx_frame->sz_alpha > 0) {
  778. side_data = av_packet_new_side_data(pkt,
  779. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  780. cx_frame->sz_alpha + 8);
  781. if(!side_data) {
  782. av_packet_unref(pkt);
  783. av_free(pkt);
  784. return AVERROR(ENOMEM);
  785. }
  786. AV_WB64(side_data, 1);
  787. memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
  788. }
  789. } else {
  790. return ret;
  791. }
  792. return pkt->size;
  793. }
  794. /**
  795. * Queue multiple output frames from the encoder, returning the front-most.
  796. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  797. * the frame queue. Return the head frame if available.
  798. * @return Stored frame size
  799. * @return AVERROR(EINVAL) on output size error
  800. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  801. */
  802. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
  803. {
  804. VPxContext *ctx = avctx->priv_data;
  805. const struct vpx_codec_cx_pkt *pkt;
  806. const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
  807. const void *iter = NULL;
  808. const void *iter_alpha = NULL;
  809. int size = 0;
  810. if (ctx->coded_frame_list) {
  811. struct FrameListData *cx_frame = ctx->coded_frame_list;
  812. /* return the leading frame if we've already begun queueing */
  813. size = storeframe(avctx, cx_frame, pkt_out);
  814. if (size < 0)
  815. return size;
  816. ctx->coded_frame_list = cx_frame->next;
  817. free_coded_frame(cx_frame);
  818. }
  819. /* consume all available output from the encoder before returning. buffers
  820. are only good through the next vpx_codec call */
  821. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
  822. (!ctx->is_alpha ||
  823. (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
  824. switch (pkt->kind) {
  825. case VPX_CODEC_CX_FRAME_PKT:
  826. if (!size) {
  827. struct FrameListData cx_frame;
  828. /* avoid storing the frame when the list is empty and we haven't yet
  829. provided a frame for output */
  830. av_assert0(!ctx->coded_frame_list);
  831. cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
  832. size = storeframe(avctx, &cx_frame, pkt_out);
  833. if (size < 0)
  834. return size;
  835. } else {
  836. struct FrameListData *cx_frame =
  837. av_malloc(sizeof(struct FrameListData));
  838. if (!cx_frame) {
  839. av_log(avctx, AV_LOG_ERROR,
  840. "Frame queue element alloc failed\n");
  841. return AVERROR(ENOMEM);
  842. }
  843. cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
  844. cx_frame->buf = av_malloc(cx_frame->sz);
  845. if (!cx_frame->buf) {
  846. av_log(avctx, AV_LOG_ERROR,
  847. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  848. cx_frame->sz);
  849. av_freep(&cx_frame);
  850. return AVERROR(ENOMEM);
  851. }
  852. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  853. if (ctx->is_alpha) {
  854. cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
  855. if (!cx_frame->buf_alpha) {
  856. av_log(avctx, AV_LOG_ERROR,
  857. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  858. cx_frame->sz_alpha);
  859. av_free(cx_frame);
  860. return AVERROR(ENOMEM);
  861. }
  862. memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
  863. }
  864. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  865. }
  866. break;
  867. case VPX_CODEC_STATS_PKT: {
  868. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  869. int err;
  870. if ((err = av_reallocp(&stats->buf,
  871. stats->sz +
  872. pkt->data.twopass_stats.sz)) < 0) {
  873. stats->sz = 0;
  874. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  875. return err;
  876. }
  877. memcpy((uint8_t*)stats->buf + stats->sz,
  878. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  879. stats->sz += pkt->data.twopass_stats.sz;
  880. break;
  881. }
  882. case VPX_CODEC_PSNR_PKT:
  883. av_assert0(!ctx->have_sse);
  884. ctx->sse[0] = pkt->data.psnr.sse[0];
  885. ctx->sse[1] = pkt->data.psnr.sse[1];
  886. ctx->sse[2] = pkt->data.psnr.sse[2];
  887. ctx->sse[3] = pkt->data.psnr.sse[3];
  888. ctx->have_sse = 1;
  889. break;
  890. case VPX_CODEC_CUSTOM_PKT:
  891. //ignore unsupported/unrecognized packet types
  892. break;
  893. }
  894. }
  895. return size;
  896. }
  897. static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt,
  898. const AVFrame *frame, int *got_packet)
  899. {
  900. VPxContext *ctx = avctx->priv_data;
  901. struct vpx_image *rawimg = NULL;
  902. struct vpx_image *rawimg_alpha = NULL;
  903. int64_t timestamp = 0;
  904. int res, coded_size;
  905. vpx_enc_frame_flags_t flags = 0;
  906. if (frame) {
  907. rawimg = &ctx->rawimg;
  908. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  909. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  910. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  911. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  912. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  913. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  914. if (ctx->is_alpha) {
  915. uint8_t *u_plane, *v_plane;
  916. rawimg_alpha = &ctx->rawimg_alpha;
  917. rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
  918. u_plane = av_malloc(frame->linesize[1] * frame->height);
  919. v_plane = av_malloc(frame->linesize[2] * frame->height);
  920. if (!u_plane || !v_plane) {
  921. av_free(u_plane);
  922. av_free(v_plane);
  923. return AVERROR(ENOMEM);
  924. }
  925. memset(u_plane, 0x80, frame->linesize[1] * frame->height);
  926. rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
  927. memset(v_plane, 0x80, frame->linesize[2] * frame->height);
  928. rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
  929. rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
  930. rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
  931. rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
  932. }
  933. timestamp = frame->pts;
  934. #if VPX_IMAGE_ABI_VERSION >= 4
  935. switch (frame->color_range) {
  936. case AVCOL_RANGE_MPEG:
  937. rawimg->range = VPX_CR_STUDIO_RANGE;
  938. break;
  939. case AVCOL_RANGE_JPEG:
  940. rawimg->range = VPX_CR_FULL_RANGE;
  941. break;
  942. }
  943. #endif
  944. if (frame->pict_type == AV_PICTURE_TYPE_I)
  945. flags |= VPX_EFLAG_FORCE_KF;
  946. }
  947. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  948. avctx->ticks_per_frame, flags, ctx->deadline);
  949. if (res != VPX_CODEC_OK) {
  950. log_encoder_error(avctx, "Error encoding frame");
  951. return AVERROR_INVALIDDATA;
  952. }
  953. if (ctx->is_alpha) {
  954. res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
  955. avctx->ticks_per_frame, flags, ctx->deadline);
  956. if (res != VPX_CODEC_OK) {
  957. log_encoder_error(avctx, "Error encoding alpha frame");
  958. return AVERROR_INVALIDDATA;
  959. }
  960. }
  961. coded_size = queue_frames(avctx, pkt);
  962. if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
  963. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  964. avctx->stats_out = av_malloc(b64_size);
  965. if (!avctx->stats_out) {
  966. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  967. b64_size);
  968. return AVERROR(ENOMEM);
  969. }
  970. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  971. ctx->twopass_stats.sz);
  972. }
  973. if (rawimg_alpha) {
  974. av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
  975. av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
  976. }
  977. *got_packet = !!coded_size;
  978. return 0;
  979. }
  980. #define OFFSET(x) offsetof(VPxContext, x)
  981. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  982. #define COMMON_OPTIONS \
  983. { "auto-alt-ref", "Enable use of alternate reference " \
  984. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE}, \
  985. { "lag-in-frames", "Number of frames to look ahead for " \
  986. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  987. { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  988. { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  989. { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
  990. { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
  991. { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
  992. { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
  993. { "tune", "Tune the encoding to a specific scenario", OFFSET(tune), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "tune"}, \
  994. { "psnr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_PSNR}, 0, 0, VE, "tune"}, \
  995. { "ssim", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_SSIM}, 0, 0, VE, "tune"}, \
  996. { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  997. { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
  998. { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
  999. { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
  1000. { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
  1001. { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  1002. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
  1003. { "partitions", "The frame partitions are independently decodable " \
  1004. "by the bool decoder, meaning that partitions can be decoded even " \
  1005. "though earlier partitions have been lost. Note that intra predicition" \
  1006. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
  1007. { "crf", "Select the quality for constant quality mode", offsetof(VPxContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
  1008. { "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 }, \
  1009. { "drop-threshold", "Frame drop threshold", offsetof(VPxContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE }, \
  1010. { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE}, \
  1011. { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
  1012. { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
  1013. #define LEGACY_OPTIONS \
  1014. {"speed", "", offsetof(VPxContext, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
  1015. {"quality", "", offsetof(VPxContext, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  1016. {"vp8flags", "", offsetof(VPxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
  1017. {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
  1018. {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"}, \
  1019. {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VPxContext, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
  1020. {"arnr_strength", "altref noise reduction filter strength", offsetof(VPxContext, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
  1021. {"arnr_type", "altref noise reduction filter type", offsetof(VPxContext, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
  1022. {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VPxContext, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE}, \
  1023. #if CONFIG_LIBVPX_VP8_ENCODER
  1024. static const AVOption vp8_options[] = {
  1025. COMMON_OPTIONS
  1026. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE},
  1027. LEGACY_OPTIONS
  1028. { NULL }
  1029. };
  1030. #endif
  1031. #if CONFIG_LIBVPX_VP9_ENCODER
  1032. static const AVOption vp9_options[] = {
  1033. COMMON_OPTIONS
  1034. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
  1035. { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  1036. { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
  1037. { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
  1038. { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_BOOL,{.i64 = -1}, -1, 1, VE},
  1039. #if VPX_ENCODER_ABI_VERSION >= 12
  1040. { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 4, VE, "aq_mode"},
  1041. #else
  1042. { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
  1043. #endif
  1044. { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
  1045. { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
  1046. { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
  1047. { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
  1048. #if VPX_ENCODER_ABI_VERSION >= 12
  1049. { "equator360", "360 video Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 4}, 0, 0, VE, "aq_mode" },
  1050. {"level", "Specify level", OFFSET(level), AV_OPT_TYPE_FLOAT, {.dbl=-1}, -1, 6.2, VE},
  1051. #endif
  1052. #ifdef VPX_CTRL_VP9E_SET_ROW_MT
  1053. {"row-mt", "Row based multi-threading", OFFSET(row_mt), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE},
  1054. #endif
  1055. #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
  1056. #if VPX_ENCODER_ABI_VERSION >= 14
  1057. { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE, "tune_content" },
  1058. #else
  1059. { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE, "tune_content" },
  1060. #endif
  1061. { "default", "Regular video content", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "tune_content" },
  1062. { "screen", "Screen capture content", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "tune_content" },
  1063. #if VPX_ENCODER_ABI_VERSION >= 14
  1064. { "film", "Film content; improves grain retention", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "tune_content" },
  1065. #endif
  1066. #endif
  1067. #if VPX_ENCODER_ABI_VERSION >= 14
  1068. { "corpus-complexity", "corpus vbr complexity midpoint", OFFSET(corpus_complexity), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 10000, VE },
  1069. #endif
  1070. #ifdef VPX_CTRL_VP9E_SET_TPL
  1071. { "enable-tpl", "Enable temporal dependency model", OFFSET(tpl_model), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE },
  1072. #endif
  1073. LEGACY_OPTIONS
  1074. { NULL }
  1075. };
  1076. #endif
  1077. #undef COMMON_OPTIONS
  1078. #undef LEGACY_OPTIONS
  1079. static const AVCodecDefault defaults[] = {
  1080. { "qmin", "-1" },
  1081. { "qmax", "-1" },
  1082. { "g", "-1" },
  1083. { "keyint_min", "-1" },
  1084. { NULL },
  1085. };
  1086. #if CONFIG_LIBVPX_VP8_ENCODER
  1087. static av_cold int vp8_init(AVCodecContext *avctx)
  1088. {
  1089. return vpx_init(avctx, vpx_codec_vp8_cx());
  1090. }
  1091. static const AVClass class_vp8 = {
  1092. .class_name = "libvpx-vp8 encoder",
  1093. .item_name = av_default_item_name,
  1094. .option = vp8_options,
  1095. .version = LIBAVUTIL_VERSION_INT,
  1096. };
  1097. AVCodec ff_libvpx_vp8_encoder = {
  1098. .name = "libvpx",
  1099. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  1100. .type = AVMEDIA_TYPE_VIDEO,
  1101. .id = AV_CODEC_ID_VP8,
  1102. .priv_data_size = sizeof(VPxContext),
  1103. .init = vp8_init,
  1104. .encode2 = vpx_encode,
  1105. .close = vpx_free,
  1106. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  1107. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
  1108. .priv_class = &class_vp8,
  1109. .defaults = defaults,
  1110. .wrapper_name = "libvpx",
  1111. };
  1112. #endif /* CONFIG_LIBVPX_VP8_ENCODER */
  1113. #if CONFIG_LIBVPX_VP9_ENCODER
  1114. static av_cold int vp9_init(AVCodecContext *avctx)
  1115. {
  1116. return vpx_init(avctx, vpx_codec_vp9_cx());
  1117. }
  1118. static const AVClass class_vp9 = {
  1119. .class_name = "libvpx-vp9 encoder",
  1120. .item_name = av_default_item_name,
  1121. .option = vp9_options,
  1122. .version = LIBAVUTIL_VERSION_INT,
  1123. };
  1124. AVCodec ff_libvpx_vp9_encoder = {
  1125. .name = "libvpx-vp9",
  1126. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
  1127. .type = AVMEDIA_TYPE_VIDEO,
  1128. .id = AV_CODEC_ID_VP9,
  1129. .priv_data_size = sizeof(VPxContext),
  1130. .init = vp9_init,
  1131. .encode2 = vpx_encode,
  1132. .close = vpx_free,
  1133. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  1134. .profiles = NULL_IF_CONFIG_SMALL(ff_vp9_profiles),
  1135. .priv_class = &class_vp9,
  1136. .defaults = defaults,
  1137. .init_static_data = ff_vp9_init_static,
  1138. .wrapper_name = "libvpx",
  1139. };
  1140. #endif /* CONFIG_LIBVPX_VP9_ENCODER */