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.

1581 lines
61KB

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