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.

1165 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. } 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 (ctx->auto_alt_ref && ctx->is_alpha && avctx->codec_id == AV_CODEC_ID_VP8) {
  576. av_log(avctx, AV_LOG_ERROR, "Transparency encoding with auto_alt_ref does not work\n");
  577. return AVERROR(EINVAL);
  578. }
  579. if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
  580. #if FF_API_PRIVATE_OPT
  581. FF_DISABLE_DEPRECATION_WARNINGS
  582. if (avctx->noise_reduction)
  583. ctx->noise_sensitivity = avctx->noise_reduction;
  584. FF_ENABLE_DEPRECATION_WARNINGS
  585. #endif
  586. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, ctx->noise_sensitivity);
  587. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  588. }
  589. #if FF_API_MPV_OPT
  590. FF_DISABLE_DEPRECATION_WARNINGS
  591. if (avctx->mb_threshold) {
  592. av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
  593. "use the static-thresh private option instead.\n");
  594. ctx->static_thresh = avctx->mb_threshold;
  595. }
  596. FF_ENABLE_DEPRECATION_WARNINGS
  597. #endif
  598. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
  599. if (ctx->crf >= 0)
  600. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  601. if (ctx->max_intra_rate >= 0)
  602. codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
  603. #if CONFIG_LIBVPX_VP9_ENCODER
  604. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  605. if (ctx->lossless >= 0)
  606. codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
  607. if (ctx->tile_columns >= 0)
  608. codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
  609. if (ctx->tile_rows >= 0)
  610. codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
  611. if (ctx->frame_parallel >= 0)
  612. codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
  613. if (ctx->aq_mode >= 0)
  614. codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
  615. #if VPX_ENCODER_ABI_VERSION > 8
  616. set_colorspace(avctx);
  617. #endif
  618. #if VPX_ENCODER_ABI_VERSION >= 11
  619. set_color_range(avctx);
  620. #endif
  621. }
  622. #endif
  623. av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
  624. //provide dummy value to initialize wrapper, values will be updated each _encode()
  625. vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
  626. (unsigned char*)1);
  627. #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
  628. if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
  629. ctx->rawimg.bit_depth = enccfg.g_bit_depth;
  630. #endif
  631. if (ctx->is_alpha)
  632. vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  633. (unsigned char*)1);
  634. cpb_props = ff_add_cpb_side_data(avctx);
  635. if (!cpb_props)
  636. return AVERROR(ENOMEM);
  637. if (enccfg.rc_end_usage == VPX_CBR ||
  638. enccfg.g_pass != VPX_RC_ONE_PASS) {
  639. cpb_props->max_bitrate = avctx->rc_max_rate;
  640. cpb_props->min_bitrate = avctx->rc_min_rate;
  641. cpb_props->avg_bitrate = avctx->bit_rate;
  642. }
  643. cpb_props->buffer_size = avctx->rc_buffer_size;
  644. return 0;
  645. }
  646. static inline void cx_pktcpy(struct FrameListData *dst,
  647. const struct vpx_codec_cx_pkt *src,
  648. const struct vpx_codec_cx_pkt *src_alpha,
  649. VPxContext *ctx)
  650. {
  651. dst->pts = src->data.frame.pts;
  652. dst->duration = src->data.frame.duration;
  653. dst->flags = src->data.frame.flags;
  654. dst->sz = src->data.frame.sz;
  655. dst->buf = src->data.frame.buf;
  656. dst->have_sse = 0;
  657. /* For alt-ref frame, don't store PSNR or increment frame_number */
  658. if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
  659. dst->frame_number = ++ctx->frame_number;
  660. dst->have_sse = ctx->have_sse;
  661. if (ctx->have_sse) {
  662. /* associate last-seen SSE to the frame. */
  663. /* Transfers ownership from ctx to dst. */
  664. /* WARNING! This makes the assumption that PSNR_PKT comes
  665. just before the frame it refers to! */
  666. memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
  667. ctx->have_sse = 0;
  668. }
  669. } else {
  670. dst->frame_number = -1; /* sanity marker */
  671. }
  672. if (src_alpha) {
  673. dst->buf_alpha = src_alpha->data.frame.buf;
  674. dst->sz_alpha = src_alpha->data.frame.sz;
  675. } else {
  676. dst->buf_alpha = NULL;
  677. dst->sz_alpha = 0;
  678. }
  679. }
  680. /**
  681. * Store coded frame information in format suitable for return from encode2().
  682. *
  683. * Write information from @a cx_frame to @a pkt
  684. * @return packet data size on success
  685. * @return a negative AVERROR on error
  686. */
  687. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  688. AVPacket *pkt)
  689. {
  690. int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
  691. uint8_t *side_data;
  692. if (ret >= 0) {
  693. int pict_type;
  694. memcpy(pkt->data, cx_frame->buf, pkt->size);
  695. pkt->pts = pkt->dts = cx_frame->pts;
  696. #if FF_API_CODED_FRAME
  697. FF_DISABLE_DEPRECATION_WARNINGS
  698. avctx->coded_frame->pts = cx_frame->pts;
  699. avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  700. FF_ENABLE_DEPRECATION_WARNINGS
  701. #endif
  702. if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
  703. pict_type = AV_PICTURE_TYPE_I;
  704. #if FF_API_CODED_FRAME
  705. FF_DISABLE_DEPRECATION_WARNINGS
  706. avctx->coded_frame->pict_type = pict_type;
  707. FF_ENABLE_DEPRECATION_WARNINGS
  708. #endif
  709. pkt->flags |= AV_PKT_FLAG_KEY;
  710. } else {
  711. pict_type = AV_PICTURE_TYPE_P;
  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. }
  718. ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
  719. cx_frame->have_sse ? 3 : 0, pict_type);
  720. if (cx_frame->have_sse) {
  721. int i;
  722. /* Beware of the Y/U/V/all order! */
  723. #if FF_API_CODED_FRAME
  724. FF_DISABLE_DEPRECATION_WARNINGS
  725. avctx->coded_frame->error[0] = cx_frame->sse[1];
  726. avctx->coded_frame->error[1] = cx_frame->sse[2];
  727. avctx->coded_frame->error[2] = cx_frame->sse[3];
  728. avctx->coded_frame->error[3] = 0; // alpha
  729. FF_ENABLE_DEPRECATION_WARNINGS
  730. #endif
  731. for (i = 0; i < 3; ++i) {
  732. avctx->error[i] += cx_frame->sse[i + 1];
  733. }
  734. cx_frame->have_sse = 0;
  735. }
  736. if (cx_frame->sz_alpha > 0) {
  737. side_data = av_packet_new_side_data(pkt,
  738. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  739. cx_frame->sz_alpha + 8);
  740. if(!side_data) {
  741. av_packet_unref(pkt);
  742. av_free(pkt);
  743. return AVERROR(ENOMEM);
  744. }
  745. AV_WB64(side_data, 1);
  746. memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
  747. }
  748. } else {
  749. return ret;
  750. }
  751. return pkt->size;
  752. }
  753. /**
  754. * Queue multiple output frames from the encoder, returning the front-most.
  755. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  756. * the frame queue. Return the head frame if available.
  757. * @return Stored frame size
  758. * @return AVERROR(EINVAL) on output size error
  759. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  760. */
  761. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
  762. {
  763. VPxContext *ctx = avctx->priv_data;
  764. const struct vpx_codec_cx_pkt *pkt;
  765. const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
  766. const void *iter = NULL;
  767. const void *iter_alpha = NULL;
  768. int size = 0;
  769. if (ctx->coded_frame_list) {
  770. struct FrameListData *cx_frame = ctx->coded_frame_list;
  771. /* return the leading frame if we've already begun queueing */
  772. size = storeframe(avctx, cx_frame, pkt_out);
  773. if (size < 0)
  774. return size;
  775. ctx->coded_frame_list = cx_frame->next;
  776. free_coded_frame(cx_frame);
  777. }
  778. /* consume all available output from the encoder before returning. buffers
  779. are only good through the next vpx_codec call */
  780. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
  781. (!ctx->is_alpha ||
  782. (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
  783. switch (pkt->kind) {
  784. case VPX_CODEC_CX_FRAME_PKT:
  785. if (!size) {
  786. struct FrameListData cx_frame;
  787. /* avoid storing the frame when the list is empty and we haven't yet
  788. provided a frame for output */
  789. av_assert0(!ctx->coded_frame_list);
  790. cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
  791. size = storeframe(avctx, &cx_frame, pkt_out);
  792. if (size < 0)
  793. return size;
  794. } else {
  795. struct FrameListData *cx_frame =
  796. av_malloc(sizeof(struct FrameListData));
  797. if (!cx_frame) {
  798. av_log(avctx, AV_LOG_ERROR,
  799. "Frame queue element alloc failed\n");
  800. return AVERROR(ENOMEM);
  801. }
  802. cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
  803. cx_frame->buf = av_malloc(cx_frame->sz);
  804. if (!cx_frame->buf) {
  805. av_log(avctx, AV_LOG_ERROR,
  806. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  807. cx_frame->sz);
  808. av_freep(&cx_frame);
  809. return AVERROR(ENOMEM);
  810. }
  811. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  812. if (ctx->is_alpha) {
  813. cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
  814. if (!cx_frame->buf_alpha) {
  815. av_log(avctx, AV_LOG_ERROR,
  816. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  817. cx_frame->sz_alpha);
  818. av_free(cx_frame);
  819. return AVERROR(ENOMEM);
  820. }
  821. memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
  822. }
  823. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  824. }
  825. break;
  826. case VPX_CODEC_STATS_PKT: {
  827. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  828. int err;
  829. if ((err = av_reallocp(&stats->buf,
  830. stats->sz +
  831. pkt->data.twopass_stats.sz)) < 0) {
  832. stats->sz = 0;
  833. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  834. return err;
  835. }
  836. memcpy((uint8_t*)stats->buf + stats->sz,
  837. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  838. stats->sz += pkt->data.twopass_stats.sz;
  839. break;
  840. }
  841. case VPX_CODEC_PSNR_PKT:
  842. av_assert0(!ctx->have_sse);
  843. ctx->sse[0] = pkt->data.psnr.sse[0];
  844. ctx->sse[1] = pkt->data.psnr.sse[1];
  845. ctx->sse[2] = pkt->data.psnr.sse[2];
  846. ctx->sse[3] = pkt->data.psnr.sse[3];
  847. ctx->have_sse = 1;
  848. break;
  849. case VPX_CODEC_CUSTOM_PKT:
  850. //ignore unsupported/unrecognized packet types
  851. break;
  852. }
  853. }
  854. return size;
  855. }
  856. static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt,
  857. const AVFrame *frame, int *got_packet)
  858. {
  859. VPxContext *ctx = avctx->priv_data;
  860. struct vpx_image *rawimg = NULL;
  861. struct vpx_image *rawimg_alpha = NULL;
  862. int64_t timestamp = 0;
  863. int res, coded_size;
  864. vpx_enc_frame_flags_t flags = 0;
  865. if (frame) {
  866. rawimg = &ctx->rawimg;
  867. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  868. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  869. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  870. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  871. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  872. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  873. if (ctx->is_alpha) {
  874. uint8_t *u_plane, *v_plane;
  875. rawimg_alpha = &ctx->rawimg_alpha;
  876. rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
  877. u_plane = av_malloc(frame->linesize[1] * frame->height);
  878. v_plane = av_malloc(frame->linesize[2] * frame->height);
  879. if (!u_plane || !v_plane) {
  880. av_free(u_plane);
  881. av_free(v_plane);
  882. return AVERROR(ENOMEM);
  883. }
  884. memset(u_plane, 0x80, frame->linesize[1] * frame->height);
  885. rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
  886. memset(v_plane, 0x80, frame->linesize[2] * frame->height);
  887. rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
  888. rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
  889. rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
  890. rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
  891. }
  892. timestamp = frame->pts;
  893. if (frame->pict_type == AV_PICTURE_TYPE_I)
  894. flags |= VPX_EFLAG_FORCE_KF;
  895. }
  896. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  897. avctx->ticks_per_frame, flags, ctx->deadline);
  898. if (res != VPX_CODEC_OK) {
  899. log_encoder_error(avctx, "Error encoding frame");
  900. return AVERROR_INVALIDDATA;
  901. }
  902. if (ctx->is_alpha) {
  903. res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
  904. avctx->ticks_per_frame, flags, ctx->deadline);
  905. if (res != VPX_CODEC_OK) {
  906. log_encoder_error(avctx, "Error encoding alpha frame");
  907. return AVERROR_INVALIDDATA;
  908. }
  909. }
  910. coded_size = queue_frames(avctx, pkt);
  911. if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
  912. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  913. avctx->stats_out = av_malloc(b64_size);
  914. if (!avctx->stats_out) {
  915. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  916. b64_size);
  917. return AVERROR(ENOMEM);
  918. }
  919. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  920. ctx->twopass_stats.sz);
  921. }
  922. if (rawimg_alpha) {
  923. av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
  924. av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
  925. }
  926. *got_packet = !!coded_size;
  927. return 0;
  928. }
  929. #define OFFSET(x) offsetof(VPxContext, x)
  930. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  931. #ifndef VPX_ERROR_RESILIENT_DEFAULT
  932. #define VPX_ERROR_RESILIENT_DEFAULT 1
  933. #define VPX_ERROR_RESILIENT_PARTITIONS 2
  934. #endif
  935. #define COMMON_OPTIONS \
  936. { "auto-alt-ref", "Enable use of alternate reference " \
  937. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE}, \
  938. { "lag-in-frames", "Number of frames to look ahead for " \
  939. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  940. { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  941. { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  942. { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
  943. { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
  944. { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
  945. { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
  946. { "tune", "Tune the encoding to a specific scenario", OFFSET(tune), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "tune"}, \
  947. { "psnr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_PSNR}, 0, 0, VE, "tune"}, \
  948. { "ssim", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_SSIM}, 0, 0, VE, "tune"}, \
  949. { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  950. { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
  951. { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
  952. { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
  953. { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
  954. { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  955. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
  956. { "partitions", "The frame partitions are independently decodable " \
  957. "by the bool decoder, meaning that partitions can be decoded even " \
  958. "though earlier partitions have been lost. Note that intra predicition" \
  959. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
  960. { "crf", "Select the quality for constant quality mode", offsetof(VPxContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
  961. { "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 }, \
  962. { "drop-threshold", "Frame drop threshold", offsetof(VPxContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE }, \
  963. { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE}, \
  964. { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
  965. { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
  966. #define LEGACY_OPTIONS \
  967. {"speed", "", offsetof(VPxContext, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
  968. {"quality", "", offsetof(VPxContext, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  969. {"vp8flags", "", offsetof(VPxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
  970. {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
  971. {"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"}, \
  972. {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VPxContext, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
  973. {"arnr_strength", "altref noise reduction filter strength", offsetof(VPxContext, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
  974. {"arnr_type", "altref noise reduction filter type", offsetof(VPxContext, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
  975. {"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}, \
  976. #if CONFIG_LIBVPX_VP8_ENCODER
  977. static const AVOption vp8_options[] = {
  978. COMMON_OPTIONS
  979. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE},
  980. LEGACY_OPTIONS
  981. { NULL }
  982. };
  983. #endif
  984. #if CONFIG_LIBVPX_VP9_ENCODER
  985. static const AVOption vp9_options[] = {
  986. COMMON_OPTIONS
  987. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
  988. { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  989. { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
  990. { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
  991. { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_BOOL,{.i64 = -1}, -1, 1, VE},
  992. { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
  993. { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
  994. { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
  995. { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
  996. { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
  997. LEGACY_OPTIONS
  998. { NULL }
  999. };
  1000. #endif
  1001. #undef COMMON_OPTIONS
  1002. #undef LEGACY_OPTIONS
  1003. static const AVCodecDefault defaults[] = {
  1004. { "qmin", "-1" },
  1005. { "qmax", "-1" },
  1006. { "g", "-1" },
  1007. { "keyint_min", "-1" },
  1008. { NULL },
  1009. };
  1010. #if CONFIG_LIBVPX_VP8_ENCODER
  1011. static av_cold int vp8_init(AVCodecContext *avctx)
  1012. {
  1013. return vpx_init(avctx, vpx_codec_vp8_cx());
  1014. }
  1015. static const AVClass class_vp8 = {
  1016. .class_name = "libvpx-vp8 encoder",
  1017. .item_name = av_default_item_name,
  1018. .option = vp8_options,
  1019. .version = LIBAVUTIL_VERSION_INT,
  1020. };
  1021. AVCodec ff_libvpx_vp8_encoder = {
  1022. .name = "libvpx",
  1023. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  1024. .type = AVMEDIA_TYPE_VIDEO,
  1025. .id = AV_CODEC_ID_VP8,
  1026. .priv_data_size = sizeof(VPxContext),
  1027. .init = vp8_init,
  1028. .encode2 = vpx_encode,
  1029. .close = vpx_free,
  1030. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  1031. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
  1032. .priv_class = &class_vp8,
  1033. .defaults = defaults,
  1034. };
  1035. #endif /* CONFIG_LIBVPX_VP8_ENCODER */
  1036. #if CONFIG_LIBVPX_VP9_ENCODER
  1037. static av_cold int vp9_init(AVCodecContext *avctx)
  1038. {
  1039. return vpx_init(avctx, vpx_codec_vp9_cx());
  1040. }
  1041. static const AVClass class_vp9 = {
  1042. .class_name = "libvpx-vp9 encoder",
  1043. .item_name = av_default_item_name,
  1044. .option = vp9_options,
  1045. .version = LIBAVUTIL_VERSION_INT,
  1046. };
  1047. AVCodec ff_libvpx_vp9_encoder = {
  1048. .name = "libvpx-vp9",
  1049. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
  1050. .type = AVMEDIA_TYPE_VIDEO,
  1051. .id = AV_CODEC_ID_VP9,
  1052. .priv_data_size = sizeof(VPxContext),
  1053. .init = vp9_init,
  1054. .encode2 = vpx_encode,
  1055. .close = vpx_free,
  1056. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  1057. .profiles = NULL_IF_CONFIG_SMALL(ff_vp9_profiles),
  1058. .priv_class = &class_vp9,
  1059. .defaults = defaults,
  1060. .init_static_data = ff_vp9_init_static,
  1061. };
  1062. #endif /* CONFIG_LIBVPX_VP9_ENCODER */