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