]> 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     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 #if FF_API_VSRC_BUFFER_ADD_FRAME
116 static int av_vsrc_buffer_add_frame_alt(AVFilterContext *buffer_filter, AVFrame *frame,
117                              int64_t pts, AVRational pixel_aspect)
118 {
119     int64_t orig_pts = frame->pts;
120     AVRational orig_sar = frame->sample_aspect_ratio;
121     int ret;
122
123     frame->pts = pts;
124     frame->sample_aspect_ratio = pixel_aspect;
125     if ((ret = av_buffersrc_write_frame(buffer_filter, frame)) < 0)
126         return ret;
127     frame->pts = orig_pts;
128     frame->sample_aspect_ratio = orig_sar;
129
130     return 0;
131 }
132 #endif
133
134 int av_buffersrc_add_frame(AVFilterContext *buffer_src,
135                            const AVFrame *frame, int flags)
136 {
137     AVFilterBufferRef *picref;
138     int ret;
139
140     if (!frame) /* NULL for EOF */
141         return av_buffersrc_add_ref(buffer_src, NULL, flags);
142
143     switch (buffer_src->outputs[0]->type) {
144     case AVMEDIA_TYPE_VIDEO:
145         picref = avfilter_get_video_buffer_ref_from_frame(frame, AV_PERM_WRITE);
146         break;
147     case AVMEDIA_TYPE_AUDIO:
148         picref = avfilter_get_audio_buffer_ref_from_frame(frame, AV_PERM_WRITE);
149         break;
150     default:
151         return AVERROR(ENOSYS);
152     }
153     if (!picref)
154         return AVERROR(ENOMEM);
155     ret = av_buffersrc_add_ref(buffer_src, picref, flags);
156     picref->buf->data[0] = NULL;
157     avfilter_unref_buffer(picref);
158     return ret;
159 }
160
161 int av_buffersrc_write_frame(AVFilterContext *buffer_filter, AVFrame *frame)
162 {
163     return av_buffersrc_add_frame(buffer_filter, frame, 0);
164 }
165
166 int av_buffersrc_add_ref(AVFilterContext *s, AVFilterBufferRef *buf, int flags)
167 {
168     BufferSourceContext *c = s->priv;
169     AVFilterBufferRef *to_free = NULL;
170     int ret;
171
172     if (!buf) {
173         c->eof = 1;
174         return 0;
175     } else if (c->eof)
176         return AVERROR(EINVAL);
177
178     if (!av_fifo_space(c->fifo) &&
179         (ret = av_fifo_realloc2(c->fifo, av_fifo_size(c->fifo) +
180                                          sizeof(buf))) < 0)
181         return ret;
182
183     if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {
184         switch (s->outputs[0]->type) {
185         case AVMEDIA_TYPE_VIDEO:
186             CHECK_VIDEO_PARAM_CHANGE(s, c, buf->video->w, buf->video->h, buf->format);
187             break;
188         case AVMEDIA_TYPE_AUDIO:
189             CHECK_AUDIO_PARAM_CHANGE(s, c, buf->audio->sample_rate, buf->audio->channel_layout,
190                                      buf->format);
191             break;
192         default:
193             return AVERROR(EINVAL);
194         }
195     }
196     if (!(flags & AV_BUFFERSRC_FLAG_NO_COPY))
197         to_free = buf = copy_buffer_ref(s, buf);
198     if(!buf)
199         return -1;
200
201     if ((ret = av_fifo_generic_write(c->fifo, &buf, sizeof(buf), NULL)) < 0) {
202         avfilter_unref_buffer(to_free);
203         return ret;
204     }
205     c->nb_failed_requests = 0;
206
207     return 0;
208 }
209
210 int av_buffersrc_buffer(AVFilterContext *s, AVFilterBufferRef *buf)
211 {
212     return av_buffersrc_add_ref(s, buf, AV_BUFFERSRC_FLAG_NO_COPY);
213 }
214
215 unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
216 {
217     return ((BufferSourceContext *)buffer_src->priv)->nb_failed_requests;
218 }
219
220 #define OFFSET(x) offsetof(BufferSourceContext, x)
221 #define V AV_OPT_FLAG_VIDEO_PARAM
222 static const AVOption video_options[] = {
223     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL,   { 0 }, 0, INT_MAX, V },
224     { "frame_rate",     NULL, OFFSET(frame_rate),          AV_OPT_TYPE_RATIONAL,   { 0 }, 0, INT_MAX, V },
225     { "video_size",     NULL, OFFSET(w),                   AV_OPT_TYPE_IMAGE_SIZE,           .flags = V },
226     { "pix_fmt",        NULL, OFFSET(pix_fmt),             AV_OPT_TYPE_PIXEL_FMT,            .flags = V },
227     { "pixel_aspect",   NULL, OFFSET(pixel_aspect),        AV_OPT_TYPE_RATIONAL,   { 0 }, 0, INT_MAX, V },
228     { "sws_param",      NULL, OFFSET(sws_param),           AV_OPT_TYPE_STRING,               .flags = V },
229     { NULL },
230 };
231 #undef V
232
233 static const AVClass vbuffer_class = {
234     .class_name = "vbuffer source",
235     .item_name  = av_default_item_name,
236     .option     = video_options,
237     .version    = LIBAVUTIL_VERSION_INT,
238     .category   = AV_CLASS_CATEGORY_FILTER,
239 };
240
241 static av_cold int init_video(AVFilterContext *ctx, const char *args, void *opaque)
242 {
243     BufferSourceContext *c = ctx->priv;
244     char pix_fmt_str[128], sws_param[256] = "", *colon, *equal;
245     int ret, n = 0;
246
247     c->class = &vbuffer_class;
248
249     if (!args) {
250         av_log(ctx, AV_LOG_ERROR, "Arguments required\n");
251         return AVERROR(EINVAL);
252     }
253     colon = strchr(args, ':');
254     equal = strchr(args, '=');
255     if (equal && (!colon || equal < colon)) {
256         av_opt_set_defaults(c);
257         ret = av_set_options_string(c, args, "=", ":");
258         if (ret < 0) {
259             av_log(ctx, AV_LOG_ERROR, "Error parsing options string: %s.\n", args);
260             goto fail;
261         }
262     } else {
263     if ((n = sscanf(args, "%d:%d:%127[^:]:%d:%d:%d:%d:%255c", &c->w, &c->h, pix_fmt_str,
264                     &c->time_base.num, &c->time_base.den,
265                     &c->pixel_aspect.num, &c->pixel_aspect.den, sws_param)) < 7) {
266         av_log(ctx, AV_LOG_ERROR, "Expected at least 7 arguments, but only %d found in '%s'\n", n, args);
267         ret = AVERROR(EINVAL);
268         goto fail;
269     }
270     av_log(ctx, AV_LOG_WARNING, "Flat options syntax is deprecated, use key=value pairs.\n");
271
272     if ((ret = ff_parse_pixel_format(&c->pix_fmt, pix_fmt_str, ctx)) < 0)
273         goto fail;
274     c->sws_param = av_strdup(sws_param);
275     if (!c->sws_param) {
276         ret = AVERROR(ENOMEM);
277         goto fail;
278     }
279     }
280
281     if (!(c->fifo = av_fifo_alloc(sizeof(AVFilterBufferRef*)))) {
282         ret = AVERROR(ENOMEM);
283         goto fail;
284     }
285
286     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",
287            c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name,
288            c->time_base.num, c->time_base.den, c->frame_rate.num, c->frame_rate.den,
289            c->pixel_aspect.num, c->pixel_aspect.den, (char *)av_x_if_null(c->sws_param, ""));
290     return 0;
291
292 fail:
293     av_opt_free(c);
294     return ret;
295 }
296
297 #define A AV_OPT_FLAG_AUDIO_PARAM
298 static const AVOption audio_options[] = {
299     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { 0 }, 0, INT_MAX, A },
300     { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { 0 }, 0, INT_MAX, A },
301     { "sample_fmt",     NULL, OFFSET(sample_fmt_str),      AV_OPT_TYPE_STRING,             .flags = A },
302     { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING,             .flags = A },
303     { NULL },
304 };
305
306 static const AVClass abuffer_class = {
307     .class_name = "abuffer source",
308     .item_name  = av_default_item_name,
309     .option     = audio_options,
310     .version    = LIBAVUTIL_VERSION_INT,
311     .category   = AV_CLASS_CATEGORY_FILTER,
312 };
313
314 static av_cold int init_audio(AVFilterContext *ctx, const char *args, void *opaque)
315 {
316     BufferSourceContext *s = ctx->priv;
317     int ret = 0;
318
319     s->class = &abuffer_class;
320     av_opt_set_defaults(s);
321
322     if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
323         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: %s.\n", args);
324         goto fail;
325     }
326
327     s->sample_fmt = av_get_sample_fmt(s->sample_fmt_str);
328     if (s->sample_fmt == AV_SAMPLE_FMT_NONE) {
329         av_log(ctx, AV_LOG_ERROR, "Invalid sample format %s.\n",
330                s->sample_fmt_str);
331         ret = AVERROR(EINVAL);
332         goto fail;
333     }
334
335     s->channel_layout = av_get_channel_layout(s->channel_layout_str);
336     if (!s->channel_layout) {
337         av_log(ctx, AV_LOG_ERROR, "Invalid channel layout %s.\n",
338                s->channel_layout_str);
339         ret = AVERROR(EINVAL);
340         goto fail;
341     }
342
343     if (!(s->fifo = av_fifo_alloc(sizeof(AVFilterBufferRef*)))) {
344         ret = AVERROR(ENOMEM);
345         goto fail;
346     }
347
348     if (!s->time_base.num)
349         s->time_base = (AVRational){1, s->sample_rate};
350
351     av_log(ctx, AV_LOG_VERBOSE, "tb:%d/%d samplefmt:%s samplerate: %d "
352            "ch layout:%s\n", s->time_base.num, s->time_base.den, s->sample_fmt_str,
353            s->sample_rate, s->channel_layout_str);
354
355 fail:
356     av_opt_free(s);
357     return ret;
358 }
359
360 static av_cold void uninit(AVFilterContext *ctx)
361 {
362     BufferSourceContext *s = ctx->priv;
363     while (s->fifo && av_fifo_size(s->fifo)) {
364         AVFilterBufferRef *buf;
365         av_fifo_generic_read(s->fifo, &buf, sizeof(buf), NULL);
366         avfilter_unref_buffer(buf);
367     }
368     av_fifo_free(s->fifo);
369     s->fifo = NULL;
370     av_freep(&s->sws_param);
371 }
372
373 static int query_formats(AVFilterContext *ctx)
374 {
375     BufferSourceContext *c = ctx->priv;
376     AVFilterChannelLayouts *channel_layouts = NULL;
377     AVFilterFormats *formats = NULL;
378     AVFilterFormats *samplerates = NULL;
379
380     switch (ctx->outputs[0]->type) {
381     case AVMEDIA_TYPE_VIDEO:
382         ff_add_format(&formats, c->pix_fmt);
383         ff_set_common_formats(ctx, formats);
384         break;
385     case AVMEDIA_TYPE_AUDIO:
386         ff_add_format(&formats,           c->sample_fmt);
387         ff_set_common_formats(ctx, formats);
388
389         ff_add_format(&samplerates,       c->sample_rate);
390         ff_set_common_samplerates(ctx, samplerates);
391
392         ff_add_channel_layout(&channel_layouts, c->channel_layout);
393         ff_set_common_channel_layouts(ctx, channel_layouts);
394         break;
395     default:
396         return AVERROR(EINVAL);
397     }
398
399     return 0;
400 }
401
402 static int config_props(AVFilterLink *link)
403 {
404     BufferSourceContext *c = link->src->priv;
405
406     switch (link->type) {
407     case AVMEDIA_TYPE_VIDEO:
408         link->w = c->w;
409         link->h = c->h;
410         link->sample_aspect_ratio = c->pixel_aspect;
411         break;
412     case AVMEDIA_TYPE_AUDIO:
413         link->channel_layout = c->channel_layout;
414         link->sample_rate    = c->sample_rate;
415         break;
416     default:
417         return AVERROR(EINVAL);
418     }
419
420     link->time_base = c->time_base;
421     link->frame_rate = c->frame_rate;
422     return 0;
423 }
424
425 static int request_frame(AVFilterLink *link)
426 {
427     BufferSourceContext *c = link->src->priv;
428     AVFilterBufferRef *buf;
429
430     if (!av_fifo_size(c->fifo)) {
431         if (c->eof)
432             return AVERROR_EOF;
433         c->nb_failed_requests++;
434         return AVERROR(EAGAIN);
435     }
436     av_fifo_generic_read(c->fifo, &buf, sizeof(buf), NULL);
437
438     switch (link->type) {
439     case AVMEDIA_TYPE_VIDEO:
440         ff_start_frame(link, avfilter_ref_buffer(buf, ~0));
441         ff_draw_slice(link, 0, link->h, 1);
442         ff_end_frame(link);
443         break;
444     case AVMEDIA_TYPE_AUDIO:
445         ff_filter_samples(link, avfilter_ref_buffer(buf, ~0));
446         break;
447     default:
448         return AVERROR(EINVAL);
449     }
450
451     avfilter_unref_buffer(buf);
452
453     return 0;
454 }
455
456 static int poll_frame(AVFilterLink *link)
457 {
458     BufferSourceContext *c = link->src->priv;
459     int size = av_fifo_size(c->fifo);
460     if (!size && c->eof)
461         return AVERROR_EOF;
462     return size/sizeof(AVFilterBufferRef*);
463 }
464
465 AVFilter avfilter_vsrc_buffer = {
466     .name      = "buffer",
467     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
468     .priv_size = sizeof(BufferSourceContext),
469     .query_formats = query_formats,
470
471     .init      = init_video,
472     .uninit    = uninit,
473
474     .inputs    = (AVFilterPad[]) {{ .name = NULL }},
475     .outputs   = (AVFilterPad[]) {{ .name            = "default",
476                                     .type            = AVMEDIA_TYPE_VIDEO,
477                                     .request_frame   = request_frame,
478                                     .poll_frame      = poll_frame,
479                                     .config_props    = config_props, },
480                                   { .name = NULL}},
481 };
482
483 AVFilter avfilter_asrc_abuffer = {
484     .name          = "abuffer",
485     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
486     .priv_size     = sizeof(BufferSourceContext),
487     .query_formats = query_formats,
488
489     .init      = init_audio,
490     .uninit    = uninit,
491
492     .inputs    = (AVFilterPad[]) {{ .name = NULL }},
493     .outputs   = (AVFilterPad[]) {{ .name            = "default",
494                                     .type            = AVMEDIA_TYPE_AUDIO,
495                                     .request_frame   = request_frame,
496                                     .poll_frame      = poll_frame,
497                                     .config_props    = config_props, },
498                                   { .name = NULL}},
499 };