]> git.sesse.net Git - ffmpeg/blob - libavfilter/buffersrc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / buffersrc.c
1 /*
2  * Copyright (c) 2008 Vitor Sessak
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  * memory buffer source filter
24  */
25
26 #include <float.h>
27
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/common.h"
30 #include "libavutil/fifo.h"
31 #include "libavutil/frame.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/samplefmt.h"
36 #include "audio.h"
37 #include "avfilter.h"
38 #include "buffersrc.h"
39 #include "formats.h"
40 #include "internal.h"
41 #include "video.h"
42 #include "avcodec.h"
43
44 typedef struct {
45     const AVClass    *class;
46     AVFifoBuffer     *fifo;
47     AVRational        time_base;     ///< time_base to set in the output link
48     AVRational        frame_rate;    ///< frame_rate to set in the output link
49     unsigned          nb_failed_requests;
50     unsigned          warning_limit;
51
52     /* video only */
53     int               w, h;
54     enum AVPixelFormat  pix_fmt;
55     AVRational        pixel_aspect;
56     char              *sws_param;
57
58     /* audio only */
59     int sample_rate;
60     enum AVSampleFormat sample_fmt;
61     int channels;
62     uint64_t channel_layout;
63     char    *channel_layout_str;
64
65     int eof;
66 } BufferSourceContext;
67
68 #define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format)\
69     if (c->w != width || c->h != height || c->pix_fmt != format) {\
70         av_log(s, AV_LOG_INFO, "Changing frame properties on the fly is not supported by all filters.\n");\
71     }
72
73 #define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, ch_count, format)\
74     if (c->sample_fmt != format || c->sample_rate != srate ||\
75         c->channel_layout != ch_layout || c->channels != ch_count) {\
76         av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
77         return AVERROR(EINVAL);\
78     }
79
80 int attribute_align_arg av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame)
81 {
82     return av_buffersrc_add_frame_flags(ctx, (AVFrame *)frame,
83                                         AV_BUFFERSRC_FLAG_KEEP_REF);
84 }
85
86 int attribute_align_arg av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
87 {
88     return av_buffersrc_add_frame_flags(ctx, frame, 0);
89 }
90
91 static int av_buffersrc_add_frame_internal(AVFilterContext *ctx,
92                                            AVFrame *frame, int flags);
93
94 int attribute_align_arg av_buffersrc_add_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
95 {
96     AVFrame *copy = NULL;
97     int ret = 0;
98
99     if (frame && frame->channel_layout &&
100         av_get_channel_layout_nb_channels(frame->channel_layout) != av_frame_get_channels(frame)) {
101         av_log(0, AV_LOG_ERROR, "Layout indicates a different number of channels than actually present\n");
102         return AVERROR(EINVAL);
103     }
104
105     if (!(flags & AV_BUFFERSRC_FLAG_KEEP_REF) || !frame)
106         return av_buffersrc_add_frame_internal(ctx, frame, flags);
107
108     if (!(copy = av_frame_alloc()))
109         return AVERROR(ENOMEM);
110     ret = av_frame_ref(copy, frame);
111     if (ret >= 0)
112         ret = av_buffersrc_add_frame_internal(ctx, copy, flags);
113
114     av_frame_free(&copy);
115     return ret;
116 }
117
118 static int av_buffersrc_add_frame_internal(AVFilterContext *ctx,
119                                            AVFrame *frame, int flags)
120 {
121     BufferSourceContext *s = ctx->priv;
122     AVFrame *copy;
123     int ret;
124
125     s->nb_failed_requests = 0;
126
127     if (!frame) {
128         s->eof = 1;
129         return 0;
130     } else if (s->eof)
131         return AVERROR(EINVAL);
132
133     if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {
134
135     switch (ctx->outputs[0]->type) {
136     case AVMEDIA_TYPE_VIDEO:
137         CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,
138                                  frame->format);
139         break;
140     case AVMEDIA_TYPE_AUDIO:
141         /* For layouts unknown on input but known on link after negotiation. */
142         if (!frame->channel_layout)
143             frame->channel_layout = s->channel_layout;
144         CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,
145                                  av_frame_get_channels(frame), frame->format);
146         break;
147     default:
148         return AVERROR(EINVAL);
149     }
150
151     }
152
153     if (!av_fifo_space(s->fifo) &&
154         (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +
155                                          sizeof(copy))) < 0)
156         return ret;
157
158     if (!(copy = av_frame_alloc()))
159         return AVERROR(ENOMEM);
160     av_frame_move_ref(copy, frame);
161
162     if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {
163         av_frame_move_ref(frame, copy);
164         av_frame_free(&copy);
165         return ret;
166     }
167
168     if ((flags & AV_BUFFERSRC_FLAG_PUSH))
169         if ((ret = ctx->output_pads[0].request_frame(ctx->outputs[0])) < 0)
170             return ret;
171
172     return 0;
173 }
174
175 #if FF_API_AVFILTERBUFFER
176 FF_DISABLE_DEPRECATION_WARNINGS
177 static void compat_free_buffer(void *opaque, uint8_t *data)
178 {
179     AVFilterBufferRef *buf = opaque;
180     AV_NOWARN_DEPRECATED(
181     avfilter_unref_buffer(buf);
182     )
183 }
184
185 static void compat_unref_buffer(void *opaque, uint8_t *data)
186 {
187     AVBufferRef *buf = opaque;
188     AV_NOWARN_DEPRECATED(
189     av_buffer_unref(&buf);
190     )
191 }
192
193 int av_buffersrc_add_ref(AVFilterContext *ctx, AVFilterBufferRef *buf,
194                          int flags)
195 {
196     BufferSourceContext *s = ctx->priv;
197     AVFrame *frame = NULL;
198     AVBufferRef *dummy_buf = NULL;
199     int ret = 0, planes, i;
200
201     if (!buf) {
202         s->eof = 1;
203         return 0;
204     } else if (s->eof)
205         return AVERROR(EINVAL);
206
207     frame = av_frame_alloc();
208     if (!frame)
209         return AVERROR(ENOMEM);
210
211     dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, buf,
212                                  (buf->perms & AV_PERM_WRITE) ? 0 : AV_BUFFER_FLAG_READONLY);
213     if (!dummy_buf) {
214         ret = AVERROR(ENOMEM);
215         goto fail;
216     }
217
218     AV_NOWARN_DEPRECATED(
219     if ((ret = avfilter_copy_buf_props(frame, buf)) < 0)
220         goto fail;
221     )
222
223 #define WRAP_PLANE(ref_out, data, data_size)                            \
224 do {                                                                    \
225     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
226     if (!dummy_ref) {                                                   \
227         ret = AVERROR(ENOMEM);                                          \
228         goto fail;                                                      \
229     }                                                                   \
230     ref_out = av_buffer_create(data, data_size, compat_unref_buffer,    \
231                                dummy_ref, (buf->perms & AV_PERM_WRITE) ? 0 : AV_BUFFER_FLAG_READONLY);                           \
232     if (!ref_out) {                                                     \
233         av_frame_unref(frame);                                          \
234         ret = AVERROR(ENOMEM);                                          \
235         goto fail;                                                      \
236     }                                                                   \
237 } while (0)
238
239     if (ctx->outputs[0]->type  == AVMEDIA_TYPE_VIDEO) {
240         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
241
242         planes = av_pix_fmt_count_planes(frame->format);
243         if (!desc || planes <= 0) {
244             ret = AVERROR(EINVAL);
245             goto fail;
246         }
247
248         for (i = 0; i < planes; i++) {
249             int v_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
250             int plane_size = (frame->height >> v_shift) * frame->linesize[i];
251
252             WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
253         }
254     } else {
255         int planar = av_sample_fmt_is_planar(frame->format);
256         int channels = av_get_channel_layout_nb_channels(frame->channel_layout);
257
258         planes = planar ? channels : 1;
259
260         if (planes > FF_ARRAY_ELEMS(frame->buf)) {
261             frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
262             frame->extended_buf = av_mallocz(sizeof(*frame->extended_buf) *
263                                              frame->nb_extended_buf);
264             if (!frame->extended_buf) {
265                 ret = AVERROR(ENOMEM);
266                 goto fail;
267             }
268         }
269
270         for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
271             WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
272
273         for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)
274             WRAP_PLANE(frame->extended_buf[i],
275                        frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
276                        frame->linesize[0]);
277     }
278
279     ret = av_buffersrc_add_frame_flags(ctx, frame, flags);
280
281 fail:
282     av_buffer_unref(&dummy_buf);
283     av_frame_free(&frame);
284
285     return ret;
286 }
287 FF_ENABLE_DEPRECATION_WARNINGS
288
289 int av_buffersrc_buffer(AVFilterContext *ctx, AVFilterBufferRef *buf)
290 {
291     return av_buffersrc_add_ref(ctx, buf, 0);
292 }
293 #endif
294
295 static av_cold int init_video(AVFilterContext *ctx)
296 {
297     BufferSourceContext *c = ctx->priv;
298
299     if (c->pix_fmt == AV_PIX_FMT_NONE || !c->w || !c->h || av_q2d(c->time_base) <= 0) {
300         av_log(ctx, AV_LOG_ERROR, "Invalid parameters provided.\n");
301         return AVERROR(EINVAL);
302     }
303
304     if (!(c->fifo = av_fifo_alloc(sizeof(AVFrame*))))
305         return AVERROR(ENOMEM);
306
307     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d pixfmt:%s tb:%d/%d fr:%d/%d sar:%d/%d sws_param:%s\n",
308            c->w, c->h, av_get_pix_fmt_name(c->pix_fmt),
309            c->time_base.num, c->time_base.den, c->frame_rate.num, c->frame_rate.den,
310            c->pixel_aspect.num, c->pixel_aspect.den, (char *)av_x_if_null(c->sws_param, ""));
311     c->warning_limit = 100;
312     return 0;
313 }
314
315 unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
316 {
317     return ((BufferSourceContext *)buffer_src->priv)->nb_failed_requests;
318 }
319
320 #define OFFSET(x) offsetof(BufferSourceContext, x)
321 #define A AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
322 #define V AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
323
324 static const AVOption buffer_options[] = {
325     { "width",         NULL,                     OFFSET(w),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
326     { "video_size",    NULL,                     OFFSET(w),                AV_OPT_TYPE_IMAGE_SIZE,                .flags = V },
327     { "height",        NULL,                     OFFSET(h),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
328     { "pix_fmt",       NULL,                     OFFSET(pix_fmt),          AV_OPT_TYPE_PIXEL_FMT, { .i64 = AV_PIX_FMT_NONE }, .min = AV_PIX_FMT_NONE, .max = INT_MAX, .flags = V },
329 #if FF_API_OLD_FILTER_OPTS
330     /* those 4 are for compatibility with the old option passing system where each filter
331      * did its own parsing */
332     { "time_base_num", "deprecated, do not use", OFFSET(time_base.num),    AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
333     { "time_base_den", "deprecated, do not use", OFFSET(time_base.den),    AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
334     { "sar_num",       "deprecated, do not use", OFFSET(pixel_aspect.num), AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
335     { "sar_den",       "deprecated, do not use", OFFSET(pixel_aspect.den), AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
336 #endif
337     { "sar",           "sample aspect ratio",    OFFSET(pixel_aspect),     AV_OPT_TYPE_RATIONAL, { .dbl = 1 }, 0, DBL_MAX, V },
338     { "pixel_aspect",  "sample aspect ratio",    OFFSET(pixel_aspect),     AV_OPT_TYPE_RATIONAL, { .dbl = 1 }, 0, DBL_MAX, V },
339     { "time_base",     NULL,                     OFFSET(time_base),        AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
340     { "frame_rate",    NULL,                     OFFSET(frame_rate),       AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
341     { "sws_param",     NULL,                     OFFSET(sws_param),        AV_OPT_TYPE_STRING,                    .flags = V },
342     { NULL },
343 };
344
345 AVFILTER_DEFINE_CLASS(buffer);
346
347 static const AVOption abuffer_options[] = {
348     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, INT_MAX, A },
349     { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
350     { "sample_fmt",     NULL, OFFSET(sample_fmt),          AV_OPT_TYPE_SAMPLE_FMT, { .i64 = AV_SAMPLE_FMT_NONE }, .min = AV_SAMPLE_FMT_NONE, .max = INT_MAX, .flags = A },
351     { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING,             .flags = A },
352     { "channels",       NULL, OFFSET(channels),            AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
353     { NULL },
354 };
355
356 AVFILTER_DEFINE_CLASS(abuffer);
357
358 static av_cold int init_audio(AVFilterContext *ctx)
359 {
360     BufferSourceContext *s = ctx->priv;
361     int ret = 0;
362
363     if (s->sample_fmt == AV_SAMPLE_FMT_NONE) {
364         av_log(ctx, AV_LOG_ERROR, "Sample format was not set or was invalid\n");
365         return AVERROR(EINVAL);
366     }
367
368     if (s->channel_layout_str) {
369         int n;
370         /* TODO reindent */
371     s->channel_layout = av_get_channel_layout(s->channel_layout_str);
372     if (!s->channel_layout) {
373         av_log(ctx, AV_LOG_ERROR, "Invalid channel layout %s.\n",
374                s->channel_layout_str);
375         return AVERROR(EINVAL);
376     }
377         n = av_get_channel_layout_nb_channels(s->channel_layout);
378         if (s->channels) {
379             if (n != s->channels) {
380                 av_log(ctx, AV_LOG_ERROR,
381                        "Mismatching channel count %d and layout '%s' "
382                        "(%d channels)\n",
383                        s->channels, s->channel_layout_str, n);
384                 return AVERROR(EINVAL);
385             }
386         }
387         s->channels = n;
388     } else if (!s->channels) {
389         av_log(ctx, AV_LOG_ERROR, "Neither number of channels nor "
390                                   "channel layout specified\n");
391         return AVERROR(EINVAL);
392     }
393
394     if (!(s->fifo = av_fifo_alloc(sizeof(AVFrame*))))
395         return AVERROR(ENOMEM);
396
397     if (!s->time_base.num)
398         s->time_base = (AVRational){1, s->sample_rate};
399
400     av_log(ctx, AV_LOG_VERBOSE,
401            "tb:%d/%d samplefmt:%s samplerate:%d chlayout:%s\n",
402            s->time_base.num, s->time_base.den, av_get_sample_fmt_name(s->sample_fmt),
403            s->sample_rate, s->channel_layout_str);
404     s->warning_limit = 100;
405
406     return ret;
407 }
408
409 static av_cold void uninit(AVFilterContext *ctx)
410 {
411     BufferSourceContext *s = ctx->priv;
412     while (s->fifo && av_fifo_size(s->fifo)) {
413         AVFrame *frame;
414         av_fifo_generic_read(s->fifo, &frame, sizeof(frame), NULL);
415         av_frame_free(&frame);
416     }
417     av_fifo_free(s->fifo);
418     s->fifo = NULL;
419 }
420
421 static int query_formats(AVFilterContext *ctx)
422 {
423     BufferSourceContext *c = ctx->priv;
424     AVFilterChannelLayouts *channel_layouts = NULL;
425     AVFilterFormats *formats = NULL;
426     AVFilterFormats *samplerates = NULL;
427
428     switch (ctx->outputs[0]->type) {
429     case AVMEDIA_TYPE_VIDEO:
430         ff_add_format(&formats, c->pix_fmt);
431         ff_set_common_formats(ctx, formats);
432         break;
433     case AVMEDIA_TYPE_AUDIO:
434         ff_add_format(&formats,           c->sample_fmt);
435         ff_set_common_formats(ctx, formats);
436
437         ff_add_format(&samplerates,       c->sample_rate);
438         ff_set_common_samplerates(ctx, samplerates);
439
440         ff_add_channel_layout(&channel_layouts,
441                               c->channel_layout ? c->channel_layout :
442                               FF_COUNT2LAYOUT(c->channels));
443         ff_set_common_channel_layouts(ctx, channel_layouts);
444         break;
445     default:
446         return AVERROR(EINVAL);
447     }
448
449     return 0;
450 }
451
452 static int config_props(AVFilterLink *link)
453 {
454     BufferSourceContext *c = link->src->priv;
455
456     switch (link->type) {
457     case AVMEDIA_TYPE_VIDEO:
458         link->w = c->w;
459         link->h = c->h;
460         link->sample_aspect_ratio = c->pixel_aspect;
461         break;
462     case AVMEDIA_TYPE_AUDIO:
463         if (!c->channel_layout)
464             c->channel_layout = link->channel_layout;
465         break;
466     default:
467         return AVERROR(EINVAL);
468     }
469
470     link->time_base = c->time_base;
471     link->frame_rate = c->frame_rate;
472     return 0;
473 }
474
475 static int request_frame(AVFilterLink *link)
476 {
477     BufferSourceContext *c = link->src->priv;
478     AVFrame *frame;
479
480     if (!av_fifo_size(c->fifo)) {
481         if (c->eof)
482             return AVERROR_EOF;
483         c->nb_failed_requests++;
484         return AVERROR(EAGAIN);
485     }
486     av_fifo_generic_read(c->fifo, &frame, sizeof(frame), NULL);
487
488     return ff_filter_frame(link, frame);
489 }
490
491 static int poll_frame(AVFilterLink *link)
492 {
493     BufferSourceContext *c = link->src->priv;
494     int size = av_fifo_size(c->fifo);
495     if (!size && c->eof)
496         return AVERROR_EOF;
497     return size/sizeof(AVFrame*);
498 }
499
500 static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
501     {
502         .name          = "default",
503         .type          = AVMEDIA_TYPE_VIDEO,
504         .request_frame = request_frame,
505         .poll_frame    = poll_frame,
506         .config_props  = config_props,
507     },
508     { NULL }
509 };
510
511 AVFilter ff_vsrc_buffer = {
512     .name      = "buffer",
513     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
514     .priv_size = sizeof(BufferSourceContext),
515     .query_formats = query_formats,
516
517     .init      = init_video,
518     .uninit    = uninit,
519
520     .inputs    = NULL,
521     .outputs   = avfilter_vsrc_buffer_outputs,
522     .priv_class = &buffer_class,
523 };
524
525 static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
526     {
527         .name          = "default",
528         .type          = AVMEDIA_TYPE_AUDIO,
529         .request_frame = request_frame,
530         .poll_frame    = poll_frame,
531         .config_props  = config_props,
532     },
533     { NULL }
534 };
535
536 AVFilter ff_asrc_abuffer = {
537     .name          = "abuffer",
538     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
539     .priv_size     = sizeof(BufferSourceContext),
540     .query_formats = query_formats,
541
542     .init      = init_audio,
543     .uninit    = uninit,
544
545     .inputs    = NULL,
546     .outputs   = avfilter_asrc_abuffer_outputs,
547     .priv_class = &abuffer_class,
548 };