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.

489 lines
18KB

  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. /**
  31. * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
  32. * One encoded frame returned from the library.
  33. */
  34. struct FrameListData {
  35. void *buf; /**≤ compressed data buffer */
  36. size_t sz; /**≤ length of compressed data */
  37. int64_t pts; /**≤ time stamp to show frame
  38. (in timebase units) */
  39. unsigned long duration; /**≤ duration to show frame
  40. (in timebase units) */
  41. uint32_t flags; /**≤ flags for this frame */
  42. struct FrameListData *next;
  43. };
  44. typedef struct VP8EncoderContext {
  45. struct vpx_codec_ctx encoder;
  46. struct vpx_image rawimg;
  47. struct vpx_fixed_buf twopass_stats;
  48. unsigned long deadline; //i.e., RT/GOOD/BEST
  49. struct FrameListData *coded_frame_list;
  50. } VP8Context;
  51. /** String mappings for enum vp8e_enc_control_id */
  52. static const char *ctlidstr[] = {
  53. [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
  54. [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
  55. [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
  56. [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
  57. [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
  58. [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
  59. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  60. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  61. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  62. [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
  63. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  64. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  65. [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
  66. [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
  67. [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
  68. [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
  69. };
  70. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  71. {
  72. VP8Context *ctx = avctx->priv_data;
  73. const char *error = vpx_codec_error(&ctx->encoder);
  74. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  75. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  76. if (detail)
  77. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  78. }
  79. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  80. const struct vpx_codec_enc_cfg *cfg)
  81. {
  82. int width = -30;
  83. int level = AV_LOG_DEBUG;
  84. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  85. av_log(avctx, level, "generic settings\n"
  86. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  87. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  88. width, "g_usage:", cfg->g_usage,
  89. width, "g_threads:", cfg->g_threads,
  90. width, "g_profile:", cfg->g_profile,
  91. width, "g_w:", cfg->g_w,
  92. width, "g_h:", cfg->g_h,
  93. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  94. width, "g_error_resilient:", cfg->g_error_resilient,
  95. width, "g_pass:", cfg->g_pass,
  96. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  97. av_log(avctx, level, "rate control settings\n"
  98. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  99. " %*s%d\n %*s%p(%zu)\n %*s%u\n",
  100. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  101. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  102. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  103. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  104. width, "rc_end_usage:", cfg->rc_end_usage,
  105. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  106. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  107. av_log(avctx, level, "quantizer settings\n"
  108. " %*s%u\n %*s%u\n",
  109. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  110. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  111. av_log(avctx, level, "bitrate tolerance\n"
  112. " %*s%u\n %*s%u\n",
  113. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  114. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  115. av_log(avctx, level, "decoder buffer model\n"
  116. " %*s%u\n %*s%u\n %*s%u\n",
  117. width, "rc_buf_sz:", cfg->rc_buf_sz,
  118. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  119. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  120. av_log(avctx, level, "2 pass rate control settings\n"
  121. " %*s%u\n %*s%u\n %*s%u\n",
  122. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  123. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  124. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  125. av_log(avctx, level, "keyframing settings\n"
  126. " %*s%d\n %*s%u\n %*s%u\n",
  127. width, "kf_mode:", cfg->kf_mode,
  128. width, "kf_min_dist:", cfg->kf_min_dist,
  129. width, "kf_max_dist:", cfg->kf_max_dist);
  130. av_log(avctx, level, "\n");
  131. }
  132. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  133. {
  134. struct FrameListData **p = list;
  135. while (*p != NULL)
  136. p = &(*p)->next;
  137. *p = cx_frame;
  138. cx_frame->next = NULL;
  139. }
  140. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  141. {
  142. av_freep(&cx_frame->buf);
  143. av_freep(&cx_frame);
  144. }
  145. static av_cold void free_frame_list(struct FrameListData *list)
  146. {
  147. struct FrameListData *p = list;
  148. while (p) {
  149. list = list->next;
  150. free_coded_frame(p);
  151. p = list;
  152. }
  153. }
  154. static av_cold int codecctl_int(AVCodecContext *avctx,
  155. enum vp8e_enc_control_id id, int val)
  156. {
  157. VP8Context *ctx = avctx->priv_data;
  158. char buf[80];
  159. int width = -30;
  160. int res;
  161. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  162. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  163. res = vpx_codec_control(&ctx->encoder, id, val);
  164. if (res != VPX_CODEC_OK) {
  165. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  166. ctlidstr[id]);
  167. log_encoder_error(avctx, buf);
  168. }
  169. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  170. }
  171. static av_cold int vp8_free(AVCodecContext *avctx)
  172. {
  173. VP8Context *ctx = avctx->priv_data;
  174. vpx_codec_destroy(&ctx->encoder);
  175. av_freep(&ctx->twopass_stats.buf);
  176. av_freep(&avctx->coded_frame);
  177. av_freep(&avctx->stats_out);
  178. free_frame_list(ctx->coded_frame_list);
  179. return 0;
  180. }
  181. static av_cold int vp8_init(AVCodecContext *avctx)
  182. {
  183. VP8Context *ctx = avctx->priv_data;
  184. const struct vpx_codec_iface *iface = &vpx_codec_vp8_cx_algo;
  185. int cpuused = 3;
  186. struct vpx_codec_enc_cfg enccfg;
  187. int res;
  188. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  189. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  190. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  191. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  192. vpx_codec_err_to_string(res));
  193. return AVERROR(EINVAL);
  194. }
  195. dump_enc_cfg(avctx, &enccfg);
  196. enccfg.g_w = avctx->width;
  197. enccfg.g_h = avctx->height;
  198. enccfg.g_timebase.num = avctx->time_base.num;
  199. enccfg.g_timebase.den = avctx->time_base.den;
  200. enccfg.g_threads = avctx->thread_count;
  201. if (avctx->flags & CODEC_FLAG_PASS1)
  202. enccfg.g_pass = VPX_RC_FIRST_PASS;
  203. else if (avctx->flags & CODEC_FLAG_PASS2)
  204. enccfg.g_pass = VPX_RC_LAST_PASS;
  205. else
  206. enccfg.g_pass = VPX_RC_ONE_PASS;
  207. if (avctx->rc_min_rate == avctx->rc_max_rate &&
  208. avctx->rc_min_rate == avctx->bit_rate)
  209. enccfg.rc_end_usage = VPX_CBR;
  210. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  211. AV_ROUND_NEAR_INF);
  212. //convert [1,51] -> [0,63]
  213. enccfg.rc_min_quantizer = ((avctx->qmin * 5 + 1) >> 2) - 1;
  214. enccfg.rc_max_quantizer = ((avctx->qmax * 5 + 1) >> 2) - 1;
  215. enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
  216. //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
  217. if (avctx->keyint_min == avctx->gop_size)
  218. enccfg.kf_min_dist = avctx->keyint_min;
  219. enccfg.kf_max_dist = avctx->gop_size;
  220. if (enccfg.g_pass == VPX_RC_FIRST_PASS)
  221. enccfg.g_lag_in_frames = 0;
  222. else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
  223. int decode_size;
  224. if (!avctx->stats_in) {
  225. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  226. return AVERROR_INVALIDDATA;
  227. }
  228. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  229. ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
  230. if (!ctx->twopass_stats.buf) {
  231. av_log(avctx, AV_LOG_ERROR,
  232. "Stat buffer alloc (%zu bytes) failed\n",
  233. ctx->twopass_stats.sz);
  234. return AVERROR(ENOMEM);
  235. }
  236. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  237. ctx->twopass_stats.sz);
  238. if (decode_size < 0) {
  239. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  240. return AVERROR_INVALIDDATA;
  241. }
  242. ctx->twopass_stats.sz = decode_size;
  243. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  244. }
  245. ctx->deadline = VPX_DL_GOOD_QUALITY;
  246. dump_enc_cfg(avctx, &enccfg);
  247. /* Construct Encoder Context */
  248. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
  249. if (res != VPX_CODEC_OK) {
  250. log_encoder_error(avctx, "Failed to initialize encoder");
  251. return AVERROR(EINVAL);
  252. }
  253. //codec control failures are currently treated only as warnings
  254. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  255. codecctl_int(avctx, VP8E_SET_CPUUSED, cpuused);
  256. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
  257. //provide dummy value to initialize wrapper, values will be updated each _encode()
  258. vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  259. (unsigned char*)1);
  260. avctx->coded_frame = avcodec_alloc_frame();
  261. if (!avctx->coded_frame) {
  262. av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
  263. vp8_free(avctx);
  264. return AVERROR(ENOMEM);
  265. }
  266. return 0;
  267. }
  268. static inline void cx_pktcpy(struct FrameListData *dst,
  269. const struct vpx_codec_cx_pkt *src)
  270. {
  271. dst->pts = src->data.frame.pts;
  272. dst->duration = src->data.frame.duration;
  273. dst->flags = src->data.frame.flags;
  274. dst->sz = src->data.frame.sz;
  275. dst->buf = src->data.frame.buf;
  276. }
  277. /**
  278. * Store coded frame information in format suitable for return from encode().
  279. *
  280. * Write buffer information from @a cx_frame to @a buf & @a buf_size.
  281. * Timing/frame details to @a coded_frame.
  282. * @return Frame size written to @a buf on success
  283. * @return AVERROR(EINVAL) on error
  284. */
  285. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  286. uint8_t *buf, int buf_size, AVFrame *coded_frame)
  287. {
  288. if ((int) cx_frame->sz <= buf_size) {
  289. buf_size = cx_frame->sz;
  290. memcpy(buf, cx_frame->buf, buf_size);
  291. coded_frame->pts = cx_frame->pts;
  292. coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  293. if (coded_frame->key_frame)
  294. coded_frame->pict_type = FF_I_TYPE;
  295. else
  296. coded_frame->pict_type = FF_P_TYPE;
  297. } else {
  298. av_log(avctx, AV_LOG_ERROR,
  299. "Compressed frame larger than storage provided! (%zu/%d)\n",
  300. cx_frame->sz, buf_size);
  301. return AVERROR(EINVAL);
  302. }
  303. return buf_size;
  304. }
  305. /**
  306. * Queue multiple output frames from the encoder, returning the front-most.
  307. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  308. * the frame queue. Return the head frame if available.
  309. * @return Stored frame size
  310. * @return AVERROR(EINVAL) on output size error
  311. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  312. */
  313. static int queue_frames(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  314. AVFrame *coded_frame)
  315. {
  316. VP8Context *ctx = avctx->priv_data;
  317. const struct vpx_codec_cx_pkt *pkt;
  318. const void *iter = NULL;
  319. int size = 0;
  320. if (ctx->coded_frame_list) {
  321. struct FrameListData *cx_frame = ctx->coded_frame_list;
  322. /* return the leading frame if we've already begun queueing */
  323. size = storeframe(avctx, cx_frame, buf, buf_size, coded_frame);
  324. if (size < 0)
  325. return AVERROR(EINVAL);
  326. ctx->coded_frame_list = cx_frame->next;
  327. free_coded_frame(cx_frame);
  328. }
  329. /* consume all available output from the encoder before returning. buffers
  330. are only good through the next vpx_codec call */
  331. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
  332. switch (pkt->kind) {
  333. case VPX_CODEC_CX_FRAME_PKT:
  334. if (!size) {
  335. struct FrameListData cx_frame;
  336. /* avoid storing the frame when the list is empty and we haven't yet
  337. provided a frame for output */
  338. assert(!ctx->coded_frame_list);
  339. cx_pktcpy(&cx_frame, pkt);
  340. size = storeframe(avctx, &cx_frame, buf, buf_size, coded_frame);
  341. if (size < 0)
  342. return AVERROR(EINVAL);
  343. } else {
  344. struct FrameListData *cx_frame =
  345. av_malloc(sizeof(struct FrameListData));
  346. if (!cx_frame) {
  347. av_log(avctx, AV_LOG_ERROR,
  348. "Frame queue element alloc failed\n");
  349. return AVERROR(ENOMEM);
  350. }
  351. cx_pktcpy(cx_frame, pkt);
  352. cx_frame->buf = av_malloc(cx_frame->sz);
  353. if (!cx_frame->buf) {
  354. av_log(avctx, AV_LOG_ERROR,
  355. "Data buffer alloc (%zu bytes) failed\n",
  356. cx_frame->sz);
  357. return AVERROR(ENOMEM);
  358. }
  359. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  360. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  361. }
  362. break;
  363. case VPX_CODEC_STATS_PKT: {
  364. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  365. stats->buf = av_realloc(stats->buf,
  366. stats->sz + pkt->data.twopass_stats.sz);
  367. if (!stats->buf) {
  368. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  369. return AVERROR(ENOMEM);
  370. }
  371. memcpy((uint8_t*)stats->buf + stats->sz,
  372. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  373. stats->sz += pkt->data.twopass_stats.sz;
  374. break;
  375. }
  376. case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
  377. case VPX_CODEC_CUSTOM_PKT:
  378. //ignore unsupported/unrecognized packet types
  379. break;
  380. }
  381. }
  382. return size;
  383. }
  384. static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  385. void *data)
  386. {
  387. VP8Context *ctx = avctx->priv_data;
  388. AVFrame *frame = data;
  389. struct vpx_image *rawimg = NULL;
  390. int64_t timestamp = 0;
  391. int res, coded_size;
  392. if (frame) {
  393. rawimg = &ctx->rawimg;
  394. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  395. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  396. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  397. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  398. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  399. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  400. timestamp = frame->pts;
  401. }
  402. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  403. avctx->ticks_per_frame, 0, ctx->deadline);
  404. if (res != VPX_CODEC_OK) {
  405. log_encoder_error(avctx, "Error encoding frame");
  406. return AVERROR_INVALIDDATA;
  407. }
  408. coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
  409. if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
  410. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  411. avctx->stats_out = av_malloc(b64_size);
  412. if (!avctx->stats_out) {
  413. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  414. b64_size);
  415. return AVERROR(ENOMEM);
  416. }
  417. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  418. ctx->twopass_stats.sz);
  419. }
  420. return coded_size;
  421. }
  422. AVCodec libvpx_encoder = {
  423. "libvpx",
  424. AVMEDIA_TYPE_VIDEO,
  425. CODEC_ID_VP8,
  426. sizeof(VP8Context),
  427. vp8_init,
  428. vp8_encode,
  429. vp8_free,
  430. NULL,
  431. CODEC_CAP_DELAY,
  432. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  433. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  434. };