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.

587 lines
23KB

  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 "libavutil/base64.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/mathematics.h"
  32. /**
  33. * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
  34. * One encoded frame returned from the library.
  35. */
  36. struct FrameListData {
  37. void *buf; /**< compressed data buffer */
  38. size_t sz; /**< length of compressed data */
  39. int64_t pts; /**< time stamp to show frame
  40. (in timebase units) */
  41. unsigned long duration; /**< duration to show frame
  42. (in timebase units) */
  43. uint32_t flags; /**< flags for this frame */
  44. struct FrameListData *next;
  45. };
  46. typedef struct VP8EncoderContext {
  47. AVClass *av_class;
  48. struct vpx_codec_ctx encoder;
  49. struct vpx_image rawimg;
  50. struct vpx_fixed_buf twopass_stats;
  51. int deadline; //i.e., RT/GOOD/BEST
  52. struct FrameListData *coded_frame_list;
  53. int cpuused;
  54. /**
  55. * VP8 specific flags, see VP8F_* below.
  56. */
  57. int flags;
  58. #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
  59. #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
  60. int arnr_max_frames;
  61. int arnr_strength;
  62. int arnr_type;
  63. int rc_lookahead;
  64. int crf;
  65. } VP8Context;
  66. #define V AV_OPT_FLAG_VIDEO_PARAM
  67. #define E AV_OPT_FLAG_ENCODING_PARAM
  68. static const AVOption options[]={
  69. {"speed", "", offsetof(VP8Context, cpuused), FF_OPT_TYPE_INT, {.dbl = 3}, -16, 16, V|E},
  70. {"quality", "", offsetof(VP8Context, deadline), FF_OPT_TYPE_INT, {.dbl = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, V|E, "quality"},
  71. {"best", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = VPX_DL_BEST_QUALITY}, INT_MIN, INT_MAX, V|E, "quality"},
  72. {"good", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, V|E, "quality"},
  73. {"realtime", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = VPX_DL_REALTIME}, INT_MIN, INT_MAX, V|E, "quality"},
  74. {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.dbl = 0}, 0, UINT_MAX, V|E, "flags"},
  75. {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, V|E, "flags"},
  76. {"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, V|E, "flags"},
  77. {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 15, V|E},
  78. {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), FF_OPT_TYPE_INT, {.dbl = 3}, 0, 6, V|E},
  79. {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), FF_OPT_TYPE_INT, {.dbl = 3}, 1, 3, V|E},
  80. #if FF_API_X264_GLOBAL_OPTS
  81. {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, rc_lookahead), FF_OPT_TYPE_INT, {.dbl = -1}, -1, 25, V|E},
  82. {"crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), FF_OPT_TYPE_INT, {.dbl = -1}, -1, 63, V|E},
  83. #else
  84. {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, rc_lookahead), FF_OPT_TYPE_INT, {.dbl = 25}, 0, 25, V|E},
  85. {"crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 63, V|E},
  86. #endif
  87. {NULL}
  88. };
  89. static const AVClass class = { "libvpx", av_default_item_name, options, LIBAVUTIL_VERSION_INT };
  90. #undef V
  91. #undef E
  92. /** String mappings for enum vp8e_enc_control_id */
  93. static const char *ctlidstr[] = {
  94. [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
  95. [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
  96. [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
  97. [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
  98. [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
  99. [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
  100. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  101. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  102. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  103. [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
  104. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  105. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  106. [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
  107. [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
  108. [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
  109. [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
  110. [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
  111. };
  112. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  113. {
  114. VP8Context *ctx = avctx->priv_data;
  115. const char *error = vpx_codec_error(&ctx->encoder);
  116. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  117. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  118. if (detail)
  119. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  120. }
  121. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  122. const struct vpx_codec_enc_cfg *cfg)
  123. {
  124. int width = -30;
  125. int level = AV_LOG_DEBUG;
  126. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  127. av_log(avctx, level, "generic settings\n"
  128. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  129. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  130. width, "g_usage:", cfg->g_usage,
  131. width, "g_threads:", cfg->g_threads,
  132. width, "g_profile:", cfg->g_profile,
  133. width, "g_w:", cfg->g_w,
  134. width, "g_h:", cfg->g_h,
  135. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  136. width, "g_error_resilient:", cfg->g_error_resilient,
  137. width, "g_pass:", cfg->g_pass,
  138. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  139. av_log(avctx, level, "rate control settings\n"
  140. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  141. " %*s%d\n %*s%p(%zu)\n %*s%u\n",
  142. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  143. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  144. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  145. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  146. width, "rc_end_usage:", cfg->rc_end_usage,
  147. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  148. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  149. av_log(avctx, level, "quantizer settings\n"
  150. " %*s%u\n %*s%u\n",
  151. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  152. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  153. av_log(avctx, level, "bitrate tolerance\n"
  154. " %*s%u\n %*s%u\n",
  155. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  156. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  157. av_log(avctx, level, "decoder buffer model\n"
  158. " %*s%u\n %*s%u\n %*s%u\n",
  159. width, "rc_buf_sz:", cfg->rc_buf_sz,
  160. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  161. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  162. av_log(avctx, level, "2 pass rate control settings\n"
  163. " %*s%u\n %*s%u\n %*s%u\n",
  164. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  165. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  166. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  167. av_log(avctx, level, "keyframing settings\n"
  168. " %*s%d\n %*s%u\n %*s%u\n",
  169. width, "kf_mode:", cfg->kf_mode,
  170. width, "kf_min_dist:", cfg->kf_min_dist,
  171. width, "kf_max_dist:", cfg->kf_max_dist);
  172. av_log(avctx, level, "\n");
  173. }
  174. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  175. {
  176. struct FrameListData **p = list;
  177. while (*p != NULL)
  178. p = &(*p)->next;
  179. *p = cx_frame;
  180. cx_frame->next = NULL;
  181. }
  182. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  183. {
  184. av_freep(&cx_frame->buf);
  185. av_freep(&cx_frame);
  186. }
  187. static av_cold void free_frame_list(struct FrameListData *list)
  188. {
  189. struct FrameListData *p = list;
  190. while (p) {
  191. list = list->next;
  192. free_coded_frame(p);
  193. p = list;
  194. }
  195. }
  196. static av_cold int codecctl_int(AVCodecContext *avctx,
  197. enum vp8e_enc_control_id id, int val)
  198. {
  199. VP8Context *ctx = avctx->priv_data;
  200. char buf[80];
  201. int width = -30;
  202. int res;
  203. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  204. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  205. res = vpx_codec_control(&ctx->encoder, id, val);
  206. if (res != VPX_CODEC_OK) {
  207. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  208. ctlidstr[id]);
  209. log_encoder_error(avctx, buf);
  210. }
  211. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  212. }
  213. static av_cold int vp8_free(AVCodecContext *avctx)
  214. {
  215. VP8Context *ctx = avctx->priv_data;
  216. vpx_codec_destroy(&ctx->encoder);
  217. av_freep(&ctx->twopass_stats.buf);
  218. av_freep(&avctx->coded_frame);
  219. av_freep(&avctx->stats_out);
  220. free_frame_list(ctx->coded_frame_list);
  221. return 0;
  222. }
  223. static av_cold int vp8_init(AVCodecContext *avctx)
  224. {
  225. VP8Context *ctx = avctx->priv_data;
  226. const struct vpx_codec_iface *iface = &vpx_codec_vp8_cx_algo;
  227. struct vpx_codec_enc_cfg enccfg;
  228. int res;
  229. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  230. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  231. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  232. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  233. vpx_codec_err_to_string(res));
  234. return AVERROR(EINVAL);
  235. }
  236. dump_enc_cfg(avctx, &enccfg);
  237. enccfg.g_w = avctx->width;
  238. enccfg.g_h = avctx->height;
  239. enccfg.g_timebase.num = avctx->time_base.num;
  240. enccfg.g_timebase.den = avctx->time_base.den;
  241. enccfg.g_threads = avctx->thread_count;
  242. #if FF_API_X264_GLOBAL_OPTS
  243. enccfg.g_lag_in_frames= FFMIN(avctx->rc_lookahead, 25); //0-25, avoids init failure
  244. if (ctx->rc_lookahead >= 0)
  245. enccfg.g_lag_in_frames= ctx->rc_lookahead;
  246. #else
  247. enccfg.g_lag_in_frames= ctx->rc_lookahead;
  248. #endif
  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)
  257. enccfg.rc_end_usage = VPX_CBR;
  258. #if FF_API_X264_GLOBAL_OPTS
  259. else if (avctx->crf || ctx->crf > 0)
  260. #else
  261. else if (ctx->crf)
  262. #endif
  263. enccfg.rc_end_usage = VPX_CQ;
  264. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  265. AV_ROUND_NEAR_INF);
  266. enccfg.rc_min_quantizer = avctx->qmin;
  267. enccfg.rc_max_quantizer = avctx->qmax;
  268. enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
  269. //0-100 (0 => CBR, 100 => VBR)
  270. enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
  271. enccfg.rc_2pass_vbr_minsection_pct =
  272. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  273. if (avctx->rc_max_rate)
  274. enccfg.rc_2pass_vbr_maxsection_pct =
  275. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  276. if (avctx->rc_buffer_size)
  277. enccfg.rc_buf_sz =
  278. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  279. if (avctx->rc_initial_buffer_occupancy)
  280. enccfg.rc_buf_initial_sz =
  281. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  282. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  283. enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
  284. //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
  285. if (avctx->keyint_min == avctx->gop_size)
  286. enccfg.kf_min_dist = avctx->keyint_min;
  287. enccfg.kf_max_dist = avctx->gop_size;
  288. if (enccfg.g_pass == VPX_RC_FIRST_PASS)
  289. enccfg.g_lag_in_frames = 0;
  290. else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
  291. int decode_size;
  292. if (!avctx->stats_in) {
  293. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  294. return AVERROR_INVALIDDATA;
  295. }
  296. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  297. ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
  298. if (!ctx->twopass_stats.buf) {
  299. av_log(avctx, AV_LOG_ERROR,
  300. "Stat buffer alloc (%zu bytes) failed\n",
  301. ctx->twopass_stats.sz);
  302. return AVERROR(ENOMEM);
  303. }
  304. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  305. ctx->twopass_stats.sz);
  306. if (decode_size < 0) {
  307. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  308. return AVERROR_INVALIDDATA;
  309. }
  310. ctx->twopass_stats.sz = decode_size;
  311. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  312. }
  313. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  314. complexity playback on low powered devices at the expense of encode
  315. quality. */
  316. if (avctx->profile != FF_PROFILE_UNKNOWN)
  317. enccfg.g_profile = avctx->profile;
  318. enccfg.g_error_resilient = ctx->flags & VP8F_ERROR_RESILIENT;
  319. dump_enc_cfg(avctx, &enccfg);
  320. /* Construct Encoder Context */
  321. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
  322. if (res != VPX_CODEC_OK) {
  323. log_encoder_error(avctx, "Failed to initialize encoder");
  324. return AVERROR(EINVAL);
  325. }
  326. //codec control failures are currently treated only as warnings
  327. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  328. codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpuused);
  329. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
  330. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  331. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, avctx->mb_threshold);
  332. #if FF_API_X264_GLOBAL_OPTS
  333. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, (int)avctx->crf);
  334. if (ctx->crf >= 0)
  335. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  336. #else
  337. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  338. #endif
  339. codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, !!(ctx->flags & VP8F_AUTO_ALT_REF));
  340. codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
  341. codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
  342. codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
  343. av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
  344. //provide dummy value to initialize wrapper, values will be updated each _encode()
  345. vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  346. (unsigned char*)1);
  347. avctx->coded_frame = avcodec_alloc_frame();
  348. if (!avctx->coded_frame) {
  349. av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
  350. vp8_free(avctx);
  351. return AVERROR(ENOMEM);
  352. }
  353. return 0;
  354. }
  355. static inline void cx_pktcpy(struct FrameListData *dst,
  356. const struct vpx_codec_cx_pkt *src)
  357. {
  358. dst->pts = src->data.frame.pts;
  359. dst->duration = src->data.frame.duration;
  360. dst->flags = src->data.frame.flags;
  361. dst->sz = src->data.frame.sz;
  362. dst->buf = src->data.frame.buf;
  363. }
  364. /**
  365. * Store coded frame information in format suitable for return from encode().
  366. *
  367. * Write buffer information from @a cx_frame to @a buf & @a buf_size.
  368. * Timing/frame details to @a coded_frame.
  369. * @return Frame size written to @a buf on success
  370. * @return AVERROR(EINVAL) on error
  371. */
  372. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  373. uint8_t *buf, int buf_size, AVFrame *coded_frame)
  374. {
  375. if ((int) cx_frame->sz <= buf_size) {
  376. buf_size = cx_frame->sz;
  377. memcpy(buf, cx_frame->buf, buf_size);
  378. coded_frame->pts = cx_frame->pts;
  379. coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  380. if (coded_frame->key_frame)
  381. coded_frame->pict_type = AV_PICTURE_TYPE_I;
  382. else
  383. coded_frame->pict_type = AV_PICTURE_TYPE_P;
  384. } else {
  385. av_log(avctx, AV_LOG_ERROR,
  386. "Compressed frame larger than storage provided! (%zu/%d)\n",
  387. cx_frame->sz, buf_size);
  388. return AVERROR(EINVAL);
  389. }
  390. return buf_size;
  391. }
  392. /**
  393. * Queue multiple output frames from the encoder, returning the front-most.
  394. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  395. * the frame queue. Return the head frame if available.
  396. * @return Stored frame size
  397. * @return AVERROR(EINVAL) on output size error
  398. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  399. */
  400. static int queue_frames(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  401. AVFrame *coded_frame)
  402. {
  403. VP8Context *ctx = avctx->priv_data;
  404. const struct vpx_codec_cx_pkt *pkt;
  405. const void *iter = NULL;
  406. int size = 0;
  407. if (ctx->coded_frame_list) {
  408. struct FrameListData *cx_frame = ctx->coded_frame_list;
  409. /* return the leading frame if we've already begun queueing */
  410. size = storeframe(avctx, cx_frame, buf, buf_size, coded_frame);
  411. if (size < 0)
  412. return AVERROR(EINVAL);
  413. ctx->coded_frame_list = cx_frame->next;
  414. free_coded_frame(cx_frame);
  415. }
  416. /* consume all available output from the encoder before returning. buffers
  417. are only good through the next vpx_codec call */
  418. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
  419. switch (pkt->kind) {
  420. case VPX_CODEC_CX_FRAME_PKT:
  421. if (!size) {
  422. struct FrameListData cx_frame;
  423. /* avoid storing the frame when the list is empty and we haven't yet
  424. provided a frame for output */
  425. assert(!ctx->coded_frame_list);
  426. cx_pktcpy(&cx_frame, pkt);
  427. size = storeframe(avctx, &cx_frame, buf, buf_size, coded_frame);
  428. if (size < 0)
  429. return AVERROR(EINVAL);
  430. } else {
  431. struct FrameListData *cx_frame =
  432. av_malloc(sizeof(struct FrameListData));
  433. if (!cx_frame) {
  434. av_log(avctx, AV_LOG_ERROR,
  435. "Frame queue element alloc failed\n");
  436. return AVERROR(ENOMEM);
  437. }
  438. cx_pktcpy(cx_frame, pkt);
  439. cx_frame->buf = av_malloc(cx_frame->sz);
  440. if (!cx_frame->buf) {
  441. av_log(avctx, AV_LOG_ERROR,
  442. "Data buffer alloc (%zu bytes) failed\n",
  443. cx_frame->sz);
  444. return AVERROR(ENOMEM);
  445. }
  446. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  447. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  448. }
  449. break;
  450. case VPX_CODEC_STATS_PKT: {
  451. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  452. stats->buf = av_realloc(stats->buf,
  453. stats->sz + pkt->data.twopass_stats.sz);
  454. if (!stats->buf) {
  455. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  456. return AVERROR(ENOMEM);
  457. }
  458. memcpy((uint8_t*)stats->buf + stats->sz,
  459. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  460. stats->sz += pkt->data.twopass_stats.sz;
  461. break;
  462. }
  463. case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
  464. case VPX_CODEC_CUSTOM_PKT:
  465. //ignore unsupported/unrecognized packet types
  466. break;
  467. }
  468. }
  469. return size;
  470. }
  471. static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  472. void *data)
  473. {
  474. VP8Context *ctx = avctx->priv_data;
  475. AVFrame *frame = data;
  476. struct vpx_image *rawimg = NULL;
  477. int64_t timestamp = 0;
  478. int res, coded_size;
  479. if (frame) {
  480. rawimg = &ctx->rawimg;
  481. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  482. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  483. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  484. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  485. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  486. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  487. timestamp = frame->pts;
  488. }
  489. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  490. avctx->ticks_per_frame, 0, ctx->deadline);
  491. if (res != VPX_CODEC_OK) {
  492. log_encoder_error(avctx, "Error encoding frame");
  493. return AVERROR_INVALIDDATA;
  494. }
  495. coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
  496. if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
  497. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  498. avctx->stats_out = av_malloc(b64_size);
  499. if (!avctx->stats_out) {
  500. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  501. b64_size);
  502. return AVERROR(ENOMEM);
  503. }
  504. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  505. ctx->twopass_stats.sz);
  506. }
  507. return coded_size;
  508. }
  509. AVCodec ff_libvpx_encoder = {
  510. .name = "libvpx",
  511. .type = AVMEDIA_TYPE_VIDEO,
  512. .id = CODEC_ID_VP8,
  513. .priv_data_size = sizeof(VP8Context),
  514. .init = vp8_init,
  515. .encode = vp8_encode,
  516. .close = vp8_free,
  517. .capabilities = CODEC_CAP_DELAY,
  518. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  519. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  520. .priv_class= &class,
  521. };