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.

1160 lines
45KB

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