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.

651 lines
25KB

  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. } VP8Context;
  66. /** String mappings for enum vp8e_enc_control_id */
  67. static const char *const ctlidstr[] = {
  68. [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
  69. [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
  70. [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
  71. [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
  72. [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
  73. [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
  74. [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
  75. [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
  76. [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
  77. [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
  78. [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
  79. [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
  80. [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
  81. [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
  82. [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
  83. [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
  84. [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
  85. };
  86. static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
  87. {
  88. VP8Context *ctx = avctx->priv_data;
  89. const char *error = vpx_codec_error(&ctx->encoder);
  90. const char *detail = vpx_codec_error_detail(&ctx->encoder);
  91. av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
  92. if (detail)
  93. av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
  94. }
  95. static av_cold void dump_enc_cfg(AVCodecContext *avctx,
  96. const struct vpx_codec_enc_cfg *cfg)
  97. {
  98. int width = -30;
  99. int level = AV_LOG_DEBUG;
  100. av_log(avctx, level, "vpx_codec_enc_cfg\n");
  101. av_log(avctx, level, "generic settings\n"
  102. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  103. " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
  104. width, "g_usage:", cfg->g_usage,
  105. width, "g_threads:", cfg->g_threads,
  106. width, "g_profile:", cfg->g_profile,
  107. width, "g_w:", cfg->g_w,
  108. width, "g_h:", cfg->g_h,
  109. width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
  110. width, "g_error_resilient:", cfg->g_error_resilient,
  111. width, "g_pass:", cfg->g_pass,
  112. width, "g_lag_in_frames:", cfg->g_lag_in_frames);
  113. av_log(avctx, level, "rate control settings\n"
  114. " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
  115. " %*s%d\n %*s%p(%zu)\n %*s%u\n",
  116. width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
  117. width, "rc_resize_allowed:", cfg->rc_resize_allowed,
  118. width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
  119. width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
  120. width, "rc_end_usage:", cfg->rc_end_usage,
  121. width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
  122. width, "rc_target_bitrate:", cfg->rc_target_bitrate);
  123. av_log(avctx, level, "quantizer settings\n"
  124. " %*s%u\n %*s%u\n",
  125. width, "rc_min_quantizer:", cfg->rc_min_quantizer,
  126. width, "rc_max_quantizer:", cfg->rc_max_quantizer);
  127. av_log(avctx, level, "bitrate tolerance\n"
  128. " %*s%u\n %*s%u\n",
  129. width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
  130. width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
  131. av_log(avctx, level, "decoder buffer model\n"
  132. " %*s%u\n %*s%u\n %*s%u\n",
  133. width, "rc_buf_sz:", cfg->rc_buf_sz,
  134. width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
  135. width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
  136. av_log(avctx, level, "2 pass rate control settings\n"
  137. " %*s%u\n %*s%u\n %*s%u\n",
  138. width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
  139. width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
  140. width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
  141. av_log(avctx, level, "keyframing settings\n"
  142. " %*s%d\n %*s%u\n %*s%u\n",
  143. width, "kf_mode:", cfg->kf_mode,
  144. width, "kf_min_dist:", cfg->kf_min_dist,
  145. width, "kf_max_dist:", cfg->kf_max_dist);
  146. av_log(avctx, level, "\n");
  147. }
  148. static void coded_frame_add(void *list, struct FrameListData *cx_frame)
  149. {
  150. struct FrameListData **p = list;
  151. while (*p)
  152. p = &(*p)->next;
  153. *p = cx_frame;
  154. cx_frame->next = NULL;
  155. }
  156. static av_cold void free_coded_frame(struct FrameListData *cx_frame)
  157. {
  158. av_freep(&cx_frame->buf);
  159. av_freep(&cx_frame);
  160. }
  161. static av_cold void free_frame_list(struct FrameListData *list)
  162. {
  163. struct FrameListData *p = list;
  164. while (p) {
  165. list = list->next;
  166. free_coded_frame(p);
  167. p = list;
  168. }
  169. }
  170. static av_cold int codecctl_int(AVCodecContext *avctx,
  171. enum vp8e_enc_control_id id, int val)
  172. {
  173. VP8Context *ctx = avctx->priv_data;
  174. char buf[80];
  175. int width = -30;
  176. int res;
  177. snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
  178. av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
  179. res = vpx_codec_control(&ctx->encoder, id, val);
  180. if (res != VPX_CODEC_OK) {
  181. snprintf(buf, sizeof(buf), "Failed to set %s codec control",
  182. ctlidstr[id]);
  183. log_encoder_error(avctx, buf);
  184. }
  185. return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
  186. }
  187. static av_cold int vp8_free(AVCodecContext *avctx)
  188. {
  189. VP8Context *ctx = avctx->priv_data;
  190. vpx_codec_destroy(&ctx->encoder);
  191. av_freep(&ctx->twopass_stats.buf);
  192. av_freep(&avctx->coded_frame);
  193. av_freep(&avctx->stats_out);
  194. free_frame_list(ctx->coded_frame_list);
  195. return 0;
  196. }
  197. static av_cold int vpx_init(AVCodecContext *avctx,
  198. const struct vpx_codec_iface *iface)
  199. {
  200. VP8Context *ctx = avctx->priv_data;
  201. struct vpx_codec_enc_cfg enccfg;
  202. int res;
  203. av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
  204. av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
  205. if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
  206. av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
  207. vpx_codec_err_to_string(res));
  208. return AVERROR(EINVAL);
  209. }
  210. dump_enc_cfg(avctx, &enccfg);
  211. enccfg.g_w = avctx->width;
  212. enccfg.g_h = avctx->height;
  213. enccfg.g_timebase.num = avctx->time_base.num;
  214. enccfg.g_timebase.den = avctx->time_base.den;
  215. enccfg.g_threads = avctx->thread_count;
  216. if (ctx->lag_in_frames >= 0)
  217. enccfg.g_lag_in_frames = ctx->lag_in_frames;
  218. if (avctx->flags & CODEC_FLAG_PASS1)
  219. enccfg.g_pass = VPX_RC_FIRST_PASS;
  220. else if (avctx->flags & CODEC_FLAG_PASS2)
  221. enccfg.g_pass = VPX_RC_LAST_PASS;
  222. else
  223. enccfg.g_pass = VPX_RC_ONE_PASS;
  224. if (!avctx->bit_rate)
  225. avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
  226. else
  227. enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
  228. AV_ROUND_NEAR_INF);
  229. if (ctx->crf)
  230. enccfg.rc_end_usage = VPX_CQ;
  231. else if (avctx->rc_min_rate == avctx->rc_max_rate &&
  232. avctx->rc_min_rate == avctx->bit_rate)
  233. enccfg.rc_end_usage = VPX_CBR;
  234. if (avctx->qmin > 0)
  235. enccfg.rc_min_quantizer = avctx->qmin;
  236. if (avctx->qmax > 0)
  237. enccfg.rc_max_quantizer = avctx->qmax;
  238. enccfg.rc_dropframe_thresh = avctx->frame_skip_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. enccfg.g_error_resilient = ctx->error_resilient;
  289. dump_enc_cfg(avctx, &enccfg);
  290. /* Construct Encoder Context */
  291. res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
  292. if (res != VPX_CODEC_OK) {
  293. log_encoder_error(avctx, "Failed to initialize encoder");
  294. return AVERROR(EINVAL);
  295. }
  296. //codec control failures are currently treated only as warnings
  297. av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
  298. if (ctx->cpu_used != INT_MIN)
  299. codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
  300. if (ctx->auto_alt_ref >= 0)
  301. codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
  302. if (ctx->arnr_max_frames >= 0)
  303. codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
  304. if (ctx->arnr_strength >= 0)
  305. codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
  306. if (ctx->arnr_type >= 0)
  307. codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
  308. codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
  309. codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
  310. #if FF_API_MPV_OPT
  311. FF_DISABLE_DEPRECATION_WARNINGS
  312. if (avctx->mb_threshold) {
  313. av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
  314. "use the static-thresh private option instead.\n");
  315. ctx->static_thresh = avctx->mb_threshold;
  316. }
  317. FF_ENABLE_DEPRECATION_WARNINGS
  318. #endif
  319. codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
  320. codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
  321. //provide dummy value to initialize wrapper, values will be updated each _encode()
  322. vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
  323. (unsigned char*)1);
  324. avctx->coded_frame = av_frame_alloc();
  325. if (!avctx->coded_frame) {
  326. av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
  327. vp8_free(avctx);
  328. return AVERROR(ENOMEM);
  329. }
  330. return 0;
  331. }
  332. static inline void cx_pktcpy(struct FrameListData *dst,
  333. const struct vpx_codec_cx_pkt *src)
  334. {
  335. dst->pts = src->data.frame.pts;
  336. dst->duration = src->data.frame.duration;
  337. dst->flags = src->data.frame.flags;
  338. dst->sz = src->data.frame.sz;
  339. dst->buf = src->data.frame.buf;
  340. }
  341. /**
  342. * Store coded frame information in format suitable for return from encode2().
  343. *
  344. * Write information from @a cx_frame to @a pkt
  345. * @return packet data size on success
  346. * @return a negative AVERROR on error
  347. */
  348. static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
  349. AVPacket *pkt, AVFrame *coded_frame)
  350. {
  351. int ret = ff_alloc_packet(pkt, cx_frame->sz);
  352. if (ret >= 0) {
  353. memcpy(pkt->data, cx_frame->buf, pkt->size);
  354. pkt->pts = pkt->dts = cx_frame->pts;
  355. coded_frame->pts = cx_frame->pts;
  356. coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
  357. if (coded_frame->key_frame) {
  358. coded_frame->pict_type = AV_PICTURE_TYPE_I;
  359. pkt->flags |= AV_PKT_FLAG_KEY;
  360. } else
  361. coded_frame->pict_type = AV_PICTURE_TYPE_P;
  362. } else {
  363. av_log(avctx, AV_LOG_ERROR,
  364. "Error getting output packet of size %zu.\n", cx_frame->sz);
  365. return ret;
  366. }
  367. return pkt->size;
  368. }
  369. /**
  370. * Queue multiple output frames from the encoder, returning the front-most.
  371. * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
  372. * the frame queue. Return the head frame if available.
  373. * @return Stored frame size
  374. * @return AVERROR(EINVAL) on output size error
  375. * @return AVERROR(ENOMEM) on coded frame queue data allocation error
  376. */
  377. static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out,
  378. AVFrame *coded_frame)
  379. {
  380. VP8Context *ctx = avctx->priv_data;
  381. const struct vpx_codec_cx_pkt *pkt;
  382. const void *iter = NULL;
  383. int size = 0;
  384. if (ctx->coded_frame_list) {
  385. struct FrameListData *cx_frame = ctx->coded_frame_list;
  386. /* return the leading frame if we've already begun queueing */
  387. size = storeframe(avctx, cx_frame, pkt_out, coded_frame);
  388. if (size < 0)
  389. return size;
  390. ctx->coded_frame_list = cx_frame->next;
  391. free_coded_frame(cx_frame);
  392. }
  393. /* consume all available output from the encoder before returning. buffers
  394. are only good through the next vpx_codec call */
  395. while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
  396. switch (pkt->kind) {
  397. case VPX_CODEC_CX_FRAME_PKT:
  398. if (!size) {
  399. struct FrameListData cx_frame;
  400. /* avoid storing the frame when the list is empty and we haven't yet
  401. provided a frame for output */
  402. assert(!ctx->coded_frame_list);
  403. cx_pktcpy(&cx_frame, pkt);
  404. size = storeframe(avctx, &cx_frame, pkt_out, coded_frame);
  405. if (size < 0)
  406. return size;
  407. } else {
  408. struct FrameListData *cx_frame =
  409. av_malloc(sizeof(struct FrameListData));
  410. if (!cx_frame) {
  411. av_log(avctx, AV_LOG_ERROR,
  412. "Frame queue element alloc failed\n");
  413. return AVERROR(ENOMEM);
  414. }
  415. cx_pktcpy(cx_frame, pkt);
  416. cx_frame->buf = av_malloc(cx_frame->sz);
  417. if (!cx_frame->buf) {
  418. av_log(avctx, AV_LOG_ERROR,
  419. "Data buffer alloc (%zu bytes) failed\n",
  420. cx_frame->sz);
  421. av_freep(&cx_frame);
  422. return AVERROR(ENOMEM);
  423. }
  424. memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
  425. coded_frame_add(&ctx->coded_frame_list, cx_frame);
  426. }
  427. break;
  428. case VPX_CODEC_STATS_PKT: {
  429. struct vpx_fixed_buf *stats = &ctx->twopass_stats;
  430. int err;
  431. if ((err = av_reallocp(&stats->buf,
  432. stats->sz +
  433. pkt->data.twopass_stats.sz)) < 0) {
  434. stats->sz = 0;
  435. av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
  436. return err;
  437. }
  438. memcpy((uint8_t*)stats->buf + stats->sz,
  439. pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
  440. stats->sz += pkt->data.twopass_stats.sz;
  441. break;
  442. }
  443. case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
  444. case VPX_CODEC_CUSTOM_PKT:
  445. //ignore unsupported/unrecognized packet types
  446. break;
  447. }
  448. }
  449. return size;
  450. }
  451. static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
  452. const AVFrame *frame, int *got_packet)
  453. {
  454. VP8Context *ctx = avctx->priv_data;
  455. struct vpx_image *rawimg = NULL;
  456. int64_t timestamp = 0;
  457. int res, coded_size;
  458. vpx_enc_frame_flags_t flags = 0;
  459. if (frame) {
  460. rawimg = &ctx->rawimg;
  461. rawimg->planes[VPX_PLANE_Y] = frame->data[0];
  462. rawimg->planes[VPX_PLANE_U] = frame->data[1];
  463. rawimg->planes[VPX_PLANE_V] = frame->data[2];
  464. rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
  465. rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
  466. rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
  467. timestamp = frame->pts;
  468. if (frame->pict_type == AV_PICTURE_TYPE_I)
  469. flags |= VPX_EFLAG_FORCE_KF;
  470. }
  471. res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
  472. avctx->ticks_per_frame, flags, ctx->deadline);
  473. if (res != VPX_CODEC_OK) {
  474. log_encoder_error(avctx, "Error encoding frame");
  475. return AVERROR_INVALIDDATA;
  476. }
  477. coded_size = queue_frames(avctx, pkt, avctx->coded_frame);
  478. if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
  479. unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
  480. avctx->stats_out = av_malloc(b64_size);
  481. if (!avctx->stats_out) {
  482. av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
  483. b64_size);
  484. return AVERROR(ENOMEM);
  485. }
  486. av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
  487. ctx->twopass_stats.sz);
  488. }
  489. *got_packet = !!coded_size;
  490. return 0;
  491. }
  492. #define OFFSET(x) offsetof(VP8Context, x)
  493. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  494. static const AVOption options[] = {
  495. { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, INT_MIN, INT_MAX, VE},
  496. { "auto-alt-ref", "Enable use of alternate reference "
  497. "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
  498. { "lag-in-frames", "Number of frames to look ahead for "
  499. "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  500. { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  501. { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
  502. { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"},
  503. { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" },
  504. { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" },
  505. { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" },
  506. { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
  507. { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"},
  508. { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"},
  509. { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"},
  510. { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
  511. #ifdef VPX_ERROR_RESILIENT_DEFAULT
  512. { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
  513. { "partitions", "The frame partitions are independently decodable "
  514. "by the bool decoder, meaning that partitions can be decoded even "
  515. "though earlier partitions have been lost. Note that intra predicition"
  516. " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
  517. #endif
  518. { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE },
  519. { "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 },
  520. { NULL }
  521. };
  522. static const AVCodecDefault defaults[] = {
  523. { "qmin", "-1" },
  524. { "qmax", "-1" },
  525. { "g", "-1" },
  526. { "keyint_min", "-1" },
  527. { NULL },
  528. };
  529. #if CONFIG_LIBVPX_VP8_ENCODER
  530. static av_cold int vp8_init(AVCodecContext *avctx)
  531. {
  532. return vpx_init(avctx, &vpx_codec_vp8_cx_algo);
  533. }
  534. static const AVClass class_vp8 = {
  535. .class_name = "libvpx encoder",
  536. .item_name = av_default_item_name,
  537. .option = options,
  538. .version = LIBAVUTIL_VERSION_INT,
  539. };
  540. AVCodec ff_libvpx_vp8_encoder = {
  541. .name = "libvpx",
  542. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
  543. .type = AVMEDIA_TYPE_VIDEO,
  544. .id = AV_CODEC_ID_VP8,
  545. .priv_data_size = sizeof(VP8Context),
  546. .init = vp8_init,
  547. .encode2 = vp8_encode,
  548. .close = vp8_free,
  549. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  550. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  551. .priv_class = &class_vp8,
  552. .defaults = defaults,
  553. };
  554. #endif /* CONFIG_LIBVPX_VP8_ENCODER */
  555. #if CONFIG_LIBVPX_VP9_ENCODER
  556. static av_cold int vp9_init(AVCodecContext *avctx)
  557. {
  558. int ret;
  559. if ((ret = ff_vp9_check_experimental(avctx)))
  560. return ret;
  561. return vpx_init(avctx, &vpx_codec_vp9_cx_algo);
  562. }
  563. static const AVClass class_vp9 = {
  564. .class_name = "libvpx encoder",
  565. .item_name = av_default_item_name,
  566. .option = options,
  567. .version = LIBAVUTIL_VERSION_INT,
  568. };
  569. AVCodec ff_libvpx_vp9_encoder = {
  570. .name = "libvpx-vp9",
  571. .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
  572. .type = AVMEDIA_TYPE_VIDEO,
  573. .id = AV_CODEC_ID_VP9,
  574. .priv_data_size = sizeof(VP8Context),
  575. .init = vp9_init,
  576. .encode2 = vp8_encode,
  577. .close = vp8_free,
  578. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
  579. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  580. .priv_class = &class_vp9,
  581. .defaults = defaults,
  582. };
  583. #endif /* CONFIG_LIBVPX_VP9_ENCODER */