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