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.

847 lines
34KB

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