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.

1146 lines
45KB

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