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.

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