libvpxenc.c 26 KB

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