2 * Copyright (c) 2010, Google, Inc.
4 * This file is part of FFmpeg.
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.
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.
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
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>
33 #include "libavutil/avassert.h"
34 #include "libavutil/base64.h"
35 #include "libavutil/common.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/opt.h"
40 * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
41 * One encoded frame returned from the library.
43 struct FrameListData {
44 void *buf; /**< compressed data buffer */
45 size_t sz; /**< length of compressed data */
46 int64_t pts; /**< time stamp to show frame
47 (in timebase units) */
48 unsigned long duration; /**< duration to show frame
49 (in timebase units) */
50 uint32_t flags; /**< flags for this frame */
52 int have_sse; /**< true if we have pending sse[] */
53 uint64_t frame_number;
54 struct FrameListData *next;
57 typedef struct VP8EncoderContext {
59 struct vpx_codec_ctx encoder;
60 struct vpx_image rawimg;
61 struct vpx_fixed_buf twopass_stats;
62 int deadline; //i.e., RT/GOOD/BEST
64 int have_sse; /**< true if we have pending sse[] */
65 uint64_t frame_number;
66 struct FrameListData *coded_frame_list;
70 * VP8 specific flags, see VP8F_* below.
73 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
74 #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
88 /** String mappings for enum vp8e_enc_control_id */
89 static const char *const ctlidstr[] = {
90 [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
91 [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
92 [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
93 [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
94 [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
95 [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
96 [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
97 [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
98 [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
99 [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
100 [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
101 [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
102 [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
103 [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
104 [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
105 [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
106 [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
107 [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
110 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
112 VP8Context *ctx = avctx->priv_data;
113 const char *error = vpx_codec_error(&ctx->encoder);
114 const char *detail = vpx_codec_error_detail(&ctx->encoder);
116 av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
118 av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
121 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
122 const struct vpx_codec_enc_cfg *cfg)
125 int level = AV_LOG_DEBUG;
127 av_log(avctx, level, "vpx_codec_enc_cfg\n");
128 av_log(avctx, level, "generic settings\n"
129 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
130 " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
131 width, "g_usage:", cfg->g_usage,
132 width, "g_threads:", cfg->g_threads,
133 width, "g_profile:", cfg->g_profile,
134 width, "g_w:", cfg->g_w,
135 width, "g_h:", cfg->g_h,
136 width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
137 width, "g_error_resilient:", cfg->g_error_resilient,
138 width, "g_pass:", cfg->g_pass,
139 width, "g_lag_in_frames:", cfg->g_lag_in_frames);
140 av_log(avctx, level, "rate control settings\n"
141 " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
142 " %*s%d\n %*s%p(%zu)\n %*s%u\n",
143 width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
144 width, "rc_resize_allowed:", cfg->rc_resize_allowed,
145 width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
146 width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
147 width, "rc_end_usage:", cfg->rc_end_usage,
148 width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
149 width, "rc_target_bitrate:", cfg->rc_target_bitrate);
150 av_log(avctx, level, "quantizer settings\n"
152 width, "rc_min_quantizer:", cfg->rc_min_quantizer,
153 width, "rc_max_quantizer:", cfg->rc_max_quantizer);
154 av_log(avctx, level, "bitrate tolerance\n"
156 width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
157 width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
158 av_log(avctx, level, "decoder buffer model\n"
159 " %*s%u\n %*s%u\n %*s%u\n",
160 width, "rc_buf_sz:", cfg->rc_buf_sz,
161 width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
162 width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
163 av_log(avctx, level, "2 pass rate control settings\n"
164 " %*s%u\n %*s%u\n %*s%u\n",
165 width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
166 width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
167 width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
168 av_log(avctx, level, "keyframing settings\n"
169 " %*s%d\n %*s%u\n %*s%u\n",
170 width, "kf_mode:", cfg->kf_mode,
171 width, "kf_min_dist:", cfg->kf_min_dist,
172 width, "kf_max_dist:", cfg->kf_max_dist);
173 av_log(avctx, level, "\n");
176 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
178 struct FrameListData **p = list;
183 cx_frame->next = NULL;
186 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
188 av_freep(&cx_frame->buf);
192 static av_cold void free_frame_list(struct FrameListData *list)
194 struct FrameListData *p = list;
203 static av_cold int codecctl_int(AVCodecContext *avctx,
204 enum vp8e_enc_control_id id, int val)
206 VP8Context *ctx = avctx->priv_data;
211 snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
212 av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
214 res = vpx_codec_control(&ctx->encoder, id, val);
215 if (res != VPX_CODEC_OK) {
216 snprintf(buf, sizeof(buf), "Failed to set %s codec control",
218 log_encoder_error(avctx, buf);
221 return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
224 static av_cold int vp8_free(AVCodecContext *avctx)
226 VP8Context *ctx = avctx->priv_data;
228 vpx_codec_destroy(&ctx->encoder);
229 av_freep(&ctx->twopass_stats.buf);
230 av_freep(&avctx->coded_frame);
231 av_freep(&avctx->stats_out);
232 free_frame_list(ctx->coded_frame_list);
236 static av_cold int vpx_init(AVCodecContext *avctx,
237 const struct vpx_codec_iface *iface)
239 VP8Context *ctx = avctx->priv_data;
240 struct vpx_codec_enc_cfg enccfg;
241 vpx_codec_flags_t flags = (avctx->flags & CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
244 av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
245 av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
247 if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
248 av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
249 vpx_codec_err_to_string(res));
250 return AVERROR(EINVAL);
254 if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
255 av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
256 return AVERROR(EINVAL);
259 dump_enc_cfg(avctx, &enccfg);
261 enccfg.g_w = avctx->width;
262 enccfg.g_h = avctx->height;
263 enccfg.g_timebase.num = avctx->time_base.num;
264 enccfg.g_timebase.den = avctx->time_base.den;
265 enccfg.g_threads = avctx->thread_count;
266 enccfg.g_lag_in_frames= ctx->lag_in_frames;
268 if (avctx->flags & CODEC_FLAG_PASS1)
269 enccfg.g_pass = VPX_RC_FIRST_PASS;
270 else if (avctx->flags & CODEC_FLAG_PASS2)
271 enccfg.g_pass = VPX_RC_LAST_PASS;
273 enccfg.g_pass = VPX_RC_ONE_PASS;
275 if (avctx->rc_min_rate == avctx->rc_max_rate &&
276 avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate)
277 enccfg.rc_end_usage = VPX_CBR;
279 enccfg.rc_end_usage = VPX_CQ;
281 if (avctx->bit_rate) {
282 enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
285 if (enccfg.rc_end_usage == VPX_CQ) {
286 enccfg.rc_target_bitrate = 1000000;
288 avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
289 av_log(avctx, AV_LOG_WARNING,
290 "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
291 enccfg.rc_target_bitrate);
295 if (avctx->qmin >= 0)
296 enccfg.rc_min_quantizer = avctx->qmin;
298 enccfg.rc_max_quantizer = avctx->qmax;
300 if (enccfg.rc_end_usage == VPX_CQ) {
301 if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
302 av_log(avctx, AV_LOG_ERROR,
303 "CQ level must be between minimum and maximum quantizer value (%d-%d)\n",
304 enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
305 return AVERROR(EINVAL);
309 enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
311 //0-100 (0 => CBR, 100 => VBR)
312 enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
314 enccfg.rc_2pass_vbr_minsection_pct =
315 avctx->rc_min_rate * 100LL / avctx->bit_rate;
316 if (avctx->rc_max_rate)
317 enccfg.rc_2pass_vbr_maxsection_pct =
318 avctx->rc_max_rate * 100LL / avctx->bit_rate;
320 if (avctx->rc_buffer_size)
322 avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
323 if (avctx->rc_initial_buffer_occupancy)
324 enccfg.rc_buf_initial_sz =
325 avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
326 enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
327 enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
329 //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
330 if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
331 enccfg.kf_min_dist = avctx->keyint_min;
332 if (avctx->gop_size >= 0)
333 enccfg.kf_max_dist = avctx->gop_size;
335 if (enccfg.g_pass == VPX_RC_FIRST_PASS)
336 enccfg.g_lag_in_frames = 0;
337 else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
340 if (!avctx->stats_in) {
341 av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
342 return AVERROR_INVALIDDATA;
345 ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
346 ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
347 if (!ctx->twopass_stats.buf) {
348 av_log(avctx, AV_LOG_ERROR,
349 "Stat buffer alloc (%zu bytes) failed\n",
350 ctx->twopass_stats.sz);
351 return AVERROR(ENOMEM);
353 decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
354 ctx->twopass_stats.sz);
355 if (decode_size < 0) {
356 av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
357 return AVERROR_INVALIDDATA;
360 ctx->twopass_stats.sz = decode_size;
361 enccfg.rc_twopass_stats_in = ctx->twopass_stats;
364 /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
365 complexity playback on low powered devices at the expense of encode
367 if (avctx->profile != FF_PROFILE_UNKNOWN)
368 enccfg.g_profile = avctx->profile;
370 enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
372 dump_enc_cfg(avctx, &enccfg);
373 /* Construct Encoder Context */
374 res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
375 if (res != VPX_CODEC_OK) {
376 log_encoder_error(avctx, "Failed to initialize encoder");
377 return AVERROR(EINVAL);
380 //codec control failures are currently treated only as warnings
381 av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
382 if (ctx->cpu_used != INT_MIN)
383 codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
384 if (ctx->flags & VP8F_AUTO_ALT_REF)
385 ctx->auto_alt_ref = 1;
386 if (ctx->auto_alt_ref >= 0)
387 codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
388 if (ctx->arnr_max_frames >= 0)
389 codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
390 if (ctx->arnr_strength >= 0)
391 codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
392 if (ctx->arnr_type >= 0)
393 codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
394 codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
395 codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
396 codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, avctx->mb_threshold);
397 codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
398 if (ctx->max_intra_rate >= 0)
399 codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
401 av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
403 //provide dummy value to initialize wrapper, values will be updated each _encode()
404 vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
407 avctx->coded_frame = avcodec_alloc_frame();
408 if (!avctx->coded_frame) {
409 av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
411 return AVERROR(ENOMEM);
416 static inline void cx_pktcpy(struct FrameListData *dst,
417 const struct vpx_codec_cx_pkt *src,
420 dst->pts = src->data.frame.pts;
421 dst->duration = src->data.frame.duration;
422 dst->flags = src->data.frame.flags;
423 dst->sz = src->data.frame.sz;
424 dst->buf = src->data.frame.buf;
426 /* For alt-ref frame, don't store PSNR or increment frame_number */
427 if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
428 dst->frame_number = ++ctx->frame_number;
429 dst->have_sse = ctx->have_sse;
431 /* associate last-seen SSE to the frame. */
432 /* Transfers ownership from ctx to dst. */
433 /* WARNING! This makes the assumption that PSNR_PKT comes
434 just before the frame it refers to! */
435 memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
439 dst->frame_number = -1; /* sanity marker */
444 * Store coded frame information in format suitable for return from encode2().
446 * Write information from @a cx_frame to @a pkt
447 * @return packet data size on success
448 * @return a negative AVERROR on error
450 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
451 AVPacket *pkt, AVFrame *coded_frame)
453 int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz);
455 memcpy(pkt->data, cx_frame->buf, pkt->size);
456 pkt->pts = pkt->dts = cx_frame->pts;
457 coded_frame->pts = cx_frame->pts;
458 coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
460 if (coded_frame->key_frame) {
461 coded_frame->pict_type = AV_PICTURE_TYPE_I;
462 pkt->flags |= AV_PKT_FLAG_KEY;
464 coded_frame->pict_type = AV_PICTURE_TYPE_P;
466 if (cx_frame->have_sse) {
468 /* Beware of the Y/U/V/all order! */
469 coded_frame->error[0] = cx_frame->sse[1];
470 coded_frame->error[1] = cx_frame->sse[2];
471 coded_frame->error[2] = cx_frame->sse[3];
472 coded_frame->error[3] = 0; // alpha
473 for (i = 0; i < 4; ++i) {
474 avctx->error[i] += coded_frame->error[i];
476 cx_frame->have_sse = 0;
485 * Queue multiple output frames from the encoder, returning the front-most.
486 * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
487 * the frame queue. Return the head frame if available.
488 * @return Stored frame size
489 * @return AVERROR(EINVAL) on output size error
490 * @return AVERROR(ENOMEM) on coded frame queue data allocation error
492 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out,
493 AVFrame *coded_frame)
495 VP8Context *ctx = avctx->priv_data;
496 const struct vpx_codec_cx_pkt *pkt;
497 const void *iter = NULL;
500 if (ctx->coded_frame_list) {
501 struct FrameListData *cx_frame = ctx->coded_frame_list;
502 /* return the leading frame if we've already begun queueing */
503 size = storeframe(avctx, cx_frame, pkt_out, coded_frame);
506 ctx->coded_frame_list = cx_frame->next;
507 free_coded_frame(cx_frame);
510 /* consume all available output from the encoder before returning. buffers
511 are only good through the next vpx_codec call */
512 while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter))) {
514 case VPX_CODEC_CX_FRAME_PKT:
516 struct FrameListData cx_frame;
518 /* avoid storing the frame when the list is empty and we haven't yet
519 provided a frame for output */
520 av_assert0(!ctx->coded_frame_list);
521 cx_pktcpy(&cx_frame, pkt, ctx);
522 size = storeframe(avctx, &cx_frame, pkt_out, coded_frame);
526 struct FrameListData *cx_frame =
527 av_malloc(sizeof(struct FrameListData));
530 av_log(avctx, AV_LOG_ERROR,
531 "Frame queue element alloc failed\n");
532 return AVERROR(ENOMEM);
534 cx_pktcpy(cx_frame, pkt, ctx);
535 cx_frame->buf = av_malloc(cx_frame->sz);
537 if (!cx_frame->buf) {
538 av_log(avctx, AV_LOG_ERROR,
539 "Data buffer alloc (%zu bytes) failed\n",
542 return AVERROR(ENOMEM);
544 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
545 coded_frame_add(&ctx->coded_frame_list, cx_frame);
548 case VPX_CODEC_STATS_PKT: {
549 struct vpx_fixed_buf *stats = &ctx->twopass_stats;
550 stats->buf = av_realloc_f(stats->buf, 1,
551 stats->sz + pkt->data.twopass_stats.sz);
553 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
554 return AVERROR(ENOMEM);
556 memcpy((uint8_t*)stats->buf + stats->sz,
557 pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
558 stats->sz += pkt->data.twopass_stats.sz;
561 case VPX_CODEC_PSNR_PKT:
562 av_assert0(!ctx->have_sse);
563 ctx->sse[0] = pkt->data.psnr.sse[0];
564 ctx->sse[1] = pkt->data.psnr.sse[1];
565 ctx->sse[2] = pkt->data.psnr.sse[2];
566 ctx->sse[3] = pkt->data.psnr.sse[3];
569 case VPX_CODEC_CUSTOM_PKT:
570 //ignore unsupported/unrecognized packet types
578 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
579 const AVFrame *frame, int *got_packet)
581 VP8Context *ctx = avctx->priv_data;
582 struct vpx_image *rawimg = NULL;
583 int64_t timestamp = 0;
585 vpx_enc_frame_flags_t flags = 0;
588 rawimg = &ctx->rawimg;
589 rawimg->planes[VPX_PLANE_Y] = frame->data[0];
590 rawimg->planes[VPX_PLANE_U] = frame->data[1];
591 rawimg->planes[VPX_PLANE_V] = frame->data[2];
592 rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
593 rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
594 rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
595 timestamp = frame->pts;
596 if (frame->pict_type == AV_PICTURE_TYPE_I)
597 flags |= VPX_EFLAG_FORCE_KF;
600 res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
601 avctx->ticks_per_frame, flags, ctx->deadline);
602 if (res != VPX_CODEC_OK) {
603 log_encoder_error(avctx, "Error encoding frame");
604 return AVERROR_INVALIDDATA;
606 coded_size = queue_frames(avctx, pkt, avctx->coded_frame);
608 if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
609 unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
611 avctx->stats_out = av_malloc(b64_size);
612 if (!avctx->stats_out) {
613 av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
615 return AVERROR(ENOMEM);
617 av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
618 ctx->twopass_stats.sz);
621 *got_packet = !!coded_size;
625 #define OFFSET(x) offsetof(VP8Context, x)
626 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
627 static const AVOption options[] = {
628 { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = INT_MIN}, INT_MIN, INT_MAX, VE},
629 { "auto-alt-ref", "Enable use of alternate reference "
630 "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
631 { "lag-in-frames", "Number of frames to look ahead for "
632 "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
633 { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
634 { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
635 { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"},
636 { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" },
637 { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" },
638 { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" },
639 { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
640 { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"},
641 { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"},
642 { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"},
643 { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"},
644 { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE},
645 #ifdef VPX_ERROR_RESILIENT_DEFAULT
646 { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"},
647 { "partitions", "The frame partitions are independently decodable "
648 "by the bool decoder, meaning that partitions can be decoded even "
649 "though earlier partitions have been lost. Note that intra predicition"
650 " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"},
652 {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 3}, -16, 16, VE},
653 {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"},
654 {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"},
655 {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"},
656 {"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"},
657 {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE},
658 {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE},
659 {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE},
660 {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE},
661 { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE },
665 static const AVCodecDefault defaults[] = {
669 { "keyint_min", "-1" },
673 #if CONFIG_LIBVPX_VP8_ENCODER
674 static av_cold int vp8_init(AVCodecContext *avctx)
676 return vpx_init(avctx, &vpx_codec_vp8_cx_algo);
679 static const AVClass class_vp8 = {
680 .class_name = "libvpx encoder",
681 .item_name = av_default_item_name,
683 .version = LIBAVUTIL_VERSION_INT,
686 AVCodec ff_libvpx_vp8_encoder = {
688 .type = AVMEDIA_TYPE_VIDEO,
689 .id = AV_CODEC_ID_VP8,
690 .priv_data_size = sizeof(VP8Context),
692 .encode2 = vp8_encode,
694 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
695 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
696 .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
697 .priv_class = &class_vp8,
698 .defaults = defaults,
700 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
702 #if CONFIG_LIBVPX_VP9_ENCODER
703 static av_cold int vp9_init(AVCodecContext *avctx)
705 return vpx_init(avctx, &vpx_codec_vp9_cx_algo);
708 static const AVClass class_vp9 = {
709 .class_name = "libvpx encoder",
710 .item_name = av_default_item_name,
712 .version = LIBAVUTIL_VERSION_INT,
715 AVCodec ff_libvpx_vp9_encoder = {
716 .name = "libvpx-vp9",
717 .type = AVMEDIA_TYPE_VIDEO,
718 .id = AV_CODEC_ID_VP9,
719 .priv_data_size = sizeof(VP8Context),
721 .encode2 = vp8_encode,
723 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS | CODEC_CAP_EXPERIMENTAL,
724 .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
725 .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
726 .priv_class = &class_vp9,
727 .defaults = defaults,
729 #endif /* CONFIG_LIBVPX_VP9_ENCODER */