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.

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