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