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.

889 lines
36KB

  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 "libavutil/base64.h"
  33. #include "libavutil/common.h"
  34. #include "libavutil/intreadwrite.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/opt.h"
  37. /**
  38. * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
  39. * One encoded frame returned from the library.
  40. */
  41. struct FrameListData {
  42. void *buf; /**< compressed data buffer */
  43. size_t sz; /**< length of compressed data */
  44. void *buf_alpha;
  45. size_t sz_alpha;
  46. int64_t pts; /**< time stamp to show frame
  47. (in timebase units) */
  48. unsigned long duration; /**< duration to show frame
  49. (in timebase units) */
  50. uint32_t flags; /**< flags for this frame */
  51. uint64_t sse[4];
  52. int have_sse; /**< true if we have pending sse[] */
  53. uint64_t frame_number;
  54. struct FrameListData *next;
  55. };
  56. typedef struct VP8EncoderContext {
  57. AVClass *class;
  58. struct vpx_codec_ctx encoder;
  59. struct vpx_image rawimg;
  60. struct vpx_codec_ctx encoder_alpha;
  61. struct vpx_image rawimg_alpha;
  62. uint8_t is_alpha;
  63. struct vpx_fixed_buf twopass_stats;
  64. int deadline; //i.e., RT/GOOD/BEST
  65. uint64_t sse[4];
  66. int have_sse; /**< true if we have pending sse[] */
  67. uint64_t frame_number;
  68. struct FrameListData *coded_frame_list;
  69. int cpu_used;
  70. /**
  71. * VP8 specific flags, see VP8F_* below.
  72. */
  73. int flags;
  74. #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
  75. #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
  76. int auto_alt_ref;
  77. int arnr_max_frames;
  78. int arnr_strength;
  79. int arnr_type;
  80. int lag_in_frames;
  81. int error_resilient;
  82. int crf;
  83. int max_intra_rate;
  84. // VP9-only
  85. int lossless;
  86. int tile_columns;
  87. int tile_rows;
  88. int frame_parallel;
  89. int aq_mode;
  90. } VP8Context;
  91. /** String mappings for enum vp8e_enc_control_id */
  92. static const char *const ctlidstr[] = {
  93. [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
  94. [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
  95. [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
  96. [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
  97. [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
  98. [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
  99. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  100. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  101. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  102. [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
  103. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  104. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  105. [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
  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_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
  110. [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
  111. #if CONFIG_LIBVPX_VP9_ENCODER
  112. [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
  113. [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
  114. [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
  115. [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
  116. [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
  117. #endif
  118. };
  119. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  120. {
  121. VP8Context *ctx = avctx->priv_data;
  122. const char *error = vpx_codec_error(&ctx->encoder);
  123. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  124. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  125. if (detail)
  126. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  127. }
  128. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  129. const struct vpx_codec_enc_cfg *cfg)
  130. {
  131. int width = -30;
  132. int level = AV_LOG_DEBUG;
  133. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  134. av_log(avctx, level, "generic settings\n"
  135. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  136. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  137. width, "g_usage:", cfg->g_usage,
  138. width, "g_threads:", cfg->g_threads,
  139. width, "g_profile:", cfg->g_profile,
  140. width, "g_w:", cfg->g_w,
  141. width, "g_h:", cfg->g_h,
  142. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  143. width, "g_error_resilient:", cfg->g_error_resilient,
  144. width, "g_pass:", cfg->g_pass,
  145. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  146. av_log(avctx, level, "rate control settings\n"
  147. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  148. " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
  149. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  150. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  151. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  152. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  153. width, "rc_end_usage:", cfg->rc_end_usage,
  154. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  155. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  156. av_log(avctx, level, "quantizer settings\n"
  157. " %*s%u\n %*s%u\n",
  158. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  159. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  160. av_log(avctx, level, "bitrate tolerance\n"
  161. " %*s%u\n %*s%u\n",
  162. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  163. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  164. av_log(avctx, level, "decoder buffer model\n"
  165. " %*s%u\n %*s%u\n %*s%u\n",
  166. width, "rc_buf_sz:", cfg->rc_buf_sz,
  167. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  168. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  169. av_log(avctx, level, "2 pass rate control settings\n"
  170. " %*s%u\n %*s%u\n %*s%u\n",
  171. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  172. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  173. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  174. av_log(avctx, level, "keyframing settings\n"
  175. " %*s%d\n %*s%u\n %*s%u\n",
  176. width, "kf_mode:", cfg->kf_mode,
  177. width, "kf_min_dist:", cfg->kf_min_dist,
  178. width, "kf_max_dist:", cfg->kf_max_dist);
  179. av_log(avctx, level, "\n");
  180. }
  181. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  182. {
  183. struct FrameListData **p = list;
  184. while (*p)
  185. p = &(*p)->next;
  186. *p = cx_frame;
  187. cx_frame->next = NULL;
  188. }
  189. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  190. {
  191. av_freep(&cx_frame->buf);
  192. if (cx_frame->buf_alpha)
  193. av_freep(&cx_frame->buf_alpha);
  194. av_freep(&cx_frame);
  195. }
  196. static av_cold void free_frame_list(struct FrameListData *list)
  197. {
  198. struct FrameListData *p = list;
  199. while (p) {
  200. list = list->next;
  201. free_coded_frame(p);
  202. p = list;
  203. }
  204. }
  205. static av_cold int codecctl_int(AVCodecContext *avctx,
  206. enum vp8e_enc_control_id id, int val)
  207. {
  208. VP8Context *ctx = avctx->priv_data;
  209. char buf[80];
  210. int width = -30;
  211. int res;
  212. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  213. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  214. res = vpx_codec_control(&ctx->encoder, id, val);
  215. if (res != VPX_CODEC_OK) {
  216. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  217. ctlidstr[id]);
  218. log_encoder_error(avctx, buf);
  219. }
  220. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  221. }
  222. static av_cold int vp8_free(AVCodecContext *avctx)
  223. {
  224. VP8Context *ctx = avctx->priv_data;
  225. vpx_codec_destroy(&ctx->encoder);
  226. if (ctx->is_alpha)
  227. vpx_codec_destroy(&ctx->encoder_alpha);
  228. av_freep(&ctx->twopass_stats.buf);
  229. av_freep(&avctx->coded_frame);
  230. av_freep(&avctx->stats_out);
  231. free_frame_list(ctx->coded_frame_list);
  232. return 0;
  233. }
  234. static av_cold int vpx_init(AVCodecContext *avctx,
  235. const struct vpx_codec_iface *iface)
  236. {
  237. VP8Context *ctx = avctx->priv_data;
  238. struct vpx_codec_enc_cfg enccfg;
  239. struct vpx_codec_enc_cfg enccfg_alpha;
  240. vpx_codec_flags_t flags = (avctx->flags & CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
  241. int res;
  242. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  243. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  244. if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
  245. ctx->is_alpha = 1;
  246. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  247. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  248. vpx_codec_err_to_string(res));
  249. return AVERROR(EINVAL);
  250. }
  251. if(!avctx->bit_rate)
  252. if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
  253. av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
  254. return AVERROR(EINVAL);
  255. }
  256. dump_enc_cfg(avctx, &enccfg);
  257. enccfg.g_w = avctx->width;
  258. enccfg.g_h = avctx->height;
  259. enccfg.g_timebase.num = avctx->time_base.num;
  260. enccfg.g_timebase.den = avctx->time_base.den;
  261. enccfg.g_threads = avctx->thread_count;
  262. enccfg.g_lag_in_frames= ctx->lag_in_frames;
  263. if (avctx->flags & CODEC_FLAG_PASS1)
  264. enccfg.g_pass = VPX_RC_FIRST_PASS;
  265. else if (avctx->flags & CODEC_FLAG_PASS2)
  266. enccfg.g_pass = VPX_RC_LAST_PASS;
  267. else
  268. enccfg.g_pass = VPX_RC_ONE_PASS;
  269. if (avctx->rc_min_rate == avctx->rc_max_rate &&
  270. avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate)
  271. enccfg.rc_end_usage = VPX_CBR;
  272. else if (ctx->crf)
  273. enccfg.rc_end_usage = VPX_CQ;
  274. if (avctx->bit_rate) {
  275. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  276. AV_ROUND_NEAR_INF);
  277. } else {
  278. if (enccfg.rc_end_usage == VPX_CQ) {
  279. enccfg.rc_target_bitrate = 1000000;
  280. } else {
  281. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  282. av_log(avctx, AV_LOG_WARNING,
  283. "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
  284. enccfg.rc_target_bitrate);
  285. }
  286. }
  287. if (avctx->qmin >= 0)
  288. enccfg.rc_min_quantizer = avctx->qmin;
  289. if (avctx->qmax >= 0)
  290. enccfg.rc_max_quantizer = avctx->qmax;
  291. if (enccfg.rc_end_usage == VPX_CQ) {
  292. if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
  293. av_log(avctx, AV_LOG_ERROR,
  294. "CQ level must be between minimum and maximum quantizer value (%d-%d)\n",
  295. enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
  296. return AVERROR(EINVAL);
  297. }
  298. }
  299. enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
  300. //0-100 (0 => CBR, 100 => VBR)
  301. enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
  302. if (avctx->bit_rate)
  303. enccfg.rc_2pass_vbr_minsection_pct =
  304. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  305. if (avctx->rc_max_rate)
  306. enccfg.rc_2pass_vbr_maxsection_pct =
  307. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  308. if (avctx->rc_buffer_size)
  309. enccfg.rc_buf_sz =
  310. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  311. if (avctx->rc_initial_buffer_occupancy)
  312. enccfg.rc_buf_initial_sz =
  313. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  314. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  315. enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
  316. //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
  317. if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
  318. enccfg.kf_min_dist = avctx->keyint_min;
  319. if (avctx->gop_size >= 0)
  320. enccfg.kf_max_dist = avctx->gop_size;
  321. if (enccfg.g_pass == VPX_RC_FIRST_PASS)
  322. enccfg.g_lag_in_frames = 0;
  323. else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
  324. int decode_size;
  325. if (!avctx->stats_in) {
  326. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  327. return AVERROR_INVALIDDATA;
  328. }
  329. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  330. ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
  331. if (!ctx->twopass_stats.buf) {
  332. av_log(avctx, AV_LOG_ERROR,
  333. "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  334. ctx->twopass_stats.sz);
  335. return AVERROR(ENOMEM);
  336. }
  337. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  338. ctx->twopass_stats.sz);
  339. if (decode_size < 0) {
  340. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  341. return AVERROR_INVALIDDATA;
  342. }
  343. ctx->twopass_stats.sz = decode_size;
  344. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  345. }
  346. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  347. complexity playback on low powered devices at the expense of encode
  348. quality. */
  349. if (avctx->profile != FF_PROFILE_UNKNOWN)
  350. enccfg.g_profile = avctx->profile;
  351. enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
  352. dump_enc_cfg(avctx, &enccfg);
  353. /* Construct Encoder Context */
  354. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
  355. if (res != VPX_CODEC_OK) {
  356. log_encoder_error(avctx, "Failed to initialize encoder");
  357. return AVERROR(EINVAL);
  358. }
  359. if (ctx->is_alpha) {
  360. enccfg_alpha = enccfg;
  361. res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
  362. if (res != VPX_CODEC_OK) {
  363. log_encoder_error(avctx, "Failed to initialize alpha encoder");
  364. return AVERROR(EINVAL);
  365. }
  366. }
  367. //codec control failures are currently treated only as warnings
  368. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  369. codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
  370. if (ctx->flags & VP8F_AUTO_ALT_REF)
  371. ctx->auto_alt_ref = 1;
  372. if (ctx->auto_alt_ref >= 0)
  373. codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
  374. if (ctx->arnr_max_frames >= 0)
  375. codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
  376. if (ctx->arnr_strength >= 0)
  377. codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
  378. if (ctx->arnr_type >= 0)
  379. codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
  380. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
  381. if (avctx->codec_id == AV_CODEC_ID_VP8)
  382. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  383. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, avctx->mb_threshold);
  384. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  385. if (ctx->max_intra_rate >= 0)
  386. codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
  387. #if CONFIG_LIBVPX_VP9_ENCODER
  388. if (avctx->codec_id == AV_CODEC_ID_VP9) {
  389. if (ctx->lossless >= 0)
  390. codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
  391. if (ctx->tile_columns >= 0)
  392. codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
  393. if (ctx->tile_rows >= 0)
  394. codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
  395. if (ctx->frame_parallel >= 0)
  396. codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
  397. if (ctx->aq_mode >= 0)
  398. codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
  399. }
  400. #endif
  401. av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
  402. //provide dummy value to initialize wrapper, values will be updated each _encode()
  403. vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  404. (unsigned char*)1);
  405. if (ctx->is_alpha)
  406. vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  407. (unsigned char*)1);
  408. avctx->coded_frame = av_frame_alloc();
  409. if (!avctx->coded_frame) {
  410. av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
  411. vp8_free(avctx);
  412. return AVERROR(ENOMEM);
  413. }
  414. return 0;
  415. }
  416. static inline void cx_pktcpy(struct FrameListData *dst,
  417. const struct vpx_codec_cx_pkt *src,
  418. const struct vpx_codec_cx_pkt *src_alpha,
  419. VP8Context *ctx)
  420. {
  421. dst->pts = src->data.frame.pts;
  422. dst->duration = src->data.frame.duration;
  423. dst->flags = src->data.frame.flags;
  424. dst->sz = src->data.frame.sz;
  425. dst->buf = src->data.frame.buf;
  426. dst->have_sse = 0;
  427. /* For alt-ref frame, don't store PSNR or increment frame_number */
  428. if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
  429. dst->frame_number = ++ctx->frame_number;
  430. dst->have_sse = ctx->have_sse;
  431. if (ctx->have_sse) {
  432. /* associate last-seen SSE to the frame. */
  433. /* Transfers ownership from ctx to dst. */
  434. /* WARNING! This makes the assumption that PSNR_PKT comes
  435. just before the frame it refers to! */
  436. memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
  437. ctx->have_sse = 0;
  438. }
  439. } else {
  440. dst->frame_number = -1; /* sanity marker */
  441. }
  442. if (src_alpha) {
  443. dst->buf_alpha = src_alpha->data.frame.buf;
  444. dst->sz_alpha = src_alpha->data.frame.sz;
  445. }
  446. else {
  447. dst->buf_alpha = NULL;
  448. dst->sz_alpha = 0;
  449. }
  450. }
  451. /**
  452. * Store coded frame information in format suitable for return from encode2().
  453. *
  454. * Write information from @a cx_frame to @a pkt
  455. * @return packet data size on success
  456. * @return a negative AVERROR on error
  457. */
  458. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  459. AVPacket *pkt, AVFrame *coded_frame)
  460. {
  461. int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz);
  462. uint8_t *side_data;
  463. if (ret >= 0) {
  464. memcpy(pkt->data, cx_frame->buf, pkt->size);
  465. pkt->pts = pkt->dts = cx_frame->pts;
  466. coded_frame->pts = cx_frame->pts;
  467. coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  468. if (coded_frame->key_frame) {
  469. coded_frame->pict_type = AV_PICTURE_TYPE_I;
  470. pkt->flags |= AV_PKT_FLAG_KEY;
  471. } else
  472. coded_frame->pict_type = AV_PICTURE_TYPE_P;
  473. if (cx_frame->have_sse) {
  474. int i;
  475. /* Beware of the Y/U/V/all order! */
  476. coded_frame->error[0] = cx_frame->sse[1];
  477. coded_frame->error[1] = cx_frame->sse[2];
  478. coded_frame->error[2] = cx_frame->sse[3];
  479. coded_frame->error[3] = 0; // alpha
  480. for (i = 0; i < 4; ++i) {
  481. avctx->error[i] += coded_frame->error[i];
  482. }
  483. cx_frame->have_sse = 0;
  484. }
  485. if (cx_frame->sz_alpha > 0) {
  486. side_data = av_packet_new_side_data(pkt,
  487. AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
  488. cx_frame->sz_alpha + 8);
  489. if(!side_data) {
  490. av_free_packet(pkt);
  491. av_free(pkt);
  492. return AVERROR(ENOMEM);
  493. }
  494. AV_WB64(side_data, 1);
  495. memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
  496. }
  497. } else {
  498. return ret;
  499. }
  500. return pkt->size;
  501. }
  502. /**
  503. * Queue multiple output frames from the encoder, returning the front-most.
  504. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  505. * the frame queue. Return the head frame if available.
  506. * @return Stored frame size
  507. * @return AVERROR(EINVAL) on output size error
  508. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  509. */
  510. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out,
  511. AVFrame *coded_frame)
  512. {
  513. VP8Context *ctx = avctx->priv_data;
  514. const struct vpx_codec_cx_pkt *pkt;
  515. const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
  516. const void *iter = NULL;
  517. const void *iter_alpha = NULL;
  518. int size = 0;
  519. if (ctx->coded_frame_list) {
  520. struct FrameListData *cx_frame = ctx->coded_frame_list;
  521. /* return the leading frame if we've already begun queueing */
  522. size = storeframe(avctx, cx_frame, pkt_out, coded_frame);
  523. if (size < 0)
  524. return size;
  525. ctx->coded_frame_list = cx_frame->next;
  526. free_coded_frame(cx_frame);
  527. }
  528. /* consume all available output from the encoder before returning. buffers
  529. are only good through the next vpx_codec call */
  530. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
  531. (!ctx->is_alpha ||
  532. (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
  533. switch (pkt->kind) {
  534. case VPX_CODEC_CX_FRAME_PKT:
  535. if (!size) {
  536. struct FrameListData cx_frame;
  537. /* avoid storing the frame when the list is empty and we haven't yet
  538. provided a frame for output */
  539. av_assert0(!ctx->coded_frame_list);
  540. cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
  541. size = storeframe(avctx, &cx_frame, pkt_out, coded_frame);
  542. if (size < 0)
  543. return size;
  544. } else {
  545. struct FrameListData *cx_frame =
  546. av_malloc(sizeof(struct FrameListData));
  547. if (!cx_frame) {
  548. av_log(avctx, AV_LOG_ERROR,
  549. "Frame queue element alloc failed\n");
  550. return AVERROR(ENOMEM);
  551. }
  552. cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
  553. cx_frame->buf = av_malloc(cx_frame->sz);
  554. if (!cx_frame->buf) {
  555. av_log(avctx, AV_LOG_ERROR,
  556. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  557. cx_frame->sz);
  558. av_free(cx_frame);
  559. return AVERROR(ENOMEM);
  560. }
  561. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  562. if (ctx->is_alpha) {
  563. cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
  564. if (!cx_frame->buf_alpha) {
  565. av_log(avctx, AV_LOG_ERROR,
  566. "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
  567. cx_frame->sz_alpha);
  568. av_free(cx_frame);
  569. return AVERROR(ENOMEM);
  570. }
  571. memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
  572. }
  573. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  574. }
  575. break;
  576. case VPX_CODEC_STATS_PKT: {
  577. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  578. int err;
  579. if ((err = av_reallocp(&stats->buf,
  580. stats->sz +
  581. pkt->data.twopass_stats.sz)) < 0) {
  582. stats->sz = 0;
  583. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  584. return err;
  585. }
  586. memcpy((uint8_t*)stats->buf + stats->sz,
  587. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  588. stats->sz += pkt->data.twopass_stats.sz;
  589. break;
  590. }
  591. case VPX_CODEC_PSNR_PKT:
  592. av_assert0(!ctx->have_sse);
  593. ctx->sse[0] = pkt->data.psnr.sse[0];
  594. ctx->sse[1] = pkt->data.psnr.sse[1];
  595. ctx->sse[2] = pkt->data.psnr.sse[2];
  596. ctx->sse[3] = pkt->data.psnr.sse[3];
  597. ctx->have_sse = 1;
  598. break;
  599. case VPX_CODEC_CUSTOM_PKT:
  600. //ignore unsupported/unrecognized packet types
  601. break;
  602. }
  603. }
  604. return size;
  605. }
  606. static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
  607. const AVFrame *frame, int *got_packet)
  608. {
  609. VP8Context *ctx = avctx->priv_data;
  610. struct vpx_image *rawimg = NULL;
  611. struct vpx_image *rawimg_alpha = NULL;
  612. int64_t timestamp = 0;
  613. int res, coded_size;
  614. vpx_enc_frame_flags_t flags = 0;
  615. if (frame) {
  616. rawimg = &ctx->rawimg;
  617. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  618. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  619. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  620. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  621. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  622. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  623. if (ctx->is_alpha) {
  624. uint8_t *u_plane, *v_plane;
  625. rawimg_alpha = &ctx->rawimg_alpha;
  626. rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
  627. u_plane = av_malloc(frame->linesize[1] * frame->height);
  628. memset(u_plane, 0x80, frame->linesize[1] * frame->height);
  629. rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
  630. v_plane = av_malloc(frame->linesize[2] * frame->height);
  631. memset(v_plane, 0x80, frame->linesize[2] * frame->height);
  632. rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
  633. rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
  634. rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
  635. rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
  636. }
  637. timestamp = frame->pts;
  638. if (frame->pict_type == AV_PICTURE_TYPE_I)
  639. flags |= VPX_EFLAG_FORCE_KF;
  640. }
  641. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  642. avctx->ticks_per_frame, flags, ctx->deadline);
  643. if (res != VPX_CODEC_OK) {
  644. log_encoder_error(avctx, "Error encoding frame");
  645. return AVERROR_INVALIDDATA;
  646. }
  647. if (ctx->is_alpha) {
  648. res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
  649. avctx->ticks_per_frame, flags, ctx->deadline);
  650. if (res != VPX_CODEC_OK) {
  651. log_encoder_error(avctx, "Error encoding alpha frame");
  652. return AVERROR_INVALIDDATA;
  653. }
  654. }
  655. coded_size = queue_frames(avctx, pkt, avctx->coded_frame);
  656. if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
  657. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  658. avctx->stats_out = av_malloc(b64_size);
  659. if (!avctx->stats_out) {
  660. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  661. b64_size);
  662. return AVERROR(ENOMEM);
  663. }
  664. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  665. ctx->twopass_stats.sz);
  666. }
  667. if (rawimg_alpha) {
  668. av_free(rawimg_alpha->planes[VPX_PLANE_U]);
  669. av_free(rawimg_alpha->planes[VPX_PLANE_V]);
  670. }
  671. *got_packet = !!coded_size;
  672. return 0;
  673. }
  674. #define OFFSET(x) offsetof(VP8Context, x)
  675. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  676. #ifndef VPX_ERROR_RESILIENT_DEFAULT
  677. #define VPX_ERROR_RESILIENT_DEFAULT 1
  678. #define VPX_ERROR_RESILIENT_PARTITIONS 2
  679. #endif
  680. #define COMMON_OPTIONS \
  681. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
  682. { "auto-alt-ref", "Enable use of alternate reference " \
  683. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE}, \
  684. { "lag-in-frames", "Number of frames to look ahead for " \
  685. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  686. { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  687. { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  688. { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
  689. { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
  690. { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
  691. { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
  692. { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  693. { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
  694. { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
  695. { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
  696. { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
  697. { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
  698. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
  699. { "partitions", "The frame partitions are independently decodable " \
  700. "by the bool decoder, meaning that partitions can be decoded even " \
  701. "though earlier partitions have been lost. Note that intra predicition" \
  702. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
  703. { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE }, \
  704. #define LEGACY_OPTIONS \
  705. {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
  706. {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
  707. {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
  708. {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
  709. {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"}, \
  710. {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
  711. {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
  712. {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
  713. {"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}, \
  714. #if CONFIG_LIBVPX_VP8_ENCODER
  715. static const AVOption vp8_options[] = {
  716. COMMON_OPTIONS
  717. LEGACY_OPTIONS
  718. { NULL }
  719. };
  720. #endif
  721. #if CONFIG_LIBVPX_VP9_ENCODER
  722. static const AVOption vp9_options[] = {
  723. COMMON_OPTIONS
  724. { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  725. { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
  726. { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
  727. { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  728. { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
  729. { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" }, \
  730. { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" }, \
  731. { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" }, \
  732. { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" }, \
  733. LEGACY_OPTIONS
  734. { NULL }
  735. };
  736. #endif
  737. #undef COMMON_OPTIONS
  738. #undef LEGACY_OPTIONS
  739. static const AVCodecDefault defaults[] = {
  740. { "qmin", "-1" },
  741. { "qmax", "-1" },
  742. { "g", "-1" },
  743. { "keyint_min", "-1" },
  744. { NULL },
  745. };
  746. #if CONFIG_LIBVPX_VP8_ENCODER
  747. static av_cold int vp8_init(AVCodecContext *avctx)
  748. {
  749. return vpx_init(avctx, &vpx_codec_vp8_cx_algo);
  750. }
  751. static const AVClass class_vp8 = {
  752. .class_name = "libvpx-vp8 encoder",
  753. .item_name = av_default_item_name,
  754. .option = vp8_options,
  755. .version = LIBAVUTIL_VERSION_INT,
  756. };
  757. AVCodec ff_libvpx_vp8_encoder = {
  758. .name = "libvpx",
  759. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  760. .type = AVMEDIA_TYPE_VIDEO,
  761. .id = AV_CODEC_ID_VP8,
  762. .priv_data_size = sizeof(VP8Context),
  763. .init = vp8_init,
  764. .encode2 = vp8_encode,
  765. .close = vp8_free,
  766. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  767. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
  768. .priv_class = &class_vp8,
  769. .defaults = defaults,
  770. };
  771. #endif /* CONFIG_LIBVPX_VP8_ENCODER */
  772. #if CONFIG_LIBVPX_VP9_ENCODER
  773. static av_cold int vp9_init(AVCodecContext *avctx)
  774. {
  775. return vpx_init(avctx, &vpx_codec_vp9_cx_algo);
  776. }
  777. static const AVClass class_vp9 = {
  778. .class_name = "libvpx-vp9 encoder",
  779. .item_name = av_default_item_name,
  780. .option = vp9_options,
  781. .version = LIBAVUTIL_VERSION_INT,
  782. };
  783. AVCodec ff_libvpx_vp9_encoder = {
  784. .name = "libvpx-vp9",
  785. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
  786. .type = AVMEDIA_TYPE_VIDEO,
  787. .id = AV_CODEC_ID_VP9,
  788. .priv_data_size = sizeof(VP8Context),
  789. .init = vp9_init,
  790. .encode2 = vp8_encode,
  791. .close = vp8_free,
  792. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  793. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  794. .priv_class = &class_vp9,
  795. .defaults = defaults,
  796. .init_static_data = ff_vp9_init_static,
  797. };
  798. #endif /* CONFIG_LIBVPX_VP9_ENCODER */