]> git.sesse.net Git - ffmpeg/blob - libavcodec/libvpxenc.c
Merge commit 'd4df02131b5522a99a4e6035368484e809706ed5'
[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/avassert.h"
34 #include "libavutil/base64.h"
35 #include "libavutil/common.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
39
40 /**
41  * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
42  * One encoded frame returned from the library.
43  */
44 struct FrameListData {
45     void *buf;                       /**< compressed data buffer */
46     size_t sz;                       /**< length of compressed data */
47     void *buf_alpha;
48     size_t sz_alpha;
49     int64_t pts;                     /**< time stamp to show frame
50                                           (in timebase units) */
51     unsigned long duration;          /**< duration to show frame
52                                           (in timebase units) */
53     uint32_t flags;                  /**< flags for this frame */
54     uint64_t sse[4];
55     int have_sse;                    /**< true if we have pending sse[] */
56     uint64_t frame_number;
57     struct FrameListData *next;
58 };
59
60 typedef struct VP8EncoderContext {
61     AVClass *class;
62     struct vpx_codec_ctx encoder;
63     struct vpx_image rawimg;
64     struct vpx_codec_ctx encoder_alpha;
65     struct vpx_image rawimg_alpha;
66     uint8_t is_alpha;
67     struct vpx_fixed_buf twopass_stats;
68     int deadline; //i.e., RT/GOOD/BEST
69     uint64_t sse[4];
70     int have_sse; /**< true if we have pending sse[] */
71     uint64_t frame_number;
72     struct FrameListData *coded_frame_list;
73
74     int cpu_used;
75     /**
76      * VP8 specific flags, see VP8F_* below.
77      */
78     int flags;
79 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
80 #define VP8F_AUTO_ALT_REF    0x00000002 ///< Enable automatic alternate reference frame generation
81
82     int auto_alt_ref;
83
84     int arnr_max_frames;
85     int arnr_strength;
86     int arnr_type;
87
88     int lag_in_frames;
89     int error_resilient;
90     int crf;
91     int max_intra_rate;
92
93     // VP9-only
94     int lossless;
95     int tile_columns;
96     int tile_rows;
97     int frame_parallel;
98 } VP8Context;
99
100 /** String mappings for enum vp8e_enc_control_id */
101 static const char *const ctlidstr[] = {
102     [VP8E_UPD_ENTROPY]           = "VP8E_UPD_ENTROPY",
103     [VP8E_UPD_REFERENCE]         = "VP8E_UPD_REFERENCE",
104     [VP8E_USE_REFERENCE]         = "VP8E_USE_REFERENCE",
105     [VP8E_SET_ROI_MAP]           = "VP8E_SET_ROI_MAP",
106     [VP8E_SET_ACTIVEMAP]         = "VP8E_SET_ACTIVEMAP",
107     [VP8E_SET_SCALEMODE]         = "VP8E_SET_SCALEMODE",
108     [VP8E_SET_CPUUSED]           = "VP8E_SET_CPUUSED",
109     [VP8E_SET_ENABLEAUTOALTREF]  = "VP8E_SET_ENABLEAUTOALTREF",
110     [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
111     [VP8E_SET_SHARPNESS]         = "VP8E_SET_SHARPNESS",
112     [VP8E_SET_STATIC_THRESHOLD]  = "VP8E_SET_STATIC_THRESHOLD",
113     [VP8E_SET_TOKEN_PARTITIONS]  = "VP8E_SET_TOKEN_PARTITIONS",
114     [VP8E_GET_LAST_QUANTIZER]    = "VP8E_GET_LAST_QUANTIZER",
115     [VP8E_SET_ARNR_MAXFRAMES]    = "VP8E_SET_ARNR_MAXFRAMES",
116     [VP8E_SET_ARNR_STRENGTH]     = "VP8E_SET_ARNR_STRENGTH",
117     [VP8E_SET_ARNR_TYPE]         = "VP8E_SET_ARNR_TYPE",
118     [VP8E_SET_CQ_LEVEL]          = "VP8E_SET_CQ_LEVEL",
119     [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
120 #if CONFIG_LIBVPX_VP9_ENCODER
121     [VP9E_SET_LOSSLESS]                = "VP9E_SET_LOSSLESS",
122     [VP9E_SET_TILE_COLUMNS]            = "VP9E_SET_TILE_COLUMNS",
123     [VP9E_SET_TILE_ROWS]               = "VP9E_SET_TILE_ROWS",
124     [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
125 #endif
126 };
127
128 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
129 {
130     VP8Context *ctx = avctx->priv_data;
131     const char *error  = vpx_codec_error(&ctx->encoder);
132     const char *detail = vpx_codec_error_detail(&ctx->encoder);
133
134     av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
135     if (detail)
136         av_log(avctx, AV_LOG_ERROR, "  Additional information: %s\n", detail);
137 }
138
139 static av_cold void dump_enc_cfg(AVCodecContext *avctx,
140                                  const struct vpx_codec_enc_cfg *cfg)
141 {
142     int width = -30;
143     int level = AV_LOG_DEBUG;
144
145     av_log(avctx, level, "vpx_codec_enc_cfg\n");
146     av_log(avctx, level, "generic settings\n"
147            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
148            "  %*s{%u/%u}\n  %*s%u\n  %*s%d\n  %*s%u\n",
149            width, "g_usage:",           cfg->g_usage,
150            width, "g_threads:",         cfg->g_threads,
151            width, "g_profile:",         cfg->g_profile,
152            width, "g_w:",               cfg->g_w,
153            width, "g_h:",               cfg->g_h,
154            width, "g_timebase:",        cfg->g_timebase.num, cfg->g_timebase.den,
155            width, "g_error_resilient:", cfg->g_error_resilient,
156            width, "g_pass:",            cfg->g_pass,
157            width, "g_lag_in_frames:",   cfg->g_lag_in_frames);
158     av_log(avctx, level, "rate control settings\n"
159            "  %*s%u\n  %*s%u\n  %*s%u\n  %*s%u\n"
160            "  %*s%d\n  %*s%p(%zu)\n  %*s%u\n",
161            width, "rc_dropframe_thresh:",   cfg->rc_dropframe_thresh,
162            width, "rc_resize_allowed:",     cfg->rc_resize_allowed,
163            width, "rc_resize_up_thresh:",   cfg->rc_resize_up_thresh,
164            width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
165            width, "rc_end_usage:",          cfg->rc_end_usage,
166            width, "rc_twopass_stats_in:",   cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
167            width, "rc_target_bitrate:",     cfg->rc_target_bitrate);
168     av_log(avctx, level, "quantizer settings\n"
169            "  %*s%u\n  %*s%u\n",
170            width, "rc_min_quantizer:", cfg->rc_min_quantizer,
171            width, "rc_max_quantizer:", cfg->rc_max_quantizer);
172     av_log(avctx, level, "bitrate tolerance\n"
173            "  %*s%u\n  %*s%u\n",
174            width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
175            width, "rc_overshoot_pct:",  cfg->rc_overshoot_pct);
176     av_log(avctx, level, "decoder buffer model\n"
177             "  %*s%u\n  %*s%u\n  %*s%u\n",
178             width, "rc_buf_sz:",         cfg->rc_buf_sz,
179             width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
180             width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
181     av_log(avctx, level, "2 pass rate control settings\n"
182            "  %*s%u\n  %*s%u\n  %*s%u\n",
183            width, "rc_2pass_vbr_bias_pct:",       cfg->rc_2pass_vbr_bias_pct,
184            width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
185            width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
186     av_log(avctx, level, "keyframing settings\n"
187            "  %*s%d\n  %*s%u\n  %*s%u\n",
188            width, "kf_mode:",     cfg->kf_mode,
189            width, "kf_min_dist:", cfg->kf_min_dist,
190            width, "kf_max_dist:", cfg->kf_max_dist);
191     av_log(avctx, level, "\n");
192 }
193
194 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
195 {
196     struct FrameListData **p = list;
197
198     while (*p != NULL)
199         p = &(*p)->next;
200     *p = cx_frame;
201     cx_frame->next = NULL;
202 }
203
204 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
205 {
206     av_freep(&cx_frame->buf);
207     if (cx_frame->buf_alpha)
208         av_freep(&cx_frame->buf_alpha);
209     av_freep(&cx_frame);
210 }
211
212 static av_cold void free_frame_list(struct FrameListData *list)
213 {
214     struct FrameListData *p = list;
215
216     while (p) {
217         list = list->next;
218         free_coded_frame(p);
219         p = list;
220     }
221 }
222
223 static av_cold int codecctl_int(AVCodecContext *avctx,
224                                 enum vp8e_enc_control_id id, int val)
225 {
226     VP8Context *ctx = avctx->priv_data;
227     char buf[80];
228     int width = -30;
229     int res;
230
231     snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
232     av_log(avctx, AV_LOG_DEBUG, "  %*s%d\n", width, buf, val);
233
234     res = vpx_codec_control(&ctx->encoder, id, val);
235     if (res != VPX_CODEC_OK) {
236         snprintf(buf, sizeof(buf), "Failed to set %s codec control",
237                  ctlidstr[id]);
238         log_encoder_error(avctx, buf);
239     }
240
241     return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
242 }
243
244 static av_cold int vp8_free(AVCodecContext *avctx)
245 {
246     VP8Context *ctx = avctx->priv_data;
247
248     vpx_codec_destroy(&ctx->encoder);
249     if (ctx->is_alpha)
250         vpx_codec_destroy(&ctx->encoder_alpha);
251     av_freep(&ctx->twopass_stats.buf);
252     av_freep(&avctx->coded_frame);
253     av_freep(&avctx->stats_out);
254     free_frame_list(ctx->coded_frame_list);
255     return 0;
256 }
257
258 static av_cold int vpx_init(AVCodecContext *avctx,
259                             const struct vpx_codec_iface *iface)
260 {
261     VP8Context *ctx = avctx->priv_data;
262     struct vpx_codec_enc_cfg enccfg;
263     struct vpx_codec_enc_cfg enccfg_alpha;
264     vpx_codec_flags_t flags = (avctx->flags & CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
265     int res;
266
267     av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
268     av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
269
270     if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
271         ctx->is_alpha = 1;
272
273     if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
274         av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
275                vpx_codec_err_to_string(res));
276         return AVERROR(EINVAL);
277     }
278
279     if(!avctx->bit_rate)
280         if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
281             av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
282             return AVERROR(EINVAL);
283         }
284
285     dump_enc_cfg(avctx, &enccfg);
286
287     enccfg.g_w            = avctx->width;
288     enccfg.g_h            = avctx->height;
289     enccfg.g_timebase.num = avctx->time_base.num;
290     enccfg.g_timebase.den = avctx->time_base.den;
291     enccfg.g_threads      = avctx->thread_count;
292     enccfg.g_lag_in_frames= ctx->lag_in_frames;
293
294     if (avctx->flags & CODEC_FLAG_PASS1)
295         enccfg.g_pass = VPX_RC_FIRST_PASS;
296     else if (avctx->flags & CODEC_FLAG_PASS2)
297         enccfg.g_pass = VPX_RC_LAST_PASS;
298     else
299         enccfg.g_pass = VPX_RC_ONE_PASS;
300
301     if (avctx->rc_min_rate == avctx->rc_max_rate &&
302         avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate)
303         enccfg.rc_end_usage = VPX_CBR;
304     else if (ctx->crf)
305         enccfg.rc_end_usage = VPX_CQ;
306
307     if (avctx->bit_rate) {
308         enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
309                                                 AV_ROUND_NEAR_INF);
310     } else {
311         if (enccfg.rc_end_usage == VPX_CQ) {
312             enccfg.rc_target_bitrate = 1000000;
313         } else {
314             avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
315             av_log(avctx, AV_LOG_WARNING,
316                    "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
317                    enccfg.rc_target_bitrate);
318         }
319     }
320
321     if (avctx->qmin >= 0)
322         enccfg.rc_min_quantizer = avctx->qmin;
323     if (avctx->qmax >= 0)
324         enccfg.rc_max_quantizer = avctx->qmax;
325
326     if (enccfg.rc_end_usage == VPX_CQ) {
327         if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
328                 av_log(avctx, AV_LOG_ERROR,
329                        "CQ level must be between minimum and maximum quantizer value (%d-%d)\n",
330                        enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
331                 return AVERROR(EINVAL);
332         }
333     }
334
335     enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
336
337     //0-100 (0 => CBR, 100 => VBR)
338     enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);
339     if (avctx->bit_rate)
340         enccfg.rc_2pass_vbr_minsection_pct     =
341             avctx->rc_min_rate * 100LL / avctx->bit_rate;
342     if (avctx->rc_max_rate)
343         enccfg.rc_2pass_vbr_maxsection_pct =
344             avctx->rc_max_rate * 100LL / avctx->bit_rate;
345
346     if (avctx->rc_buffer_size)
347         enccfg.rc_buf_sz         =
348             avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
349     if (avctx->rc_initial_buffer_occupancy)
350         enccfg.rc_buf_initial_sz =
351             avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
352     enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;
353     enccfg.rc_undershoot_pct     = round(avctx->rc_buffer_aggressivity * 100);
354
355     //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
356     if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
357         enccfg.kf_min_dist = avctx->keyint_min;
358     if (avctx->gop_size >= 0)
359         enccfg.kf_max_dist = avctx->gop_size;
360
361     if (enccfg.g_pass == VPX_RC_FIRST_PASS)
362         enccfg.g_lag_in_frames = 0;
363     else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
364         int decode_size;
365
366         if (!avctx->stats_in) {
367             av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
368             return AVERROR_INVALIDDATA;
369         }
370
371         ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;
372         ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);
373         if (!ctx->twopass_stats.buf) {
374             av_log(avctx, AV_LOG_ERROR,
375                    "Stat buffer alloc (%zu bytes) failed\n",
376                    ctx->twopass_stats.sz);
377             return AVERROR(ENOMEM);
378         }
379         decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
380                                        ctx->twopass_stats.sz);
381         if (decode_size < 0) {
382             av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
383             return AVERROR_INVALIDDATA;
384         }
385
386         ctx->twopass_stats.sz      = decode_size;
387         enccfg.rc_twopass_stats_in = ctx->twopass_stats;
388     }
389
390     /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
391        complexity playback on low powered devices at the expense of encode
392        quality. */
393    if (avctx->profile != FF_PROFILE_UNKNOWN)
394        enccfg.g_profile = avctx->profile;
395
396     enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
397
398     dump_enc_cfg(avctx, &enccfg);
399     /* Construct Encoder Context */
400     res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
401     if (res != VPX_CODEC_OK) {
402         log_encoder_error(avctx, "Failed to initialize encoder");
403         return AVERROR(EINVAL);
404     }
405
406     if (ctx->is_alpha) {
407         enccfg_alpha = enccfg;
408         res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
409         if (res != VPX_CODEC_OK) {
410             log_encoder_error(avctx, "Failed to initialize alpha encoder");
411             return AVERROR(EINVAL);
412         }
413     }
414
415     //codec control failures are currently treated only as warnings
416     av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
417     if (ctx->cpu_used != INT_MIN)
418         codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);
419     if (ctx->flags & VP8F_AUTO_ALT_REF)
420         ctx->auto_alt_ref = 1;
421     if (ctx->auto_alt_ref >= 0)
422         codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
423     if (ctx->arnr_max_frames >= 0)
424         codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);
425     if (ctx->arnr_strength >= 0)
426         codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);
427     if (ctx->arnr_type >= 0)
428         codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);
429     codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
430     codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));
431     codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  avctx->mb_threshold);
432     codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);
433     if (ctx->max_intra_rate >= 0)
434         codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
435
436 #if CONFIG_LIBVPX_VP9_ENCODER
437     if (avctx->codec_id == AV_CODEC_ID_VP9) {
438         if (ctx->lossless >= 0)
439             codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
440         if (ctx->tile_columns >= 0)
441             codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
442         if (ctx->tile_rows >= 0)
443             codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
444         if (ctx->frame_parallel >= 0)
445             codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
446     }
447 #endif
448
449     av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
450
451     //provide dummy value to initialize wrapper, values will be updated each _encode()
452     vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
453                  (unsigned char*)1);
454
455     if (ctx->is_alpha)
456         vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
457                      (unsigned char*)1);
458
459     avctx->coded_frame = av_frame_alloc();
460     if (!avctx->coded_frame) {
461         av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");
462         vp8_free(avctx);
463         return AVERROR(ENOMEM);
464     }
465     return 0;
466 }
467
468 static inline void cx_pktcpy(struct FrameListData *dst,
469                              const struct vpx_codec_cx_pkt *src,
470                              const struct vpx_codec_cx_pkt *src_alpha,
471                              VP8Context *ctx)
472 {
473     dst->pts      = src->data.frame.pts;
474     dst->duration = src->data.frame.duration;
475     dst->flags    = src->data.frame.flags;
476     dst->sz       = src->data.frame.sz;
477     dst->buf      = src->data.frame.buf;
478     dst->have_sse = 0;
479     /* For alt-ref frame, don't store PSNR or increment frame_number */
480     if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
481         dst->frame_number = ++ctx->frame_number;
482         dst->have_sse = ctx->have_sse;
483         if (ctx->have_sse) {
484             /* associate last-seen SSE to the frame. */
485             /* Transfers ownership from ctx to dst. */
486             /* WARNING! This makes the assumption that PSNR_PKT comes
487                just before the frame it refers to! */
488             memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
489             ctx->have_sse = 0;
490         }
491     } else {
492         dst->frame_number = -1;   /* sanity marker */
493     }
494     if (src_alpha) {
495         dst->buf_alpha = src_alpha->data.frame.buf;
496         dst->sz_alpha = src_alpha->data.frame.sz;
497     }
498     else {
499         dst->buf_alpha = NULL;
500         dst->sz_alpha = 0;
501     }
502 }
503
504 /**
505  * Store coded frame information in format suitable for return from encode2().
506  *
507  * Write information from @a cx_frame to @a pkt
508  * @return packet data size on success
509  * @return a negative AVERROR on error
510  */
511 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
512                       AVPacket *pkt, AVFrame *coded_frame)
513 {
514     int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz);
515     uint8_t *side_data;
516     if (ret >= 0) {
517         memcpy(pkt->data, cx_frame->buf, pkt->size);
518         pkt->pts = pkt->dts    = cx_frame->pts;
519         coded_frame->pts       = cx_frame->pts;
520         coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
521
522         if (coded_frame->key_frame) {
523             coded_frame->pict_type = AV_PICTURE_TYPE_I;
524             pkt->flags            |= AV_PKT_FLAG_KEY;
525         } else
526             coded_frame->pict_type = AV_PICTURE_TYPE_P;
527
528         if (cx_frame->have_sse) {
529             int i;
530             /* Beware of the Y/U/V/all order! */
531             coded_frame->error[0] = cx_frame->sse[1];
532             coded_frame->error[1] = cx_frame->sse[2];
533             coded_frame->error[2] = cx_frame->sse[3];
534             coded_frame->error[3] = 0;    // alpha
535             for (i = 0; i < 4; ++i) {
536                 avctx->error[i] += coded_frame->error[i];
537             }
538             cx_frame->have_sse = 0;
539         }
540         if (cx_frame->sz_alpha > 0) {
541             side_data = av_packet_new_side_data(pkt,
542                                                 AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
543                                                 cx_frame->sz_alpha + 8);
544             if(side_data == NULL) {
545                 av_free_packet(pkt);
546                 av_free(pkt);
547                 return AVERROR(ENOMEM);
548             }
549             AV_WB64(side_data, 1);
550             memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
551         }
552     } else {
553         return ret;
554     }
555     return pkt->size;
556 }
557
558 /**
559  * Queue multiple output frames from the encoder, returning the front-most.
560  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
561  * the frame queue. Return the head frame if available.
562  * @return Stored frame size
563  * @return AVERROR(EINVAL) on output size error
564  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
565  */
566 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out,
567                         AVFrame *coded_frame)
568 {
569     VP8Context *ctx = avctx->priv_data;
570     const struct vpx_codec_cx_pkt *pkt;
571     const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
572     const void *iter = NULL;
573     const void *iter_alpha = NULL;
574     int size = 0;
575
576     if (ctx->coded_frame_list) {
577         struct FrameListData *cx_frame = ctx->coded_frame_list;
578         /* return the leading frame if we've already begun queueing */
579         size = storeframe(avctx, cx_frame, pkt_out, coded_frame);
580         if (size < 0)
581             return size;
582         ctx->coded_frame_list = cx_frame->next;
583         free_coded_frame(cx_frame);
584     }
585
586     /* consume all available output from the encoder before returning. buffers
587        are only good through the next vpx_codec call */
588     while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
589             (!ctx->is_alpha ||
590              (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
591         switch (pkt->kind) {
592         case VPX_CODEC_CX_FRAME_PKT:
593             if (!size) {
594                 struct FrameListData cx_frame;
595
596                 /* avoid storing the frame when the list is empty and we haven't yet
597                    provided a frame for output */
598                 av_assert0(!ctx->coded_frame_list);
599                 cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
600                 size = storeframe(avctx, &cx_frame, pkt_out, coded_frame);
601                 if (size < 0)
602                     return size;
603             } else {
604                 struct FrameListData *cx_frame =
605                     av_malloc(sizeof(struct FrameListData));
606
607                 if (!cx_frame) {
608                     av_log(avctx, AV_LOG_ERROR,
609                            "Frame queue element alloc failed\n");
610                     return AVERROR(ENOMEM);
611                 }
612                 cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
613                 cx_frame->buf = av_malloc(cx_frame->sz);
614
615                 if (!cx_frame->buf) {
616                     av_log(avctx, AV_LOG_ERROR,
617                            "Data buffer alloc (%zu bytes) failed\n",
618                            cx_frame->sz);
619                     av_free(cx_frame);
620                     return AVERROR(ENOMEM);
621                 }
622                 memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
623                 if (ctx->is_alpha) {
624                     cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
625                     if (!cx_frame->buf_alpha) {
626                         av_log(avctx, AV_LOG_ERROR,
627                                "Data buffer alloc (%zu bytes) failed\n",
628                                cx_frame->sz_alpha);
629                         av_free(cx_frame);
630                         return AVERROR(ENOMEM);
631                     }
632                     memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
633                 }
634                 coded_frame_add(&ctx->coded_frame_list, cx_frame);
635             }
636             break;
637         case VPX_CODEC_STATS_PKT: {
638             struct vpx_fixed_buf *stats = &ctx->twopass_stats;
639             stats->buf = av_realloc_f(stats->buf, 1,
640                                       stats->sz + pkt->data.twopass_stats.sz);
641             if (!stats->buf) {
642                 av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
643                 return AVERROR(ENOMEM);
644             }
645             memcpy((uint8_t*)stats->buf + stats->sz,
646                    pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
647             stats->sz += pkt->data.twopass_stats.sz;
648             break;
649         }
650         case VPX_CODEC_PSNR_PKT:
651             av_assert0(!ctx->have_sse);
652             ctx->sse[0] = pkt->data.psnr.sse[0];
653             ctx->sse[1] = pkt->data.psnr.sse[1];
654             ctx->sse[2] = pkt->data.psnr.sse[2];
655             ctx->sse[3] = pkt->data.psnr.sse[3];
656             ctx->have_sse = 1;
657             break;
658         case VPX_CODEC_CUSTOM_PKT:
659             //ignore unsupported/unrecognized packet types
660             break;
661         }
662     }
663
664     return size;
665 }
666
667 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
668                       const AVFrame *frame, int *got_packet)
669 {
670     VP8Context *ctx = avctx->priv_data;
671     struct vpx_image *rawimg = NULL;
672     struct vpx_image *rawimg_alpha = NULL;
673     int64_t timestamp = 0;
674     int res, coded_size;
675     vpx_enc_frame_flags_t flags = 0;
676
677     if (frame) {
678         rawimg                      = &ctx->rawimg;
679         rawimg->planes[VPX_PLANE_Y] = frame->data[0];
680         rawimg->planes[VPX_PLANE_U] = frame->data[1];
681         rawimg->planes[VPX_PLANE_V] = frame->data[2];
682         rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
683         rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
684         rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
685         if (ctx->is_alpha) {
686             uint8_t *u_plane, *v_plane;
687             rawimg_alpha = &ctx->rawimg_alpha;
688             rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
689             u_plane = av_malloc(frame->linesize[1] * frame->height);
690             memset(u_plane, 0x80, frame->linesize[1] * frame->height);
691             rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
692             v_plane = av_malloc(frame->linesize[2] * frame->height);
693             memset(v_plane, 0x80, frame->linesize[2] * frame->height);
694             rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
695             rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
696             rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
697             rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
698         }
699         timestamp                   = frame->pts;
700         if (frame->pict_type == AV_PICTURE_TYPE_I)
701             flags |= VPX_EFLAG_FORCE_KF;
702     }
703
704     res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
705                            avctx->ticks_per_frame, flags, ctx->deadline);
706     if (res != VPX_CODEC_OK) {
707         log_encoder_error(avctx, "Error encoding frame");
708         return AVERROR_INVALIDDATA;
709     }
710
711     if (ctx->is_alpha) {
712         res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
713                                avctx->ticks_per_frame, flags, ctx->deadline);
714         if (res != VPX_CODEC_OK) {
715             log_encoder_error(avctx, "Error encoding alpha frame");
716             return AVERROR_INVALIDDATA;
717         }
718     }
719
720     coded_size = queue_frames(avctx, pkt, avctx->coded_frame);
721
722     if (!frame && avctx->flags & CODEC_FLAG_PASS1) {
723         unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
724
725         avctx->stats_out = av_malloc(b64_size);
726         if (!avctx->stats_out) {
727             av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
728                    b64_size);
729             return AVERROR(ENOMEM);
730         }
731         av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
732                          ctx->twopass_stats.sz);
733     }
734
735     if (rawimg_alpha) {
736         av_free(rawimg_alpha->planes[VPX_PLANE_U]);
737         av_free(rawimg_alpha->planes[VPX_PLANE_V]);
738     }
739
740     *got_packet = !!coded_size;
741     return 0;
742 }
743
744 #define OFFSET(x) offsetof(VP8Context, x)
745 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
746
747 #ifndef VPX_ERROR_RESILIENT_DEFAULT
748 #define VPX_ERROR_RESILIENT_DEFAULT 1
749 #define VPX_ERROR_RESILIENT_PARTITIONS 2
750 #endif
751
752 #define COMMON_OPTIONS \
753     { "cpu-used",        "Quality/Speed ratio modifier",           OFFSET(cpu_used),        AV_OPT_TYPE_INT, {.i64 = INT_MIN}, INT_MIN, INT_MAX, VE}, \
754     { "auto-alt-ref",    "Enable use of alternate reference " \
755                          "frames (2-pass only)",                   OFFSET(auto_alt_ref),    AV_OPT_TYPE_INT, {.i64 = -1},      -1,      1,       VE}, \
756     { "lag-in-frames",   "Number of frames to look ahead for " \
757                          "alternate reference frame selection",    OFFSET(lag_in_frames),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
758     { "arnr-maxframes",  "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
759     { "arnr-strength",   "altref noise reduction filter strength", OFFSET(arnr_strength),   AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE}, \
760     { "arnr-type",       "altref noise reduction filter type",     OFFSET(arnr_type),       AV_OPT_TYPE_INT, {.i64 = -1},      -1,      INT_MAX, VE, "arnr_type"}, \
761     { "backward",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
762     { "forward",         NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
763     { "centered",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
764     { "deadline",        "Time to spend encoding, in microseconds.", OFFSET(deadline),      AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
765     { "best",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
766     { "good",            NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
767     { "realtime",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME},     0, 0, VE, "quality"}, \
768     { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
769     { "max-intra-rate",  "Maximum I-frame bitrate (pct) 0=unlimited",  OFFSET(max_intra_rate),  AV_OPT_TYPE_INT,  {.i64 = -1}, -1,      INT_MAX, VE}, \
770     { "default",         "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
771     { "partitions",      "The frame partitions are independently decodable " \
772                          "by the bool decoder, meaning that partitions can be decoded even " \
773                          "though earlier partitions have been lost. Note that intra predicition" \
774                          " is still done over the partition boundary.",       0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
775     { "crf",              "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 63, VE }, \
776
777 #define LEGACY_OPTIONS \
778     {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 3}, -16, 16, VE}, \
779     {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
780     {"vp8flags", "", offsetof(VP8Context, flags), FF_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
781     {"error_resilient", "enable error resilience", 0, FF_OPT_TYPE_CONST, {.dbl = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
782     {"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"}, \
783     {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
784     {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
785     {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
786     {"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}, \
787
788 #if CONFIG_LIBVPX_VP8_ENCODER
789 static const AVOption vp8_options[] = {
790     COMMON_OPTIONS
791     LEGACY_OPTIONS
792     { NULL }
793 };
794 #endif
795
796 #if CONFIG_LIBVPX_VP9_ENCODER
797 static const AVOption vp9_options[] = {
798     COMMON_OPTIONS
799     { "lossless",        "Lossless mode",                               OFFSET(lossless),        AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
800     { "tile-columns",    "Number of tile columns to use, log2",         OFFSET(tile_columns),    AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
801     { "tile-rows",       "Number of tile rows to use, log2",            OFFSET(tile_rows),       AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
802     { "frame-parallel",  "Enable frame parallel decodability features", OFFSET(frame_parallel),  AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
803     LEGACY_OPTIONS
804     { NULL }
805 };
806 #endif
807
808 #undef COMMON_OPTIONS
809 #undef LEGACY_OPTIONS
810
811 static const AVCodecDefault defaults[] = {
812     { "qmin",             "-1" },
813     { "qmax",             "-1" },
814     { "g",                "-1" },
815     { "keyint_min",       "-1" },
816     { NULL },
817 };
818
819 #if CONFIG_LIBVPX_VP8_ENCODER
820 static av_cold int vp8_init(AVCodecContext *avctx)
821 {
822     return vpx_init(avctx, &vpx_codec_vp8_cx_algo);
823 }
824
825 static const AVClass class_vp8 = {
826     .class_name = "libvpx-vp8 encoder",
827     .item_name  = av_default_item_name,
828     .option     = vp8_options,
829     .version    = LIBAVUTIL_VERSION_INT,
830 };
831
832 AVCodec ff_libvpx_vp8_encoder = {
833     .name           = "libvpx",
834     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP8"),
835     .type           = AVMEDIA_TYPE_VIDEO,
836     .id             = AV_CODEC_ID_VP8,
837     .priv_data_size = sizeof(VP8Context),
838     .init           = vp8_init,
839     .encode2        = vp8_encode,
840     .close          = vp8_free,
841     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
842     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
843     .priv_class     = &class_vp8,
844     .defaults       = defaults,
845 };
846 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
847
848 #if CONFIG_LIBVPX_VP9_ENCODER
849 static av_cold int vp9_init(AVCodecContext *avctx)
850 {
851     return vpx_init(avctx, &vpx_codec_vp9_cx_algo);
852 }
853
854 static const AVClass class_vp9 = {
855     .class_name = "libvpx-vp9 encoder",
856     .item_name  = av_default_item_name,
857     .option     = vp9_options,
858     .version    = LIBAVUTIL_VERSION_INT,
859 };
860
861 AVCodec ff_libvpx_vp9_encoder = {
862     .name           = "libvpx-vp9",
863     .long_name      = NULL_IF_CONFIG_SMALL("libvpx VP9"),
864     .type           = AVMEDIA_TYPE_VIDEO,
865     .id             = AV_CODEC_ID_VP9,
866     .priv_data_size = sizeof(VP8Context),
867     .init           = vp9_init,
868     .encode2        = vp8_encode,
869     .close          = vp8_free,
870     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS | CODEC_CAP_EXPERIMENTAL,
871     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
872     .priv_class     = &class_vp9,
873     .defaults       = defaults,
874 };
875 #endif /* CONFIG_LIBVPX_VP9_ENCODER */