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.

1331 lines
52KB

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