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