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.

699 lines
27KB

  1. /*
  2. * Copyright (c) 2010, Google, Inc.
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav 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. * Libav 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 Libav; 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 "libvpx.h"
  31. #include "libavutil/base64.h"
  32. #include "libavutil/common.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/opt.h"
  35. /**
  36. * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
  37. * One encoded frame returned from the library.
  38. */
  39. struct FrameListData {
  40. void *buf; /**< compressed data buffer */
  41. size_t sz; /**< length of compressed data */
  42. int64_t pts; /**< time stamp to show frame
  43. (in timebase units) */
  44. unsigned long duration; /**< duration to show frame
  45. (in timebase units) */
  46. uint32_t flags; /**< flags for this frame */
  47. struct FrameListData *next;
  48. };
  49. typedef struct VP8EncoderContext {
  50. AVClass *class;
  51. struct vpx_codec_ctx encoder;
  52. struct vpx_image rawimg;
  53. struct vpx_fixed_buf twopass_stats;
  54. unsigned long deadline; //i.e., RT/GOOD/BEST
  55. struct FrameListData *coded_frame_list;
  56. int cpu_used;
  57. int auto_alt_ref;
  58. int arnr_max_frames;
  59. int arnr_strength;
  60. int arnr_type;
  61. int lag_in_frames;
  62. int error_resilient;
  63. int crf;
  64. int static_thresh;
  65. int drop_threshold;
  66. int noise_sensitivity;
  67. } VP8Context;
  68. /** String mappings for enum vp8e_enc_control_id */
  69. static const char *const ctlidstr[] = {
  70. [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
  71. [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
  72. [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
  73. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  74. [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
  75. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  76. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  77. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  78. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  79. };
  80. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  81. {
  82. VP8Context *ctx = avctx->priv_data;
  83. const char *error = vpx_codec_error(&ctx->encoder);
  84. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  85. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  86. if (detail)
  87. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  88. }
  89. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  90. const struct vpx_codec_enc_cfg *cfg)
  91. {
  92. int width = -30;
  93. int level = AV_LOG_DEBUG;
  94. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  95. av_log(avctx, level, "generic settings\n"
  96. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  97. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  98. width, "g_usage:", cfg->g_usage,
  99. width, "g_threads:", cfg->g_threads,
  100. width, "g_profile:", cfg->g_profile,
  101. width, "g_w:", cfg->g_w,
  102. width, "g_h:", cfg->g_h,
  103. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  104. width, "g_error_resilient:", cfg->g_error_resilient,
  105. width, "g_pass:", cfg->g_pass,
  106. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  107. av_log(avctx, level, "rate control settings\n"
  108. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  109. " %*s%d\n %*s%p(%zu)\n %*s%u\n",
  110. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  111. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  112. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  113. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  114. width, "rc_end_usage:", cfg->rc_end_usage,
  115. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  116. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  117. av_log(avctx, level, "quantizer settings\n"
  118. " %*s%u\n %*s%u\n",
  119. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  120. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  121. av_log(avctx, level, "bitrate tolerance\n"
  122. " %*s%u\n %*s%u\n",
  123. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  124. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  125. av_log(avctx, level, "decoder buffer model\n"
  126. " %*s%u\n %*s%u\n %*s%u\n",
  127. width, "rc_buf_sz:", cfg->rc_buf_sz,
  128. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  129. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  130. av_log(avctx, level, "2 pass rate control settings\n"
  131. " %*s%u\n %*s%u\n %*s%u\n",
  132. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  133. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  134. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  135. av_log(avctx, level, "keyframing settings\n"
  136. " %*s%d\n %*s%u\n %*s%u\n",
  137. width, "kf_mode:", cfg->kf_mode,
  138. width, "kf_min_dist:", cfg->kf_min_dist,
  139. width, "kf_max_dist:", cfg->kf_max_dist);
  140. av_log(avctx, level, "\n");
  141. }
  142. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  143. {
  144. struct FrameListData **p = list;
  145. while (*p)
  146. p = &(*p)->next;
  147. *p = cx_frame;
  148. cx_frame->next = NULL;
  149. }
  150. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  151. {
  152. av_freep(&cx_frame->buf);
  153. av_freep(&cx_frame);
  154. }
  155. static av_cold void free_frame_list(struct FrameListData *list)
  156. {
  157. struct FrameListData *p = list;
  158. while (p) {
  159. list = list->next;
  160. free_coded_frame(p);
  161. p = list;
  162. }
  163. }
  164. static av_cold int codecctl_int(AVCodecContext *avctx,
  165. enum vp8e_enc_control_id id, int val)
  166. {
  167. VP8Context *ctx = avctx->priv_data;
  168. char buf[80];
  169. int width = -30;
  170. int res;
  171. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  172. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  173. res = vpx_codec_control(&ctx->encoder, id, val);
  174. if (res != VPX_CODEC_OK) {
  175. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  176. ctlidstr[id]);
  177. log_encoder_error(avctx, buf);
  178. }
  179. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  180. }
  181. static av_cold int vp8_free(AVCodecContext *avctx)
  182. {
  183. VP8Context *ctx = avctx->priv_data;
  184. vpx_codec_destroy(&ctx->encoder);
  185. av_freep(&ctx->twopass_stats.buf);
  186. av_freep(&avctx->stats_out);
  187. free_frame_list(ctx->coded_frame_list);
  188. return 0;
  189. }
  190. static av_cold int vpx_init(AVCodecContext *avctx,
  191. const struct vpx_codec_iface *iface)
  192. {
  193. VP8Context *ctx = avctx->priv_data;
  194. struct vpx_codec_enc_cfg enccfg = { 0 };
  195. AVCPBProperties *cpb_props;
  196. int res;
  197. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  198. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  199. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  200. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  201. vpx_codec_err_to_string(res));
  202. return AVERROR(EINVAL);
  203. }
  204. dump_enc_cfg(avctx, &enccfg);
  205. enccfg.g_w = avctx->width;
  206. enccfg.g_h = avctx->height;
  207. enccfg.g_timebase.num = avctx->time_base.num;
  208. enccfg.g_timebase.den = avctx->time_base.den;
  209. enccfg.g_threads = avctx->thread_count;
  210. if (ctx->lag_in_frames >= 0)
  211. enccfg.g_lag_in_frames = ctx->lag_in_frames;
  212. if (avctx->flags & AV_CODEC_FLAG_PASS1)
  213. enccfg.g_pass = VPX_RC_FIRST_PASS;
  214. else if (avctx->flags & AV_CODEC_FLAG_PASS2)
  215. enccfg.g_pass = VPX_RC_LAST_PASS;
  216. else
  217. enccfg.g_pass = VPX_RC_ONE_PASS;
  218. if (!avctx->bit_rate)
  219. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  220. else
  221. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  222. AV_ROUND_NEAR_INF);
  223. if (ctx->crf)
  224. enccfg.rc_end_usage = VPX_CQ;
  225. else if (avctx->rc_min_rate == avctx->rc_max_rate &&
  226. avctx->rc_min_rate == avctx->bit_rate)
  227. enccfg.rc_end_usage = VPX_CBR;
  228. if (avctx->qmin > 0)
  229. enccfg.rc_min_quantizer = avctx->qmin;
  230. if (avctx->qmax > 0)
  231. enccfg.rc_max_quantizer = avctx->qmax;
  232. #if FF_API_PRIVATE_OPT
  233. FF_DISABLE_DEPRECATION_WARNINGS
  234. if (avctx->frame_skip_threshold)
  235. ctx->drop_threshold = avctx->frame_skip_threshold;
  236. FF_ENABLE_DEPRECATION_WARNINGS
  237. #endif
  238. enccfg.rc_dropframe_thresh = ctx->drop_threshold;
  239. //0-100 (0 => CBR, 100 => VBR)
  240. enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
  241. enccfg.rc_2pass_vbr_minsection_pct =
  242. avctx->rc_min_rate * 100LL / avctx->bit_rate;
  243. if (avctx->rc_max_rate)
  244. enccfg.rc_2pass_vbr_maxsection_pct =
  245. avctx->rc_max_rate * 100LL / avctx->bit_rate;
  246. if (avctx->rc_buffer_size)
  247. enccfg.rc_buf_sz =
  248. avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
  249. if (avctx->rc_initial_buffer_occupancy)
  250. enccfg.rc_buf_initial_sz =
  251. avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
  252. enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
  253. //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
  254. if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
  255. enccfg.kf_min_dist = avctx->keyint_min;
  256. if (avctx->gop_size >= 0)
  257. enccfg.kf_max_dist = avctx->gop_size;
  258. if (enccfg.g_pass == VPX_RC_FIRST_PASS)
  259. enccfg.g_lag_in_frames = 0;
  260. else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
  261. int decode_size, ret;
  262. if (!avctx->stats_in) {
  263. av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
  264. return AVERROR_INVALIDDATA;
  265. }
  266. ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
  267. ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
  268. if (ret < 0) {
  269. av_log(avctx, AV_LOG_ERROR,
  270. "Stat buffer alloc (%zu bytes) failed\n",
  271. ctx->twopass_stats.sz);
  272. return ret;
  273. }
  274. decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
  275. ctx->twopass_stats.sz);
  276. if (decode_size < 0) {
  277. av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
  278. return AVERROR_INVALIDDATA;
  279. }
  280. ctx->twopass_stats.sz = decode_size;
  281. enccfg.rc_twopass_stats_in = ctx->twopass_stats;
  282. }
  283. /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
  284. complexity playback on low powered devices at the expense of encode
  285. quality. */
  286. if (avctx->profile != FF_PROFILE_UNKNOWN)
  287. enccfg.g_profile = avctx->profile;
  288. else if (avctx->pix_fmt == AV_PIX_FMT_YUV420P)
  289. avctx->profile = enccfg.g_profile = FF_PROFILE_VP9_0;
  290. else
  291. avctx->profile = enccfg.g_profile = FF_PROFILE_VP9_1;
  292. enccfg.g_error_resilient = ctx->error_resilient;
  293. dump_enc_cfg(avctx, &enccfg);
  294. /* Construct Encoder Context */
  295. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
  296. if (res != VPX_CODEC_OK) {
  297. log_encoder_error(avctx, "Failed to initialize encoder");
  298. return AVERROR(EINVAL);
  299. }
  300. //codec control failures are currently treated only as warnings
  301. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  302. if (ctx->cpu_used != INT_MIN)
  303. codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
  304. if (ctx->auto_alt_ref >= 0)
  305. codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
  306. if (ctx->arnr_max_frames >= 0)
  307. codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
  308. if (ctx->arnr_strength >= 0)
  309. codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
  310. if (ctx->arnr_type >= 0)
  311. codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
  312. if (CONFIG_LIBVPX_VP8_ENCODER && iface == &vpx_codec_vp8_cx_algo) {
  313. #if FF_API_PRIVATE_OPT
  314. FF_DISABLE_DEPRECATION_WARNINGS
  315. if (avctx->noise_reduction)
  316. ctx->noise_sensitivity = avctx->noise_reduction;
  317. FF_ENABLE_DEPRECATION_WARNINGS
  318. #endif
  319. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, ctx->noise_sensitivity);
  320. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  321. }
  322. #if FF_API_MPV_OPT
  323. FF_DISABLE_DEPRECATION_WARNINGS
  324. if (avctx->mb_threshold) {
  325. av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
  326. "use the static-thresh private option instead.\n");
  327. ctx->static_thresh = avctx->mb_threshold;
  328. }
  329. FF_ENABLE_DEPRECATION_WARNINGS
  330. #endif
  331. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
  332. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  333. //provide dummy value to initialize wrapper, values will be updated each _encode()
  334. vpx_img_wrap(&ctx->rawimg, ff_vpx_pixfmt_to_imgfmt(avctx->pix_fmt),
  335. avctx->width, avctx->height, 1, (unsigned char *)1);
  336. cpb_props = ff_add_cpb_side_data(avctx);
  337. if (!cpb_props)
  338. return AVERROR(ENOMEM);
  339. if (enccfg.rc_end_usage == VPX_CBR ||
  340. enccfg.g_pass != VPX_RC_ONE_PASS) {
  341. cpb_props->max_bitrate = avctx->rc_max_rate;
  342. cpb_props->min_bitrate = avctx->rc_min_rate;
  343. cpb_props->avg_bitrate = avctx->bit_rate;
  344. }
  345. cpb_props->buffer_size = avctx->rc_buffer_size;
  346. return 0;
  347. }
  348. static inline void cx_pktcpy(struct FrameListData *dst,
  349. const struct vpx_codec_cx_pkt *src)
  350. {
  351. dst->pts = src->data.frame.pts;
  352. dst->duration = src->data.frame.duration;
  353. dst->flags = src->data.frame.flags;
  354. dst->sz = src->data.frame.sz;
  355. dst->buf = src->data.frame.buf;
  356. }
  357. /**
  358. * Store coded frame information in format suitable for return from encode2().
  359. *
  360. * Write information from @a cx_frame to @a pkt
  361. * @return packet data size on success
  362. * @return a negative AVERROR on error
  363. */
  364. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  365. AVPacket *pkt)
  366. {
  367. int ret = ff_alloc_packet(pkt, cx_frame->sz);
  368. if (ret >= 0) {
  369. memcpy(pkt->data, cx_frame->buf, pkt->size);
  370. pkt->pts = pkt->dts = cx_frame->pts;
  371. #if FF_API_CODED_FRAME
  372. FF_DISABLE_DEPRECATION_WARNINGS
  373. avctx->coded_frame->pts = cx_frame->pts;
  374. avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  375. FF_ENABLE_DEPRECATION_WARNINGS
  376. #endif
  377. if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
  378. #if FF_API_CODED_FRAME
  379. FF_DISABLE_DEPRECATION_WARNINGS
  380. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  381. FF_ENABLE_DEPRECATION_WARNINGS
  382. #endif
  383. pkt->flags |= AV_PKT_FLAG_KEY;
  384. } else {
  385. #if FF_API_CODED_FRAME
  386. FF_DISABLE_DEPRECATION_WARNINGS
  387. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  388. FF_ENABLE_DEPRECATION_WARNINGS
  389. #endif
  390. }
  391. } else {
  392. av_log(avctx, AV_LOG_ERROR,
  393. "Error getting output packet of size %zu.\n", cx_frame->sz);
  394. return ret;
  395. }
  396. return pkt->size;
  397. }
  398. /**
  399. * Queue multiple output frames from the encoder, returning the front-most.
  400. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  401. * the frame queue. Return the head frame if available.
  402. * @return Stored frame size
  403. * @return AVERROR(EINVAL) on output size error
  404. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  405. */
  406. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
  407. {
  408. VP8Context *ctx = avctx->priv_data;
  409. const struct vpx_codec_cx_pkt *pkt;
  410. const void *iter = NULL;
  411. int size = 0;
  412. if (ctx->coded_frame_list) {
  413. struct FrameListData *cx_frame = ctx->coded_frame_list;
  414. /* return the leading frame if we've already begun queueing */
  415. size = storeframe(avctx, cx_frame, pkt_out);
  416. if (size < 0)
  417. return size;
  418. ctx->coded_frame_list = cx_frame->next;
  419. free_coded_frame(cx_frame);
  420. }
  421. /* consume all available output from the encoder before returning. buffers
  422. are only good through the next vpx_codec call */
  423. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
  424. switch (pkt->kind) {
  425. case VPX_CODEC_CX_FRAME_PKT:
  426. if (!size) {
  427. struct FrameListData cx_frame;
  428. /* avoid storing the frame when the list is empty and we haven't yet
  429. provided a frame for output */
  430. assert(!ctx->coded_frame_list);
  431. cx_pktcpy(&cx_frame, pkt);
  432. size = storeframe(avctx, &cx_frame, pkt_out);
  433. if (size < 0)
  434. return size;
  435. } else {
  436. struct FrameListData *cx_frame =
  437. av_malloc(sizeof(struct FrameListData));
  438. if (!cx_frame) {
  439. av_log(avctx, AV_LOG_ERROR,
  440. "Frame queue element alloc failed\n");
  441. return AVERROR(ENOMEM);
  442. }
  443. cx_pktcpy(cx_frame, pkt);
  444. cx_frame->buf = av_malloc(cx_frame->sz);
  445. if (!cx_frame->buf) {
  446. av_log(avctx, AV_LOG_ERROR,
  447. "Data buffer alloc (%zu bytes) failed\n",
  448. cx_frame->sz);
  449. av_freep(&cx_frame);
  450. return AVERROR(ENOMEM);
  451. }
  452. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  453. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  454. }
  455. break;
  456. case VPX_CODEC_STATS_PKT: {
  457. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  458. int err;
  459. if ((err = av_reallocp(&stats->buf,
  460. stats->sz +
  461. pkt->data.twopass_stats.sz)) < 0) {
  462. stats->sz = 0;
  463. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  464. return err;
  465. }
  466. memcpy((uint8_t*)stats->buf + stats->sz,
  467. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  468. stats->sz += pkt->data.twopass_stats.sz;
  469. break;
  470. }
  471. case VPX_CODEC_PSNR_PKT: //FIXME add support for AV_CODEC_FLAG_PSNR
  472. case VPX_CODEC_CUSTOM_PKT:
  473. //ignore unsupported/unrecognized packet types
  474. break;
  475. }
  476. }
  477. return size;
  478. }
  479. static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
  480. const AVFrame *frame, int *got_packet)
  481. {
  482. VP8Context *ctx = avctx->priv_data;
  483. struct vpx_image *rawimg = NULL;
  484. int64_t timestamp = 0;
  485. int res, coded_size;
  486. vpx_enc_frame_flags_t flags = 0;
  487. if (frame) {
  488. rawimg = &ctx->rawimg;
  489. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  490. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  491. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  492. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  493. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  494. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  495. timestamp = frame->pts;
  496. if (frame->pict_type == AV_PICTURE_TYPE_I)
  497. flags |= VPX_EFLAG_FORCE_KF;
  498. }
  499. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  500. avctx->ticks_per_frame, flags, ctx->deadline);
  501. if (res != VPX_CODEC_OK) {
  502. log_encoder_error(avctx, "Error encoding frame");
  503. return AVERROR_INVALIDDATA;
  504. }
  505. coded_size = queue_frames(avctx, pkt);
  506. if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
  507. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  508. avctx->stats_out = av_malloc(b64_size);
  509. if (!avctx->stats_out) {
  510. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  511. b64_size);
  512. return AVERROR(ENOMEM);
  513. }
  514. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  515. ctx->twopass_stats.sz);
  516. }
  517. *got_packet = !!coded_size;
  518. return 0;
  519. }
  520. #define OFFSET(x) offsetof(VP8Context, x)
  521. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  522. static const AVOption options[] = {
  523. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, INT_MIN, INT_MAX, VE},
  524. { "auto-alt-ref", "Enable use of alternate reference "
  525. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  526. { "lag-in-frames", "Number of frames to look ahead for "
  527. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  528. { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  529. { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  530. { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"},
  531. { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" },
  532. { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" },
  533. { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" },
  534. { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
  535. { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"},
  536. { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"},
  537. { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"},
  538. { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
  539. #ifdef VPX_ERROR_RESILIENT_DEFAULT
  540. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
  541. { "partitions", "The frame partitions are independently decodable "
  542. "by the bool decoder, meaning that partitions can be decoded even "
  543. "though earlier partitions have been lost. Note that intra predicition"
  544. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
  545. #endif
  546. { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE },
  547. { "static-thresh", "A change threshold on blocks below which they will be skipped by the encoder", OFFSET(static_thresh), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  548. { "drop-threshold", "Frame drop threshold", offsetof(VP8Context, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE },
  549. { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE},
  550. { NULL }
  551. };
  552. static const AVCodecDefault defaults[] = {
  553. { "qmin", "-1" },
  554. { "qmax", "-1" },
  555. { "g", "-1" },
  556. { "keyint_min", "-1" },
  557. { NULL },
  558. };
  559. #if CONFIG_LIBVPX_VP8_ENCODER
  560. static av_cold int vp8_init(AVCodecContext *avctx)
  561. {
  562. return vpx_init(avctx, &vpx_codec_vp8_cx_algo);
  563. }
  564. static const AVClass class_vp8 = {
  565. .class_name = "libvpx encoder",
  566. .item_name = av_default_item_name,
  567. .option = options,
  568. .version = LIBAVUTIL_VERSION_INT,
  569. };
  570. AVCodec ff_libvpx_vp8_encoder = {
  571. .name = "libvpx",
  572. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  573. .type = AVMEDIA_TYPE_VIDEO,
  574. .id = AV_CODEC_ID_VP8,
  575. .priv_data_size = sizeof(VP8Context),
  576. .init = vp8_init,
  577. .encode2 = vp8_encode,
  578. .close = vp8_free,
  579. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  580. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  581. .priv_class = &class_vp8,
  582. .defaults = defaults,
  583. };
  584. #endif /* CONFIG_LIBVPX_VP8_ENCODER */
  585. #if CONFIG_LIBVPX_VP9_ENCODER
  586. static av_cold int vp9_init(AVCodecContext *avctx)
  587. {
  588. return vpx_init(avctx, &vpx_codec_vp9_cx_algo);
  589. }
  590. static const AVClass class_vp9 = {
  591. .class_name = "libvpx encoder",
  592. .item_name = av_default_item_name,
  593. .option = options,
  594. .version = LIBAVUTIL_VERSION_INT,
  595. };
  596. static const AVProfile profiles[] = {
  597. { FF_PROFILE_VP9_0, "Profile 0" },
  598. { FF_PROFILE_VP9_1, "Profile 1" },
  599. { FF_PROFILE_VP9_2, "Profile 2" },
  600. { FF_PROFILE_VP9_3, "Profile 3" },
  601. { FF_PROFILE_UNKNOWN },
  602. };
  603. AVCodec ff_libvpx_vp9_encoder = {
  604. .name = "libvpx-vp9",
  605. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
  606. .type = AVMEDIA_TYPE_VIDEO,
  607. .id = AV_CODEC_ID_VP9,
  608. .priv_data_size = sizeof(VP8Context),
  609. .init = vp9_init,
  610. .encode2 = vp8_encode,
  611. .close = vp8_free,
  612. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
  613. .pix_fmts = (const enum AVPixelFormat[]) {
  614. AV_PIX_FMT_YUV420P,
  615. #if VPX_IMAGE_ABI_VERSION >= 3
  616. AV_PIX_FMT_YUV422P,
  617. AV_PIX_FMT_YUV444P,
  618. AV_PIX_FMT_YUV440P,
  619. #endif
  620. AV_PIX_FMT_NONE,
  621. },
  622. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  623. .priv_class = &class_vp9,
  624. .defaults = defaults,
  625. };
  626. #endif /* CONFIG_LIBVPX_VP9_ENCODER */