]> git.sesse.net Git - ffmpeg/blob - libavfilter/buffersink.c
Merge commit 'c2cb01d418dd18e1cf997c038d37378d773121be'
[ffmpeg] / libavfilter / buffersink.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
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  * buffer sink
24  */
25
26 #include "libavutil/audio_fifo.h"
27 #include "libavutil/avassert.h"
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/common.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32
33 #include "audio.h"
34 #include "avfilter.h"
35 #include "buffersink.h"
36 #include "internal.h"
37
38 typedef struct {
39     const AVClass *class;
40     AVFifoBuffer *fifo;                      ///< FIFO buffer of video frame references
41     unsigned warning_limit;
42
43     /* only used for video */
44     enum AVPixelFormat *pixel_fmts;           ///< list of accepted pixel formats, must be terminated with -1
45     int pixel_fmts_size;
46
47     /* only used for audio */
48     enum AVSampleFormat *sample_fmts;       ///< list of accepted sample formats, terminated by AV_SAMPLE_FMT_NONE
49     int sample_fmts_size;
50     int64_t *channel_layouts;               ///< list of accepted channel layouts, terminated by -1
51     int channel_layouts_size;
52     int *channel_counts;                    ///< list of accepted channel counts, terminated by -1
53     int channel_counts_size;
54     int all_channel_counts;
55     int *sample_rates;                      ///< list of accepted sample rates, terminated by -1
56     int sample_rates_size;
57
58     /* only used for compat API */
59     AVAudioFifo  *audio_fifo;    ///< FIFO for audio samples
60     int64_t next_pts;            ///< interpolating audio pts
61 } BufferSinkContext;
62
63 #define NB_ITEMS(list) (list ## _size / sizeof(*list))
64
65 static av_cold void uninit(AVFilterContext *ctx)
66 {
67     BufferSinkContext *sink = ctx->priv;
68     AVFrame *frame;
69
70     if (sink->audio_fifo)
71         av_audio_fifo_free(sink->audio_fifo);
72
73     if (sink->fifo) {
74         while (av_fifo_size(sink->fifo) >= sizeof(AVFilterBufferRef *)) {
75             av_fifo_generic_read(sink->fifo, &frame, sizeof(frame), NULL);
76             av_frame_free(&frame);
77         }
78         av_fifo_free(sink->fifo);
79         sink->fifo = NULL;
80     }
81 }
82
83 static int add_buffer_ref(AVFilterContext *ctx, AVFrame *ref)
84 {
85     BufferSinkContext *buf = ctx->priv;
86
87     if (av_fifo_space(buf->fifo) < sizeof(AVFilterBufferRef *)) {
88         /* realloc fifo size */
89         if (av_fifo_realloc2(buf->fifo, av_fifo_size(buf->fifo) * 2) < 0) {
90             av_log(ctx, AV_LOG_ERROR,
91                    "Cannot buffer more frames. Consume some available frames "
92                    "before adding new ones.\n");
93             return AVERROR(ENOMEM);
94         }
95     }
96
97     /* cache frame */
98     av_fifo_generic_write(buf->fifo, &ref, sizeof(AVFilterBufferRef *), NULL);
99     return 0;
100 }
101
102 static int filter_frame(AVFilterLink *link, AVFrame *frame)
103 {
104     AVFilterContext *ctx = link->dst;
105     BufferSinkContext *buf = link->dst->priv;
106     int ret;
107
108     if ((ret = add_buffer_ref(ctx, frame)) < 0)
109         return ret;
110     if (buf->warning_limit &&
111         av_fifo_size(buf->fifo) / sizeof(AVFilterBufferRef *) >= buf->warning_limit) {
112         av_log(ctx, AV_LOG_WARNING,
113                "%d buffers queued in %s, something may be wrong.\n",
114                buf->warning_limit,
115                (char *)av_x_if_null(ctx->name, ctx->filter->name));
116         buf->warning_limit *= 10;
117     }
118     return 0;
119 }
120
121 int av_buffersink_get_frame(AVFilterContext *ctx, AVFrame *frame)
122 {
123     return av_buffersink_get_frame_flags(ctx, frame, 0);
124 }
125
126 int attribute_align_arg av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
127 {
128     BufferSinkContext *buf = ctx->priv;
129     AVFilterLink *inlink = ctx->inputs[0];
130     int ret;
131     AVFrame *cur_frame;
132
133     /* no picref available, fetch it from the filterchain */
134     if (!av_fifo_size(buf->fifo)) {
135         if (flags & AV_BUFFERSINK_FLAG_NO_REQUEST)
136             return AVERROR(EAGAIN);
137         if ((ret = ff_request_frame(inlink)) < 0)
138             return ret;
139     }
140
141     if (!av_fifo_size(buf->fifo))
142         return AVERROR(EINVAL);
143
144     if (flags & AV_BUFFERSINK_FLAG_PEEK) {
145         cur_frame = *((AVFrame **)av_fifo_peek2(buf->fifo, 0));
146         if ((ret = av_frame_ref(frame, cur_frame)) < 0)
147             return ret;
148     } else {
149         av_fifo_generic_read(buf->fifo, &cur_frame, sizeof(cur_frame), NULL);
150         av_frame_move_ref(frame, cur_frame);
151         av_frame_free(&cur_frame);
152     }
153
154     return 0;
155 }
156
157 static int read_from_fifo(AVFilterContext *ctx, AVFrame *frame,
158                           int nb_samples)
159 {
160     BufferSinkContext *s = ctx->priv;
161     AVFilterLink   *link = ctx->inputs[0];
162     AVFrame *tmp;
163
164     if (!(tmp = ff_get_audio_buffer(link, nb_samples)))
165         return AVERROR(ENOMEM);
166     av_audio_fifo_read(s->audio_fifo, (void**)tmp->extended_data, nb_samples);
167
168     tmp->pts = s->next_pts;
169     s->next_pts += av_rescale_q(nb_samples, (AVRational){1, link->sample_rate},
170                                 link->time_base);
171
172     av_frame_move_ref(frame, tmp);
173     av_frame_free(&tmp);
174
175     return 0;
176
177 }
178
179 int attribute_align_arg av_buffersink_get_samples(AVFilterContext *ctx, AVFrame *frame, int nb_samples)
180 {
181     BufferSinkContext *s = ctx->priv;
182     AVFilterLink   *link = ctx->inputs[0];
183     AVFrame *cur_frame;
184     int ret = 0;
185
186     if (!s->audio_fifo) {
187         int nb_channels = link->channels;
188         if (!(s->audio_fifo = av_audio_fifo_alloc(link->format, nb_channels, nb_samples)))
189             return AVERROR(ENOMEM);
190     }
191
192     while (ret >= 0) {
193         if (av_audio_fifo_size(s->audio_fifo) >= nb_samples)
194             return read_from_fifo(ctx, frame, nb_samples);
195
196         if (!(cur_frame = av_frame_alloc()))
197             return AVERROR(ENOMEM);
198         ret = av_buffersink_get_frame_flags(ctx, cur_frame, 0);
199         if (ret == AVERROR_EOF && av_audio_fifo_size(s->audio_fifo)) {
200             av_frame_free(&cur_frame);
201             return read_from_fifo(ctx, frame, av_audio_fifo_size(s->audio_fifo));
202         } else if (ret < 0) {
203             av_frame_free(&cur_frame);
204             return ret;
205         }
206
207         if (cur_frame->pts != AV_NOPTS_VALUE) {
208             s->next_pts = cur_frame->pts -
209                           av_rescale_q(av_audio_fifo_size(s->audio_fifo),
210                                        (AVRational){ 1, link->sample_rate },
211                                        link->time_base);
212         }
213
214         ret = av_audio_fifo_write(s->audio_fifo, (void**)cur_frame->extended_data,
215                                   cur_frame->nb_samples);
216         av_frame_free(&cur_frame);
217     }
218
219     return ret;
220
221 }
222
223 AVBufferSinkParams *av_buffersink_params_alloc(void)
224 {
225     static const int pixel_fmts[] = { AV_PIX_FMT_NONE };
226     AVBufferSinkParams *params = av_malloc(sizeof(AVBufferSinkParams));
227     if (!params)
228         return NULL;
229
230     params->pixel_fmts = pixel_fmts;
231     return params;
232 }
233
234 AVABufferSinkParams *av_abuffersink_params_alloc(void)
235 {
236     AVABufferSinkParams *params = av_mallocz(sizeof(AVABufferSinkParams));
237
238     if (!params)
239         return NULL;
240     return params;
241 }
242
243 #define FIFO_INIT_SIZE 8
244
245 static av_cold int common_init(AVFilterContext *ctx)
246 {
247     BufferSinkContext *buf = ctx->priv;
248
249     buf->fifo = av_fifo_alloc(FIFO_INIT_SIZE*sizeof(AVFilterBufferRef *));
250     if (!buf->fifo) {
251         av_log(ctx, AV_LOG_ERROR, "Failed to allocate fifo\n");
252         return AVERROR(ENOMEM);
253     }
254     buf->warning_limit = 100;
255     return 0;
256 }
257
258 void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size)
259 {
260     AVFilterLink *inlink = ctx->inputs[0];
261
262     inlink->min_samples = inlink->max_samples =
263     inlink->partial_buf_size = frame_size;
264 }
265
266 #if FF_API_AVFILTERBUFFER
267 static void compat_free_buffer(AVFilterBuffer *buf)
268 {
269     AVFrame *frame = buf->priv;
270     av_frame_free(&frame);
271     av_free(buf);
272 }
273
274 static int attribute_align_arg compat_read(AVFilterContext *ctx, AVFilterBufferRef **pbuf, int nb_samples, int flags)
275 {
276     AVFilterBufferRef *buf;
277     AVFrame *frame;
278     int ret;
279
280     if (!pbuf)
281         return ff_poll_frame(ctx->inputs[0]);
282
283     frame = av_frame_alloc();
284     if (!frame)
285         return AVERROR(ENOMEM);
286
287     if (!nb_samples)
288         ret = av_buffersink_get_frame_flags(ctx, frame, flags);
289     else
290         ret = av_buffersink_get_samples(ctx, frame, nb_samples);
291
292     if (ret < 0)
293         goto fail;
294
295     AV_NOWARN_DEPRECATED(
296     if (ctx->inputs[0]->type == AVMEDIA_TYPE_VIDEO) {
297         buf = avfilter_get_video_buffer_ref_from_arrays(frame->data, frame->linesize,
298                                                         AV_PERM_READ,
299                                                         frame->width, frame->height,
300                                                         frame->format);
301     } else {
302         buf = avfilter_get_audio_buffer_ref_from_arrays(frame->extended_data,
303                                                         frame->linesize[0], AV_PERM_READ,
304                                                         frame->nb_samples,
305                                                         frame->format,
306                                                         frame->channel_layout);
307     }
308     if (!buf) {
309         ret = AVERROR(ENOMEM);
310         goto fail;
311     }
312
313     avfilter_copy_frame_props(buf, frame);
314     )
315
316     buf->buf->priv = frame;
317     buf->buf->free = compat_free_buffer;
318
319     *pbuf = buf;
320
321     return 0;
322 fail:
323     av_frame_free(&frame);
324     return ret;
325 }
326
327 int av_buffersink_read(AVFilterContext *ctx, AVFilterBufferRef **buf)
328 {
329     return compat_read(ctx, buf, 0, 0);
330 }
331
332 int av_buffersink_read_samples(AVFilterContext *ctx, AVFilterBufferRef **buf,
333                                int nb_samples)
334 {
335     return compat_read(ctx, buf, nb_samples, 0);
336 }
337
338 int av_buffersink_get_buffer_ref(AVFilterContext *ctx,
339                                   AVFilterBufferRef **bufref, int flags)
340 {
341     *bufref = NULL;
342
343     av_assert0(    !strcmp(ctx->filter->name, "buffersink")
344                 || !strcmp(ctx->filter->name, "abuffersink")
345                 || !strcmp(ctx->filter->name, "ffbuffersink")
346                 || !strcmp(ctx->filter->name, "ffabuffersink"));
347
348     return compat_read(ctx, bufref, 0, flags);
349 }
350 #endif
351
352 AVRational av_buffersink_get_frame_rate(AVFilterContext *ctx)
353 {
354     av_assert0(   !strcmp(ctx->filter->name, "buffersink")
355                || !strcmp(ctx->filter->name, "ffbuffersink"));
356
357     return ctx->inputs[0]->frame_rate;
358 }
359
360 int attribute_align_arg av_buffersink_poll_frame(AVFilterContext *ctx)
361 {
362     BufferSinkContext *buf = ctx->priv;
363     AVFilterLink *inlink = ctx->inputs[0];
364
365     av_assert0(   !strcmp(ctx->filter->name, "buffersink")
366                || !strcmp(ctx->filter->name, "abuffersink")
367                || !strcmp(ctx->filter->name, "ffbuffersink")
368                || !strcmp(ctx->filter->name, "ffabuffersink"));
369
370     return av_fifo_size(buf->fifo)/sizeof(AVFilterBufferRef *) + ff_poll_frame(inlink);
371 }
372
373 static av_cold int vsink_init(AVFilterContext *ctx, void *opaque)
374 {
375     BufferSinkContext *buf = ctx->priv;
376     AVBufferSinkParams *params = opaque;
377     int ret;
378
379     if (params) {
380         if ((ret = av_opt_set_int_list(buf, "pix_fmts", params->pixel_fmts, AV_PIX_FMT_NONE, 0)) < 0)
381             return ret;
382     }
383
384     return common_init(ctx);
385 }
386
387 #define CHECK_LIST_SIZE(field) \
388         if (buf->field ## _size % sizeof(*buf->field)) { \
389             av_log(ctx, AV_LOG_ERROR, "Invalid size for " #field ": %d, " \
390                    "should be multiple of %d\n", \
391                    buf->field ## _size, (int)sizeof(*buf->field)); \
392             return AVERROR(EINVAL); \
393         }
394 static int vsink_query_formats(AVFilterContext *ctx)
395 {
396     BufferSinkContext *buf = ctx->priv;
397     AVFilterFormats *formats = NULL;
398     unsigned i;
399     int ret;
400
401     CHECK_LIST_SIZE(pixel_fmts)
402     if (buf->pixel_fmts_size) {
403         for (i = 0; i < NB_ITEMS(buf->pixel_fmts); i++)
404             if ((ret = ff_add_format(&formats, buf->pixel_fmts[i])) < 0) {
405                 ff_formats_unref(&formats);
406                 return ret;
407             }
408         ff_set_common_formats(ctx, formats);
409     } else {
410         ff_default_query_formats(ctx);
411     }
412
413     return 0;
414 }
415
416 static av_cold int asink_init(AVFilterContext *ctx, void *opaque)
417 {
418     BufferSinkContext *buf = ctx->priv;
419     AVABufferSinkParams *params = opaque;
420     int ret;
421
422     if (params) {
423         if ((ret = av_opt_set_int_list(buf, "sample_fmts",     params->sample_fmts,  AV_SAMPLE_FMT_NONE, 0)) < 0 ||
424             (ret = av_opt_set_int_list(buf, "sample_rates",    params->sample_rates,    -1, 0)) < 0 ||
425             (ret = av_opt_set_int_list(buf, "channel_layouts", params->channel_layouts, -1, 0)) < 0 ||
426             (ret = av_opt_set_int_list(buf, "channel_counts",  params->channel_counts,  -1, 0)) < 0 ||
427             (ret = av_opt_set_int(buf, "all_channel_counts", params->all_channel_counts, 0)) < 0)
428             return ret;
429     }
430     return common_init(ctx);
431 }
432
433 static int asink_query_formats(AVFilterContext *ctx)
434 {
435     BufferSinkContext *buf = ctx->priv;
436     AVFilterFormats *formats = NULL;
437     AVFilterChannelLayouts *layouts = NULL;
438     unsigned i;
439     int ret;
440
441     CHECK_LIST_SIZE(sample_fmts)
442     CHECK_LIST_SIZE(sample_rates)
443     CHECK_LIST_SIZE(channel_layouts)
444     CHECK_LIST_SIZE(channel_counts)
445
446     if (buf->sample_fmts_size) {
447         for (i = 0; i < NB_ITEMS(buf->sample_fmts); i++)
448             if ((ret = ff_add_format(&formats, buf->sample_fmts[i])) < 0) {
449                 ff_formats_unref(&formats);
450                 return ret;
451             }
452         ff_set_common_formats(ctx, formats);
453     }
454
455     if (buf->channel_layouts_size || buf->channel_counts_size ||
456         buf->all_channel_counts) {
457         for (i = 0; i < NB_ITEMS(buf->channel_layouts); i++)
458             if ((ret = ff_add_channel_layout(&layouts, buf->channel_layouts[i])) < 0) {
459                 ff_channel_layouts_unref(&layouts);
460                 return ret;
461             }
462         for (i = 0; i < NB_ITEMS(buf->channel_counts); i++)
463             if ((ret = ff_add_channel_layout(&layouts, FF_COUNT2LAYOUT(buf->channel_counts[i]))) < 0) {
464                 ff_channel_layouts_unref(&layouts);
465                 return ret;
466             }
467         if (buf->all_channel_counts) {
468             if (layouts)
469                 av_log(ctx, AV_LOG_WARNING,
470                        "Conflicting all_channel_counts and list in options\n");
471             else if (!(layouts = ff_all_channel_counts()))
472                 return AVERROR(ENOMEM);
473         }
474         ff_set_common_channel_layouts(ctx, layouts);
475     }
476
477     if (buf->sample_rates_size) {
478         formats = NULL;
479         for (i = 0; i < NB_ITEMS(buf->sample_rates); i++)
480             if ((ret = ff_add_format(&formats, buf->sample_rates[i])) < 0) {
481                 ff_formats_unref(&formats);
482                 return ret;
483             }
484         ff_set_common_samplerates(ctx, formats);
485     }
486
487     return 0;
488 }
489
490 #define OFFSET(x) offsetof(BufferSinkContext, x)
491 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
492 static const AVOption buffersink_options[] = {
493     { "pix_fmts", "set the supported pixel formats", OFFSET(pixel_fmts), AV_OPT_TYPE_BINARY, .flags = FLAGS },
494     { NULL },
495 };
496 #undef FLAGS
497 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
498 static const AVOption abuffersink_options[] = {
499     { "sample_fmts",     "set the supported sample formats",  OFFSET(sample_fmts),     AV_OPT_TYPE_BINARY, .flags = FLAGS },
500     { "sample_rates",    "set the supported sample rates",    OFFSET(sample_rates),    AV_OPT_TYPE_BINARY, .flags = FLAGS },
501     { "channel_layouts", "set the supported channel layouts", OFFSET(channel_layouts), AV_OPT_TYPE_BINARY, .flags = FLAGS },
502     { "channel_counts",  "set the supported channel counts",  OFFSET(channel_counts),  AV_OPT_TYPE_BINARY, .flags = FLAGS },
503     { "all_channel_counts", "accept all channel counts", OFFSET(all_channel_counts), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
504     { NULL },
505 };
506 #undef FLAGS
507
508 AVFILTER_DEFINE_CLASS(buffersink);
509 AVFILTER_DEFINE_CLASS(abuffersink);
510
511 #if FF_API_AVFILTERBUFFER
512
513 #define ffbuffersink_options buffersink_options
514 #define ffabuffersink_options abuffersink_options
515 AVFILTER_DEFINE_CLASS(ffbuffersink);
516 AVFILTER_DEFINE_CLASS(ffabuffersink);
517
518 static const AVFilterPad ffbuffersink_inputs[] = {
519     {
520         .name      = "default",
521         .type      = AVMEDIA_TYPE_VIDEO,
522         .filter_frame = filter_frame,
523     },
524     { NULL },
525 };
526
527 AVFilter avfilter_vsink_ffbuffersink = {
528     .name      = "ffbuffersink",
529     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them available to the end of the filter graph."),
530     .priv_size = sizeof(BufferSinkContext),
531     .priv_class = &ffbuffersink_class,
532     .init_opaque = vsink_init,
533     .uninit    = uninit,
534
535     .query_formats = vsink_query_formats,
536     .inputs        = ffbuffersink_inputs,
537     .outputs       = NULL,
538 };
539
540 static const AVFilterPad ffabuffersink_inputs[] = {
541     {
542         .name           = "default",
543         .type           = AVMEDIA_TYPE_AUDIO,
544         .filter_frame   = filter_frame,
545     },
546     { NULL },
547 };
548
549 AVFilter avfilter_asink_ffabuffersink = {
550     .name      = "ffabuffersink",
551     .description = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them available to the end of the filter graph."),
552     .init_opaque = asink_init,
553     .uninit    = uninit,
554     .priv_size = sizeof(BufferSinkContext),
555     .priv_class = &ffabuffersink_class,
556     .query_formats = asink_query_formats,
557     .inputs        = ffabuffersink_inputs,
558     .outputs       = NULL,
559 };
560 #endif /* FF_API_AVFILTERBUFFER */
561
562 static const AVFilterPad avfilter_vsink_buffer_inputs[] = {
563     {
564         .name        = "default",
565         .type        = AVMEDIA_TYPE_VIDEO,
566         .filter_frame = filter_frame,
567     },
568     { NULL }
569 };
570
571 AVFilter avfilter_vsink_buffer = {
572     .name      = "buffersink",
573     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them available to the end of the filter graph."),
574     .priv_size = sizeof(BufferSinkContext),
575     .priv_class = &buffersink_class,
576     .init_opaque = vsink_init,
577     .uninit    = uninit,
578
579     .query_formats = vsink_query_formats,
580     .inputs    = avfilter_vsink_buffer_inputs,
581     .outputs   = NULL,
582 };
583
584 static const AVFilterPad avfilter_asink_abuffer_inputs[] = {
585     {
586         .name           = "default",
587         .type           = AVMEDIA_TYPE_AUDIO,
588         .filter_frame   = filter_frame,
589     },
590     { NULL }
591 };
592
593 AVFilter avfilter_asink_abuffer = {
594     .name      = "abuffersink",
595     .description = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them available to the end of the filter graph."),
596     .priv_class = &abuffersink_class,
597     .priv_size = sizeof(BufferSinkContext),
598     .init_opaque = asink_init,
599     .uninit    = uninit,
600
601     .query_formats = asink_query_formats,
602     .inputs    = avfilter_asink_abuffer_inputs,
603     .outputs   = NULL,
604 };