2 * Copyright (c) 2010, Google, Inc.
4 * This file is part of Libav.
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.
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.
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
23 * VP8 encoder support via libvpx
26 #define VPX_DISABLE_CTRL_TYPECHECKS 1
27 #define VPX_CODEC_DISABLE_COMPAT 1
28 #include <vpx/vpx_encoder.h>
29 #include <vpx/vp8cx.h>
32 #include "libavutil/base64.h"
33 #include "libavutil/mathematics.h"
36 * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
37 * One encoded frame returned from the library.
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;
50 typedef struct VP8EncoderContext {
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;
58 /** String mappings for enum vp8e_enc_control_id */
59 static const char *ctlidstr[] = {
60 [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
61 [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
62 [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
63 [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
64 [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
65 [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
66 [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
67 [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
68 [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
69 [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
70 [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
71 [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
72 [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
73 [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
74 [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
75 [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
78 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
80 VP8Context *ctx = avctx->priv_data;
81 const char *error = vpx_codec_error(&ctx->encoder);
82 const char *detail = vpx_codec_error_detail(&ctx->encoder);
84 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
86 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
89 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
90 const struct vpx_codec_enc_cfg *cfg)
93 int level = AV_LOG_DEBUG;
95 av_log(avctx, level, "vpx_codec_enc_cfg\n");
96 av_log(avctx, level, "generic settings\n"
97 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
98 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
99 width, "g_usage:", cfg->g_usage,
100 width, "g_threads:", cfg->g_threads,
101 width, "g_profile:", cfg->g_profile,
102 width, "g_w:", cfg->g_w,
103 width, "g_h:", cfg->g_h,
104 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
105 width, "g_error_resilient:", cfg->g_error_resilient,
106 width, "g_pass:", cfg->g_pass,
107 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
108 av_log(avctx, level, "rate control settings\n"
109 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
110 " %*s%d\n %*s%p(%zu)\n %*s%u\n",
111 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
112 width, "rc_resize_allowed:", cfg->rc_resize_allowed,
113 width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
114 width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
115 width, "rc_end_usage:", cfg->rc_end_usage,
116 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
117 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
118 av_log(avctx, level, "quantizer settings\n"
120 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
121 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
122 av_log(avctx, level, "bitrate tolerance\n"
124 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
125 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
126 av_log(avctx, level, "decoder buffer model\n"
127 " %*s%u\n %*s%u\n %*s%u\n",
128 width, "rc_buf_sz:", cfg->rc_buf_sz,
129 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
130 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
131 av_log(avctx, level, "2 pass rate control settings\n"
132 " %*s%u\n %*s%u\n %*s%u\n",
133 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
134 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
135 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
136 av_log(avctx, level, "keyframing settings\n"
137 " %*s%d\n %*s%u\n %*s%u\n",
138 width, "kf_mode:", cfg->kf_mode,
139 width, "kf_min_dist:", cfg->kf_min_dist,
140 width, "kf_max_dist:", cfg->kf_max_dist);
141 av_log(avctx, level, "\n");
144 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
146 struct FrameListData **p = list;
151 cx_frame->next = NULL;
154 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
156 av_freep(&cx_frame->buf);
160 static av_cold void free_frame_list(struct FrameListData *list)
162 struct FrameListData *p = list;
171 static av_cold int codecctl_int(AVCodecContext *avctx,
172 enum vp8e_enc_control_id id, int val)
174 VP8Context *ctx = avctx->priv_data;
179 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
180 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
182 res = vpx_codec_control(&ctx->encoder, id, val);
183 if (res != VPX_CODEC_OK) {
184 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
186 log_encoder_error(avctx, buf);
189 return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
192 static av_cold int vp8_free(AVCodecContext *avctx)
194 VP8Context *ctx = avctx->priv_data;
196 vpx_codec_destroy(&ctx->encoder);
197 av_freep(&ctx->twopass_stats.buf);
198 av_freep(&avctx->coded_frame);
199 av_freep(&avctx->stats_out);
200 free_frame_list(ctx->coded_frame_list);
204 static av_cold int vp8_init(AVCodecContext *avctx)
206 VP8Context *ctx = avctx->priv_data;
207 const struct vpx_codec_iface *iface = &vpx_codec_vp8_cx_algo;
209 struct vpx_codec_enc_cfg enccfg;
212 av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
213 av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
215 if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
216 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
217 vpx_codec_err_to_string(res));
218 return AVERROR(EINVAL);
220 dump_enc_cfg(avctx, &enccfg);
222 enccfg.g_w = avctx->width;
223 enccfg.g_h = avctx->height;
224 enccfg.g_timebase.num = avctx->time_base.num;
225 enccfg.g_timebase.den = avctx->time_base.den;
226 enccfg.g_threads = avctx->thread_count;
228 if (avctx->flags & CODEC_FLAG_PASS1)
229 enccfg.g_pass = VPX_RC_FIRST_PASS;
230 else if (avctx->flags & CODEC_FLAG_PASS2)
231 enccfg.g_pass = VPX_RC_LAST_PASS;
233 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)
237 enccfg.rc_end_usage = VPX_CBR;
238 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
241 enccfg.rc_min_quantizer = avctx->qmin;
242 enccfg.rc_max_quantizer = avctx->qmax;
243 enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
245 //0-100 (0 => CBR, 100 => VBR)
246 enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
247 enccfg.rc_2pass_vbr_minsection_pct =
248 avctx->rc_min_rate * 100LL / avctx->bit_rate;
249 if (avctx->rc_max_rate)
250 enccfg.rc_2pass_vbr_maxsection_pct =
251 avctx->rc_max_rate * 100LL / avctx->bit_rate;
253 if (avctx->rc_buffer_size)
255 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
256 if (avctx->rc_initial_buffer_occupancy)
257 enccfg.rc_buf_initial_sz =
258 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
259 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
261 //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
262 if (avctx->keyint_min == avctx->gop_size)
263 enccfg.kf_min_dist = avctx->keyint_min;
264 enccfg.kf_max_dist = avctx->gop_size;
266 if (enccfg.g_pass == VPX_RC_FIRST_PASS)
267 enccfg.g_lag_in_frames = 0;
268 else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
271 if (!avctx->stats_in) {
272 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
273 return AVERROR_INVALIDDATA;
276 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
277 ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
278 if (!ctx->twopass_stats.buf) {
279 av_log(avctx, AV_LOG_ERROR,
280 "Stat buffer alloc (%zu bytes) failed\n",
281 ctx->twopass_stats.sz);
282 return AVERROR(ENOMEM);
284 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
285 ctx->twopass_stats.sz);
286 if (decode_size < 0) {
287 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
288 return AVERROR_INVALIDDATA;
291 ctx->twopass_stats.sz = decode_size;
292 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
295 ctx->deadline = VPX_DL_GOOD_QUALITY;
296 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
297 complexity playback on low powered devices at the expense of encode
299 if (avctx->profile != FF_PROFILE_UNKNOWN)
300 enccfg.g_profile = avctx->profile;
302 dump_enc_cfg(avctx, &enccfg);
303 /* Construct Encoder Context */
304 res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);
305 if (res != VPX_CODEC_OK) {
306 log_encoder_error(avctx, "Failed to initialize encoder");
307 return AVERROR(EINVAL);
310 //codec control failures are currently treated only as warnings
311 av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
312 codecctl_int(avctx, VP8E_SET_CPUUSED, cpuused);
313 codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
314 codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
315 codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, avctx->mb_threshold);
317 //provide dummy value to initialize wrapper, values will be updated each _encode()
318 vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
321 avctx->coded_frame = avcodec_alloc_frame();
322 if (!avctx->coded_frame) {
323 av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
325 return AVERROR(ENOMEM);
330 static inline void cx_pktcpy(struct FrameListData *dst,
331 const struct vpx_codec_cx_pkt *src)
333 dst->pts = src->data.frame.pts;
334 dst->duration = src->data.frame.duration;
335 dst->flags = src->data.frame.flags;
336 dst->sz = src->data.frame.sz;
337 dst->buf = src->data.frame.buf;
341 * Store coded frame information in format suitable for return from encode().
343 * Write buffer information from @a cx_frame to @a buf & @a buf_size.
344 * Timing/frame details to @a coded_frame.
345 * @return Frame size written to @a buf on success
346 * @return AVERROR(EINVAL) on error
348 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
349 uint8_t *buf, int buf_size, AVFrame *coded_frame)
351 if ((int) cx_frame->sz <= buf_size) {
352 buf_size = cx_frame->sz;
353 memcpy(buf, cx_frame->buf, buf_size);
354 coded_frame->pts = cx_frame->pts;
355 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;
360 coded_frame->pict_type = AV_PICTURE_TYPE_P;
362 av_log(avctx, AV_LOG_ERROR,
363 "Compressed frame larger than storage provided! (%zu/%d)\n",
364 cx_frame->sz, buf_size);
365 return AVERROR(EINVAL);
371 * Queue multiple output frames from the encoder, returning the front-most.
372 * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
373 * the frame queue. Return the head frame if available.
374 * @return Stored frame size
375 * @return AVERROR(EINVAL) on output size error
376 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
378 static int queue_frames(AVCodecContext *avctx, uint8_t *buf, int buf_size,
379 AVFrame *coded_frame)
381 VP8Context *ctx = avctx->priv_data;
382 const struct vpx_codec_cx_pkt *pkt;
383 const void *iter = NULL;
386 if (ctx->coded_frame_list) {
387 struct FrameListData *cx_frame = ctx->coded_frame_list;
388 /* return the leading frame if we've already begun queueing */
389 size = storeframe(avctx, cx_frame, buf, buf_size, coded_frame);
391 return AVERROR(EINVAL);
392 ctx->coded_frame_list = cx_frame->next;
393 free_coded_frame(cx_frame);
396 /* consume all available output from the encoder before returning. buffers
397 are only good through the next vpx_codec call */
398 while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
400 case VPX_CODEC_CX_FRAME_PKT:
402 struct FrameListData cx_frame;
404 /* avoid storing the frame when the list is empty and we haven't yet
405 provided a frame for output */
406 assert(!ctx->coded_frame_list);
407 cx_pktcpy(&cx_frame, pkt);
408 size = storeframe(avctx, &cx_frame, buf, buf_size, coded_frame);
410 return AVERROR(EINVAL);
412 struct FrameListData *cx_frame =
413 av_malloc(sizeof(struct FrameListData));
416 av_log(avctx, AV_LOG_ERROR,
417 "Frame queue element alloc failed\n");
418 return AVERROR(ENOMEM);
420 cx_pktcpy(cx_frame, pkt);
421 cx_frame->buf = av_malloc(cx_frame->sz);
423 if (!cx_frame->buf) {
424 av_log(avctx, AV_LOG_ERROR,
425 "Data buffer alloc (%zu bytes) failed\n",
427 return AVERROR(ENOMEM);
429 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
430 coded_frame_add(&ctx->coded_frame_list, cx_frame);
433 case VPX_CODEC_STATS_PKT: {
434 struct vpx_fixed_buf *stats = &ctx->twopass_stats;
435 stats->buf = av_realloc(stats->buf,
436 stats->sz + pkt->data.twopass_stats.sz);
438 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
439 return AVERROR(ENOMEM);
441 memcpy((uint8_t*)stats->buf + stats->sz,
442 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
443 stats->sz += pkt->data.twopass_stats.sz;
446 case VPX_CODEC_PSNR_PKT: //FIXME add support for CODEC_FLAG_PSNR
447 case VPX_CODEC_CUSTOM_PKT:
448 //ignore unsupported/unrecognized packet types
456 static int vp8_encode(AVCodecContext *avctx, uint8_t *buf, int buf_size,
459 VP8Context *ctx = avctx->priv_data;
460 AVFrame *frame = data;
461 struct vpx_image *rawimg = NULL;
462 int64_t timestamp = 0;
466 rawimg = &ctx->rawimg;
467 rawimg->planes[VPX_PLANE_Y] = frame->data[0];
468 rawimg->planes[VPX_PLANE_U] = frame->data[1];
469 rawimg->planes[VPX_PLANE_V] = frame->data[2];
470 rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
471 rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
472 rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
473 timestamp = frame->pts;
476 res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
477 avctx->ticks_per_frame, 0, ctx->deadline);
478 if (res != VPX_CODEC_OK) {
479 log_encoder_error(avctx, "Error encoding frame");
480 return AVERROR_INVALIDDATA;
482 coded_size = queue_frames(avctx, buf, buf_size, avctx->coded_frame);
484 if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
485 unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
487 avctx->stats_out = av_malloc(b64_size);
488 if (!avctx->stats_out) {
489 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
491 return AVERROR(ENOMEM);
493 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
494 ctx->twopass_stats.sz);
499 AVCodec ff_libvpx_encoder = {
509 .pix_fmts = (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
510 .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),