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