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.

881 lines
35KB

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