]> git.sesse.net Git - ffmpeg/blob - libavfilter/buffersrc.c
Merge commit 'c1fcfdec75468009dc7de29a5d1c6adf3b2ef77d'
[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 "audio.h"
27 #include "avfilter.h"
28 #include "buffersrc.h"
29 #include "formats.h"
30 #include "internal.h"
31 #include "video.h"
32 #include "avcodec.h"
33
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/common.h"
36 #include "libavutil/fifo.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/samplefmt.h"
40
41 typedef struct {
42     const AVClass    *class;
43     AVFifoBuffer     *fifo;
44     AVRational        time_base;     ///< time_base to set in the output link
45     AVRational        frame_rate;    ///< frame_rate to set in the output link
46     unsigned          nb_failed_requests;
47     unsigned          warning_limit;
48
49     /* video only */
50     int               w, h;
51     enum AVPixelFormat  pix_fmt;
52     AVRational        pixel_aspect;
53     char              *sws_param;
54
55     /* audio only */
56     int sample_rate;
57     enum AVSampleFormat sample_fmt;
58     char               *sample_fmt_str;
59     uint64_t channel_layout;
60     char    *channel_layout_str;
61
62     int eof;
63 } BufferSourceContext;
64
65 #define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format)\
66     if (c->w != width || c->h != height || c->pix_fmt != format) {\
67         av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
68         return AVERROR(EINVAL);\
69     }
70
71 #define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, format)\
72     if (c->sample_fmt != format || c->sample_rate != srate ||\
73         c->channel_layout != ch_layout) {\
74         av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
75         return AVERROR(EINVAL);\
76     }
77
78 int av_buffersrc_add_frame(AVFilterContext *buffer_src,
79                            const AVFrame *frame, int flags)
80 {
81     AVFilterBufferRef *picref;
82     int ret;
83
84     if (!frame) /* NULL for EOF */
85         return av_buffersrc_add_ref(buffer_src, NULL, flags);
86
87     picref = avfilter_get_buffer_ref_from_frame(buffer_src->outputs[0]->type,
88                                                 frame, AV_PERM_WRITE);
89     if (!picref)
90         return AVERROR(ENOMEM);
91     ret = av_buffersrc_add_ref(buffer_src, picref, flags);
92     picref->buf->data[0] = NULL;
93     avfilter_unref_buffer(picref);
94     return ret;
95 }
96
97 int av_buffersrc_write_frame(AVFilterContext *buffer_filter, const AVFrame *frame)
98 {
99     return av_buffersrc_add_frame(buffer_filter, frame, 0);
100 }
101
102 int av_buffersrc_add_ref(AVFilterContext *s, AVFilterBufferRef *buf, int flags)
103 {
104     BufferSourceContext *c = s->priv;
105     AVFilterBufferRef *to_free = NULL;
106     int ret;
107
108     if (!buf) {
109         c->eof = 1;
110         return 0;
111     } else if (c->eof)
112         return AVERROR(EINVAL);
113
114     if (!av_fifo_space(c->fifo) &&
115         (ret = av_fifo_realloc2(c->fifo, av_fifo_size(c->fifo) +
116                                          sizeof(buf))) < 0)
117         return ret;
118
119     if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {
120         switch (s->outputs[0]->type) {
121         case AVMEDIA_TYPE_VIDEO:
122             CHECK_VIDEO_PARAM_CHANGE(s, c, buf->video->w, buf->video->h, buf->format);
123             break;
124         case AVMEDIA_TYPE_AUDIO:
125             CHECK_AUDIO_PARAM_CHANGE(s, c, buf->audio->sample_rate, buf->audio->channel_layout,
126                                      buf->format);
127             break;
128         default:
129             return AVERROR(EINVAL);
130         }
131     }
132     if (!(flags & AV_BUFFERSRC_FLAG_NO_COPY))
133         to_free = buf = ff_copy_buffer_ref(s->outputs[0], buf);
134     if(!buf)
135         return -1;
136
137     if ((ret = av_fifo_generic_write(c->fifo, &buf, sizeof(buf), NULL)) < 0) {
138         avfilter_unref_buffer(to_free);
139         return ret;
140     }
141     c->nb_failed_requests = 0;
142     if (c->warning_limit &&
143         av_fifo_size(c->fifo) / sizeof(buf) >= c->warning_limit) {
144         av_log(s, AV_LOG_WARNING,
145                "%d buffers queued in %s, something may be wrong.\n",
146                c->warning_limit,
147                (char *)av_x_if_null(s->name, s->filter->name));
148         c->warning_limit *= 10;
149     }
150
151     if ((flags & AV_BUFFERSRC_FLAG_PUSH))
152         if ((ret = s->output_pads[0].request_frame(s->outputs[0])) < 0)
153             return ret;
154
155     return 0;
156 }
157
158 #ifdef FF_API_BUFFERSRC_BUFFER
159 int av_buffersrc_buffer(AVFilterContext *s, AVFilterBufferRef *buf)
160 {
161     return av_buffersrc_add_ref(s, buf, AV_BUFFERSRC_FLAG_NO_COPY);
162 }
163 #endif
164
165 unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
166 {
167     return ((BufferSourceContext *)buffer_src->priv)->nb_failed_requests;
168 }
169
170 #define OFFSET(x) offsetof(BufferSourceContext, x)
171 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
172 static const AVOption buffer_options[] = {
173     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL,   { .dbl = 0 }, 0, INT_MAX, FLAGS },
174     { "frame_rate",     NULL, OFFSET(frame_rate),          AV_OPT_TYPE_RATIONAL,   { .dbl = 0 }, 0, INT_MAX, FLAGS },
175     { "video_size",     NULL, OFFSET(w),                   AV_OPT_TYPE_IMAGE_SIZE, .flags = FLAGS },
176     { "pix_fmt",        NULL, OFFSET(pix_fmt),             AV_OPT_TYPE_PIXEL_FMT,  .flags = FLAGS },
177     { "pixel_aspect",   NULL, OFFSET(pixel_aspect),        AV_OPT_TYPE_RATIONAL,   { .dbl = 0 }, 0, INT_MAX, FLAGS },
178     { "sws_param",      NULL, OFFSET(sws_param),           AV_OPT_TYPE_STRING,     .flags = FLAGS },
179     { NULL },
180 };
181 #undef FLAGS
182
183 AVFILTER_DEFINE_CLASS(buffer);
184
185 static av_cold int init_video(AVFilterContext *ctx, const char *args)
186 {
187     BufferSourceContext *c = ctx->priv;
188     char pix_fmt_str[128], sws_param[256] = "", *colon, *equal;
189     int ret, n = 0;
190
191     c->class = &buffer_class;
192
193     if (!args) {
194         av_log(ctx, AV_LOG_ERROR, "Arguments required\n");
195         return AVERROR(EINVAL);
196     }
197     colon = strchr(args, ':');
198     equal = strchr(args, '=');
199     if (equal && (!colon || equal < colon)) {
200         av_opt_set_defaults(c);
201         ret = av_set_options_string(c, args, "=", ":");
202         if (ret < 0)
203             goto fail;
204     } else {
205     if ((n = sscanf(args, "%d:%d:%127[^:]:%d:%d:%d:%d:%255c", &c->w, &c->h, pix_fmt_str,
206                     &c->time_base.num, &c->time_base.den,
207                     &c->pixel_aspect.num, &c->pixel_aspect.den, sws_param)) < 7) {
208         av_log(ctx, AV_LOG_ERROR, "Expected at least 7 arguments, but only %d found in '%s'\n", n, args);
209         ret = AVERROR(EINVAL);
210         goto fail;
211     }
212     av_log(ctx, AV_LOG_WARNING, "Flat options syntax is deprecated, use key=value pairs\n");
213
214     if ((ret = ff_parse_pixel_format(&c->pix_fmt, pix_fmt_str, ctx)) < 0)
215         goto fail;
216     c->sws_param = av_strdup(sws_param);
217     if (!c->sws_param) {
218         ret = AVERROR(ENOMEM);
219         goto fail;
220     }
221     }
222
223     if (!(c->fifo = av_fifo_alloc(sizeof(AVFilterBufferRef*)))) {
224         ret = AVERROR(ENOMEM);
225         goto fail;
226     }
227
228     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",
229            c->w, c->h, av_get_pix_fmt_name(c->pix_fmt),
230            c->time_base.num, c->time_base.den, c->frame_rate.num, c->frame_rate.den,
231            c->pixel_aspect.num, c->pixel_aspect.den, (char *)av_x_if_null(c->sws_param, ""));
232     c->warning_limit = 100;
233     return 0;
234
235 fail:
236     av_opt_free(c);
237     return ret;
238 }
239
240 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
241 static const AVOption abuffer_options[] = {
242     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, INT_MAX, FLAGS },
243     { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, FLAGS },
244     { "sample_fmt",     NULL, OFFSET(sample_fmt_str),      AV_OPT_TYPE_STRING, .flags = FLAGS },
245     { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING, .flags = FLAGS },
246     { NULL },
247 };
248
249 AVFILTER_DEFINE_CLASS(abuffer);
250
251 static av_cold int init_audio(AVFilterContext *ctx, const char *args)
252 {
253     BufferSourceContext *s = ctx->priv;
254     int ret = 0;
255
256     s->class = &abuffer_class;
257     av_opt_set_defaults(s);
258
259     if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
260         goto fail;
261
262     s->sample_fmt = av_get_sample_fmt(s->sample_fmt_str);
263     if (s->sample_fmt == AV_SAMPLE_FMT_NONE) {
264         av_log(ctx, AV_LOG_ERROR, "Invalid sample format '%s'\n",
265                s->sample_fmt_str);
266         ret = AVERROR(EINVAL);
267         goto fail;
268     }
269
270     s->channel_layout = av_get_channel_layout(s->channel_layout_str);
271     if (!s->channel_layout) {
272         av_log(ctx, AV_LOG_ERROR, "Invalid channel layout '%s'\n",
273                s->channel_layout_str);
274         ret = AVERROR(EINVAL);
275         goto fail;
276     }
277
278     if (!(s->fifo = av_fifo_alloc(sizeof(AVFilterBufferRef*)))) {
279         ret = AVERROR(ENOMEM);
280         goto fail;
281     }
282
283     if (!s->time_base.num)
284         s->time_base = (AVRational){1, s->sample_rate};
285
286     av_log(ctx, AV_LOG_VERBOSE,
287            "tb:%d/%d samplefmt:%s samplerate:%d chlayout:%s\n",
288            s->time_base.num, s->time_base.den, s->sample_fmt_str,
289            s->sample_rate, s->channel_layout_str);
290     s->warning_limit = 100;
291
292 fail:
293     av_opt_free(s);
294     return ret;
295 }
296
297 static av_cold void uninit(AVFilterContext *ctx)
298 {
299     BufferSourceContext *s = ctx->priv;
300     while (s->fifo && av_fifo_size(s->fifo)) {
301         AVFilterBufferRef *buf;
302         av_fifo_generic_read(s->fifo, &buf, sizeof(buf), NULL);
303         avfilter_unref_buffer(buf);
304     }
305     av_fifo_free(s->fifo);
306     s->fifo = NULL;
307     av_freep(&s->sws_param);
308 }
309
310 static int query_formats(AVFilterContext *ctx)
311 {
312     BufferSourceContext *c = ctx->priv;
313     AVFilterChannelLayouts *channel_layouts = NULL;
314     AVFilterFormats *formats = NULL;
315     AVFilterFormats *samplerates = NULL;
316
317     switch (ctx->outputs[0]->type) {
318     case AVMEDIA_TYPE_VIDEO:
319         ff_add_format(&formats, c->pix_fmt);
320         ff_set_common_formats(ctx, formats);
321         break;
322     case AVMEDIA_TYPE_AUDIO:
323         ff_add_format(&formats,           c->sample_fmt);
324         ff_set_common_formats(ctx, formats);
325
326         ff_add_format(&samplerates,       c->sample_rate);
327         ff_set_common_samplerates(ctx, samplerates);
328
329         ff_add_channel_layout(&channel_layouts, c->channel_layout);
330         ff_set_common_channel_layouts(ctx, channel_layouts);
331         break;
332     default:
333         return AVERROR(EINVAL);
334     }
335
336     return 0;
337 }
338
339 static int config_props(AVFilterLink *link)
340 {
341     BufferSourceContext *c = link->src->priv;
342
343     switch (link->type) {
344     case AVMEDIA_TYPE_VIDEO:
345         link->w = c->w;
346         link->h = c->h;
347         link->sample_aspect_ratio = c->pixel_aspect;
348         break;
349     case AVMEDIA_TYPE_AUDIO:
350         link->channel_layout = c->channel_layout;
351         link->sample_rate    = c->sample_rate;
352         break;
353     default:
354         return AVERROR(EINVAL);
355     }
356
357     link->time_base = c->time_base;
358     link->frame_rate = c->frame_rate;
359     return 0;
360 }
361
362 static int request_frame(AVFilterLink *link)
363 {
364     BufferSourceContext *c = link->src->priv;
365     AVFilterBufferRef *buf;
366     int ret = 0;
367
368     if (!av_fifo_size(c->fifo)) {
369         if (c->eof)
370             return AVERROR_EOF;
371         c->nb_failed_requests++;
372         return AVERROR(EAGAIN);
373     }
374     av_fifo_generic_read(c->fifo, &buf, sizeof(buf), NULL);
375
376     switch (link->type) {
377     case AVMEDIA_TYPE_VIDEO:
378         if ((ret = ff_start_frame(link, buf)) < 0 ||
379             (ret = ff_draw_slice(link, 0, link->h, 1)) < 0 ||
380             (ret = ff_end_frame(link)) < 0)
381             return ret;
382         break;
383     case AVMEDIA_TYPE_AUDIO:
384         ret = ff_filter_samples(link, buf);
385         break;
386     default:
387         avfilter_unref_bufferp(&buf);
388         return AVERROR(EINVAL);
389     }
390
391     return ret;
392 }
393
394 static int poll_frame(AVFilterLink *link)
395 {
396     BufferSourceContext *c = link->src->priv;
397     int size = av_fifo_size(c->fifo);
398     if (!size && c->eof)
399         return AVERROR_EOF;
400     return size/sizeof(AVFilterBufferRef*);
401 }
402
403 static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
404     {
405         .name          = "default",
406         .type          = AVMEDIA_TYPE_VIDEO,
407         .request_frame = request_frame,
408         .poll_frame    = poll_frame,
409         .config_props  = config_props,
410     },
411     { NULL }
412 };
413
414 AVFilter avfilter_vsrc_buffer = {
415     .name      = "buffer",
416     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
417     .priv_size = sizeof(BufferSourceContext),
418     .query_formats = query_formats,
419
420     .init      = init_video,
421     .uninit    = uninit,
422
423     .inputs    = NULL,
424     .outputs   = avfilter_vsrc_buffer_outputs,
425     .priv_class = &buffer_class,
426 };
427
428 static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
429     {
430         .name          = "default",
431         .type          = AVMEDIA_TYPE_AUDIO,
432         .request_frame = request_frame,
433         .poll_frame    = poll_frame,
434         .config_props  = config_props,
435     },
436     { NULL }
437 };
438
439 AVFilter avfilter_asrc_abuffer = {
440     .name          = "abuffer",
441     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
442     .priv_size     = sizeof(BufferSourceContext),
443     .query_formats = query_formats,
444
445     .init      = init_audio,
446     .uninit    = uninit,
447
448     .inputs    = NULL,
449     .outputs   = avfilter_asrc_abuffer_outputs,
450     .priv_class = &abuffer_class,
451 };