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