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.

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