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