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.

1176 lines
46KB

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