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.

494 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. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  247. complexity playback on low powered devices at the expense of encode
  248. quality. */
  249. if (avctx->profile != FF_PROFILE_UNKNOWN)
  250. enccfg.g_profile = avctx->profile;
  251. dump_enc_cfg(avctx, &enccfg);
  252. /* Construct Encoder Context */
  253. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
  254. if (res != VPX_CODEC_OK) {
  255. log_encoder_error(avctx, "Failed to initialize encoder");
  256. return AVERROR(EINVAL);
  257. }
  258. //codec control failures are currently treated only as warnings
  259. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  260. codecctl_int(avctx, VP8E_SET_CPUUSED, cpuused);
  261. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
  262. //provide dummy value to initialize wrapper, values will be updated each _encode()
  263. vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  264. (unsigned char*)1);
  265. avctx->coded_frame = avcodec_alloc_frame();
  266. if (!avctx->coded_frame) {
  267. av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
  268. vp8_free(avctx);
  269. return AVERROR(ENOMEM);
  270. }
  271. return 0;
  272. }
  273. static inline void cx_pktcpy(struct FrameListData *dst,
  274. const struct vpx_codec_cx_pkt *src)
  275. {
  276. dst->pts = src->data.frame.pts;
  277. dst->duration = src->data.frame.duration;
  278. dst->flags = src->data.frame.flags;
  279. dst->sz = src->data.frame.sz;
  280. dst->buf = src->data.frame.buf;
  281. }
  282. /**
  283. * Store coded frame information in format suitable for return from encode().
  284. *
  285. * Write buffer information from @a cx_frame to @a buf & @a buf_size.
  286. * Timing/frame details to @a coded_frame.
  287. * @return Frame size written to @a buf on success
  288. * @return AVERROR(EINVAL) on error
  289. */
  290. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  291. uint8_t *buf, int buf_size, AVFrame *coded_frame)
  292. {
  293. if ((int) cx_frame->sz <= buf_size) {
  294. buf_size = cx_frame->sz;
  295. memcpy(buf, cx_frame->buf, buf_size);
  296. coded_frame->pts = cx_frame->pts;
  297. coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  298. if (coded_frame->key_frame)
  299. coded_frame->pict_type = FF_I_TYPE;
  300. else
  301. coded_frame->pict_type = FF_P_TYPE;
  302. } else {
  303. av_log(avctx, AV_LOG_ERROR,
  304. "Compressed frame larger than storage provided! (%zu/%d)\n",
  305. cx_frame->sz, buf_size);
  306. return AVERROR(EINVAL);
  307. }
  308. return buf_size;
  309. }
  310. /**
  311. * Queue multiple output frames from the encoder, returning the front-most.
  312. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  313. * the frame queue. Return the head frame if available.
  314. * @return Stored frame size
  315. * @return AVERROR(EINVAL) on output size error
  316. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  317. */
  318. static int queue_frames(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  319. AVFrame *coded_frame)
  320. {
  321. VP8Context *ctx = avctx->priv_data;
  322. const struct vpx_codec_cx_pkt *pkt;
  323. const void *iter = NULL;
  324. int size = 0;
  325. if (ctx->coded_frame_list) {
  326. struct FrameListData *cx_frame = ctx->coded_frame_list;
  327. /* return the leading frame if we've already begun queueing */
  328. size = storeframe(avctx, cx_frame, buf, buf_size, coded_frame);
  329. if (size < 0)
  330. return AVERROR(EINVAL);
  331. ctx->coded_frame_list = cx_frame->next;
  332. free_coded_frame(cx_frame);
  333. }
  334. /* consume all available output from the encoder before returning. buffers
  335. are only good through the next vpx_codec call */
  336. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
  337. switch (pkt->kind) {
  338. case VPX_CODEC_CX_FRAME_PKT:
  339. if (!size) {
  340. struct FrameListData cx_frame;
  341. /* avoid storing the frame when the list is empty and we haven't yet
  342. provided a frame for output */
  343. assert(!ctx->coded_frame_list);
  344. cx_pktcpy(&cx_frame, pkt);
  345. size = storeframe(avctx, &cx_frame, buf, buf_size, coded_frame);
  346. if (size < 0)
  347. return AVERROR(EINVAL);
  348. } else {
  349. struct FrameListData *cx_frame =
  350. av_malloc(sizeof(struct FrameListData));
  351. if (!cx_frame) {
  352. av_log(avctx, AV_LOG_ERROR,
  353. "Frame queue element alloc failed\n");
  354. return AVERROR(ENOMEM);
  355. }
  356. cx_pktcpy(cx_frame, pkt);
  357. cx_frame->buf = av_malloc(cx_frame->sz);
  358. if (!cx_frame->buf) {
  359. av_log(avctx, AV_LOG_ERROR,
  360. "Data buffer alloc (%zu bytes) failed\n",
  361. cx_frame->sz);
  362. return AVERROR(ENOMEM);
  363. }
  364. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  365. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  366. }
  367. break;
  368. case VPX_CODEC_STATS_PKT: {
  369. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  370. stats->buf = av_realloc(stats->buf,
  371. stats->sz + pkt->data.twopass_stats.sz);
  372. if (!stats->buf) {
  373. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  374. return AVERROR(ENOMEM);
  375. }
  376. memcpy((uint8_t*)stats->buf + stats->sz,
  377. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  378. stats->sz += pkt->data.twopass_stats.sz;
  379. break;
  380. }
  381. case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
  382. case VPX_CODEC_CUSTOM_PKT:
  383. //ignore unsupported/unrecognized packet types
  384. break;
  385. }
  386. }
  387. return size;
  388. }
  389. static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
  390. void *data)
  391. {
  392. VP8Context *ctx = avctx->priv_data;
  393. AVFrame *frame = data;
  394. struct vpx_image *rawimg = NULL;
  395. int64_t timestamp = 0;
  396. int res, coded_size;
  397. if (frame) {
  398. rawimg = &ctx->rawimg;
  399. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  400. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  401. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  402. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  403. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  404. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  405. timestamp = frame->pts;
  406. }
  407. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  408. avctx->ticks_per_frame, 0, ctx->deadline);
  409. if (res != VPX_CODEC_OK) {
  410. log_encoder_error(avctx, "Error encoding frame");
  411. return AVERROR_INVALIDDATA;
  412. }
  413. coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
  414. if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
  415. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  416. avctx->stats_out = av_malloc(b64_size);
  417. if (!avctx->stats_out) {
  418. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  419. b64_size);
  420. return AVERROR(ENOMEM);
  421. }
  422. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  423. ctx->twopass_stats.sz);
  424. }
  425. return coded_size;
  426. }
  427. AVCodec libvpx_encoder = {
  428. "libvpx",
  429. AVMEDIA_TYPE_VIDEO,
  430. CODEC_ID_VP8,
  431. sizeof(VP8Context),
  432. vp8_init,
  433. vp8_encode,
  434. vp8_free,
  435. NULL,
  436. CODEC_CAP_DELAY,
  437. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  438. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  439. };