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