]> git.sesse.net Git - ffmpeg/blob - libavfilter/buffersrc.c
Merge commit 'dad5fd59f3d6a8311365314cfcde0ebcd15c2b01'
[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 <float.h>
27
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/common.h"
30 #include "libavutil/fifo.h"
31 #include "libavutil/frame.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/samplefmt.h"
36 #include "libavutil/timestamp.h"
37 #include "audio.h"
38 #include "avfilter.h"
39 #include "buffersrc.h"
40 #include "formats.h"
41 #include "internal.h"
42 #include "video.h"
43
44 typedef struct BufferSourceContext {
45     const AVClass    *class;
46     AVFifoBuffer     *fifo;
47     AVRational        time_base;     ///< time_base to set in the output link
48     AVRational        frame_rate;    ///< frame_rate to set in the output link
49     unsigned          nb_failed_requests;
50     unsigned          warning_limit;
51
52     /* video only */
53     int               w, h;
54     enum AVPixelFormat  pix_fmt;
55     AVRational        pixel_aspect;
56     char              *sws_param;
57
58     AVBufferRef *hw_frames_ctx;
59
60     /* audio only */
61     int sample_rate;
62     enum AVSampleFormat sample_fmt;
63     int channels;
64     uint64_t channel_layout;
65     char    *channel_layout_str;
66
67     int got_format_from_params;
68     int eof;
69 } BufferSourceContext;
70
71 #define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format, pts)\
72     if (c->w != width || c->h != height || c->pix_fmt != format) {\
73         av_log(s, AV_LOG_INFO, "filter context - w: %d h: %d fmt: %d, incoming frame - w: %d h: %d fmt: %d pts_time: %s\n",\
74                c->w, c->h, c->pix_fmt, width, height, format, av_ts2timestr(pts, &s->outputs[0]->time_base));\
75         av_log(s, AV_LOG_WARNING, "Changing video frame properties on the fly is not supported by all filters.\n");\
76     }
77
78 #define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, ch_count, format, pts)\
79     if (c->sample_fmt != format || c->sample_rate != srate ||\
80         c->channel_layout != ch_layout || c->channels != ch_count) {\
81         av_log(s, AV_LOG_INFO, "filter context - fmt: %s r: %d layout: %"PRIX64" ch: %d, incoming frame - fmt: %s r: %d layout: %"PRIX64" ch: %d pts_time: %s\n",\
82                av_get_sample_fmt_name(c->sample_fmt), c->sample_rate, c->channel_layout, c->channels,\
83                av_get_sample_fmt_name(format), srate, ch_layout, ch_count, av_ts2timestr(pts, &s->outputs[0]->time_base));\
84         av_log(s, AV_LOG_ERROR, "Changing audio frame properties on the fly is not supported.\n");\
85         return AVERROR(EINVAL);\
86     }
87
88 AVBufferSrcParameters *av_buffersrc_parameters_alloc(void)
89 {
90     AVBufferSrcParameters *par = av_mallocz(sizeof(*par));
91     if (!par)
92         return NULL;
93
94     par->format = -1;
95
96     return par;
97 }
98
99 int av_buffersrc_parameters_set(AVFilterContext *ctx, AVBufferSrcParameters *param)
100 {
101     BufferSourceContext *s = ctx->priv;
102
103     if (param->time_base.num > 0 && param->time_base.den > 0)
104         s->time_base = param->time_base;
105
106     switch (ctx->filter->outputs[0].type) {
107     case AVMEDIA_TYPE_VIDEO:
108         if (param->format != AV_PIX_FMT_NONE) {
109             s->got_format_from_params = 1;
110             s->pix_fmt = param->format;
111         }
112         if (param->width > 0)
113             s->w = param->width;
114         if (param->height > 0)
115             s->h = param->height;
116         if (param->sample_aspect_ratio.num > 0 && param->sample_aspect_ratio.den > 0)
117             s->pixel_aspect = param->sample_aspect_ratio;
118         if (param->frame_rate.num > 0 && param->frame_rate.den > 0)
119             s->frame_rate = param->frame_rate;
120         if (param->hw_frames_ctx) {
121             av_buffer_unref(&s->hw_frames_ctx);
122             s->hw_frames_ctx = av_buffer_ref(param->hw_frames_ctx);
123             if (!s->hw_frames_ctx)
124                 return AVERROR(ENOMEM);
125         }
126         break;
127     case AVMEDIA_TYPE_AUDIO:
128         if (param->format != AV_SAMPLE_FMT_NONE) {
129             s->got_format_from_params = 1;
130             s->sample_fmt = param->format;
131         }
132         if (param->sample_rate > 0)
133             s->sample_rate = param->sample_rate;
134         if (param->channel_layout)
135             s->channel_layout = param->channel_layout;
136         break;
137     default:
138         return AVERROR_BUG;
139     }
140
141     return 0;
142 }
143
144 int attribute_align_arg av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame)
145 {
146     return av_buffersrc_add_frame_flags(ctx, (AVFrame *)frame,
147                                         AV_BUFFERSRC_FLAG_KEEP_REF);
148 }
149
150 int attribute_align_arg av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
151 {
152     return av_buffersrc_add_frame_flags(ctx, frame, 0);
153 }
154
155 static int av_buffersrc_add_frame_internal(AVFilterContext *ctx,
156                                            AVFrame *frame, int flags);
157
158 int attribute_align_arg av_buffersrc_add_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
159 {
160     AVFrame *copy = NULL;
161     int ret = 0;
162
163     if (frame && frame->channel_layout &&
164         av_get_channel_layout_nb_channels(frame->channel_layout) != frame->channels) {
165         av_log(ctx, AV_LOG_ERROR, "Layout indicates a different number of channels than actually present\n");
166         return AVERROR(EINVAL);
167     }
168
169     if (!(flags & AV_BUFFERSRC_FLAG_KEEP_REF) || !frame)
170         return av_buffersrc_add_frame_internal(ctx, frame, flags);
171
172     if (!(copy = av_frame_alloc()))
173         return AVERROR(ENOMEM);
174     ret = av_frame_ref(copy, frame);
175     if (ret >= 0)
176         ret = av_buffersrc_add_frame_internal(ctx, copy, flags);
177
178     av_frame_free(&copy);
179     return ret;
180 }
181
182 static int push_frame(AVFilterGraph *graph)
183 {
184     int ret;
185
186     while (1) {
187         ret = ff_filter_graph_run_once(graph);
188         if (ret == AVERROR(EAGAIN))
189             break;
190         if (ret < 0)
191             return ret;
192     }
193     return 0;
194 }
195
196 static int av_buffersrc_add_frame_internal(AVFilterContext *ctx,
197                                            AVFrame *frame, int flags)
198 {
199     BufferSourceContext *s = ctx->priv;
200     AVFrame *copy;
201     int refcounted, ret;
202
203     s->nb_failed_requests = 0;
204
205     if (!frame)
206         return av_buffersrc_close(ctx, AV_NOPTS_VALUE, flags);
207     if (s->eof)
208         return AVERROR(EINVAL);
209
210     refcounted = !!frame->buf[0];
211
212     if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {
213
214         switch (ctx->outputs[0]->type) {
215         case AVMEDIA_TYPE_VIDEO:
216             CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,
217                                      frame->format, frame->pts);
218             break;
219         case AVMEDIA_TYPE_AUDIO:
220             /* For layouts unknown on input but known on link after negotiation. */
221             if (!frame->channel_layout)
222                 frame->channel_layout = s->channel_layout;
223             CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,
224                                      frame->channels, frame->format, frame->pts);
225             break;
226         default:
227             return AVERROR(EINVAL);
228         }
229
230     }
231
232     if (!av_fifo_space(s->fifo) &&
233         (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +
234                                          sizeof(copy))) < 0)
235         return ret;
236
237     if (!(copy = av_frame_alloc()))
238         return AVERROR(ENOMEM);
239
240     if (refcounted) {
241         av_frame_move_ref(copy, frame);
242     } else {
243         ret = av_frame_ref(copy, frame);
244         if (ret < 0) {
245             av_frame_free(&copy);
246             return ret;
247         }
248     }
249
250     if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {
251         if (refcounted)
252             av_frame_move_ref(frame, copy);
253         av_frame_free(&copy);
254         return ret;
255     }
256
257     if ((ret = ctx->output_pads[0].request_frame(ctx->outputs[0])) < 0)
258         return ret;
259
260     if ((flags & AV_BUFFERSRC_FLAG_PUSH)) {
261         ret = push_frame(ctx->graph);
262         if (ret < 0)
263             return ret;
264     }
265
266     return 0;
267 }
268
269 int av_buffersrc_close(AVFilterContext *ctx, int64_t pts, unsigned flags)
270 {
271     BufferSourceContext *s = ctx->priv;
272
273     s->eof = 1;
274     ff_avfilter_link_set_in_status(ctx->outputs[0], AVERROR_EOF, pts);
275     return (flags & AV_BUFFERSRC_FLAG_PUSH) ? push_frame(ctx->graph) : 0;
276 }
277
278 static av_cold int init_video(AVFilterContext *ctx)
279 {
280     BufferSourceContext *c = ctx->priv;
281
282     if (!(c->pix_fmt != AV_PIX_FMT_NONE || c->got_format_from_params) || !c->w || !c->h ||
283         av_q2d(c->time_base) <= 0) {
284         av_log(ctx, AV_LOG_ERROR, "Invalid parameters provided.\n");
285         return AVERROR(EINVAL);
286     }
287
288     if (!(c->fifo = av_fifo_alloc(sizeof(AVFrame*))))
289         return AVERROR(ENOMEM);
290
291     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",
292            c->w, c->h, av_get_pix_fmt_name(c->pix_fmt),
293            c->time_base.num, c->time_base.den, c->frame_rate.num, c->frame_rate.den,
294            c->pixel_aspect.num, c->pixel_aspect.den, (char *)av_x_if_null(c->sws_param, ""));
295     c->warning_limit = 100;
296     return 0;
297 }
298
299 unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
300 {
301     return ((BufferSourceContext *)buffer_src->priv)->nb_failed_requests;
302 }
303
304 #define OFFSET(x) offsetof(BufferSourceContext, x)
305 #define A AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
306 #define V AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
307
308 static const AVOption buffer_options[] = {
309     { "width",         NULL,                     OFFSET(w),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
310     { "video_size",    NULL,                     OFFSET(w),                AV_OPT_TYPE_IMAGE_SIZE,                .flags = V },
311     { "height",        NULL,                     OFFSET(h),                AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, V },
312     { "pix_fmt",       NULL,                     OFFSET(pix_fmt),          AV_OPT_TYPE_PIXEL_FMT, { .i64 = AV_PIX_FMT_NONE }, .min = AV_PIX_FMT_NONE, .max = INT_MAX, .flags = V },
313     { "sar",           "sample aspect ratio",    OFFSET(pixel_aspect),     AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
314     { "pixel_aspect",  "sample aspect ratio",    OFFSET(pixel_aspect),     AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
315     { "time_base",     NULL,                     OFFSET(time_base),        AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
316     { "frame_rate",    NULL,                     OFFSET(frame_rate),       AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, DBL_MAX, V },
317     { "sws_param",     NULL,                     OFFSET(sws_param),        AV_OPT_TYPE_STRING,                    .flags = V },
318     { NULL },
319 };
320
321 AVFILTER_DEFINE_CLASS(buffer);
322
323 static const AVOption abuffer_options[] = {
324     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, INT_MAX, A },
325     { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
326     { "sample_fmt",     NULL, OFFSET(sample_fmt),          AV_OPT_TYPE_SAMPLE_FMT, { .i64 = AV_SAMPLE_FMT_NONE }, .min = AV_SAMPLE_FMT_NONE, .max = INT_MAX, .flags = A },
327     { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING,             .flags = A },
328     { "channels",       NULL, OFFSET(channels),            AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
329     { NULL },
330 };
331
332 AVFILTER_DEFINE_CLASS(abuffer);
333
334 static av_cold int init_audio(AVFilterContext *ctx)
335 {
336     BufferSourceContext *s = ctx->priv;
337     int ret = 0;
338
339     if (!(s->sample_fmt != AV_SAMPLE_FMT_NONE || s->got_format_from_params)) {
340         av_log(ctx, AV_LOG_ERROR, "Sample format was not set or was invalid\n");
341         return AVERROR(EINVAL);
342     }
343
344     if (s->channel_layout_str || s->channel_layout) {
345         int n;
346
347         if (!s->channel_layout) {
348             s->channel_layout = av_get_channel_layout(s->channel_layout_str);
349             if (!s->channel_layout) {
350                 av_log(ctx, AV_LOG_ERROR, "Invalid channel layout %s.\n",
351                        s->channel_layout_str);
352                 return AVERROR(EINVAL);
353             }
354         }
355         n = av_get_channel_layout_nb_channels(s->channel_layout);
356         if (s->channels) {
357             if (n != s->channels) {
358                 av_log(ctx, AV_LOG_ERROR,
359                        "Mismatching channel count %d and layout '%s' "
360                        "(%d channels)\n",
361                        s->channels, s->channel_layout_str, n);
362                 return AVERROR(EINVAL);
363             }
364         }
365         s->channels = n;
366     } else if (!s->channels) {
367         av_log(ctx, AV_LOG_ERROR, "Neither number of channels nor "
368                                   "channel layout specified\n");
369         return AVERROR(EINVAL);
370     }
371
372     if (!(s->fifo = av_fifo_alloc(sizeof(AVFrame*))))
373         return AVERROR(ENOMEM);
374
375     if (!s->time_base.num)
376         s->time_base = (AVRational){1, s->sample_rate};
377
378     av_log(ctx, AV_LOG_VERBOSE,
379            "tb:%d/%d samplefmt:%s samplerate:%d chlayout:%s\n",
380            s->time_base.num, s->time_base.den, av_get_sample_fmt_name(s->sample_fmt),
381            s->sample_rate, s->channel_layout_str);
382     s->warning_limit = 100;
383
384     return ret;
385 }
386
387 static av_cold void uninit(AVFilterContext *ctx)
388 {
389     BufferSourceContext *s = ctx->priv;
390     while (s->fifo && av_fifo_size(s->fifo)) {
391         AVFrame *frame;
392         av_fifo_generic_read(s->fifo, &frame, sizeof(frame), NULL);
393         av_frame_free(&frame);
394     }
395     av_buffer_unref(&s->hw_frames_ctx);
396     av_fifo_freep(&s->fifo);
397 }
398
399 static int query_formats(AVFilterContext *ctx)
400 {
401     BufferSourceContext *c = ctx->priv;
402     AVFilterChannelLayouts *channel_layouts = NULL;
403     AVFilterFormats *formats = NULL;
404     AVFilterFormats *samplerates = NULL;
405     int ret;
406
407     switch (ctx->outputs[0]->type) {
408     case AVMEDIA_TYPE_VIDEO:
409         if ((ret = ff_add_format         (&formats, c->pix_fmt)) < 0 ||
410             (ret = ff_set_common_formats (ctx     , formats   )) < 0)
411             return ret;
412         break;
413     case AVMEDIA_TYPE_AUDIO:
414         if ((ret = ff_add_format             (&formats    , c->sample_fmt )) < 0 ||
415             (ret = ff_set_common_formats     (ctx         , formats       )) < 0 ||
416             (ret = ff_add_format             (&samplerates, c->sample_rate)) < 0 ||
417             (ret = ff_set_common_samplerates (ctx         , samplerates   )) < 0)
418             return ret;
419
420         if ((ret = ff_add_channel_layout(&channel_layouts,
421                               c->channel_layout ? c->channel_layout :
422                               FF_COUNT2LAYOUT(c->channels))) < 0)
423             return ret;
424         if ((ret = ff_set_common_channel_layouts(ctx, channel_layouts)) < 0)
425             return ret;
426         break;
427     default:
428         return AVERROR(EINVAL);
429     }
430
431     return 0;
432 }
433
434 static int config_props(AVFilterLink *link)
435 {
436     BufferSourceContext *c = link->src->priv;
437
438     switch (link->type) {
439     case AVMEDIA_TYPE_VIDEO:
440         link->w = c->w;
441         link->h = c->h;
442         link->sample_aspect_ratio = c->pixel_aspect;
443
444         if (c->hw_frames_ctx) {
445             link->hw_frames_ctx = av_buffer_ref(c->hw_frames_ctx);
446             if (!link->hw_frames_ctx)
447                 return AVERROR(ENOMEM);
448         }
449         break;
450     case AVMEDIA_TYPE_AUDIO:
451         if (!c->channel_layout)
452             c->channel_layout = link->channel_layout;
453         break;
454     default:
455         return AVERROR(EINVAL);
456     }
457
458     link->time_base = c->time_base;
459     link->frame_rate = c->frame_rate;
460     return 0;
461 }
462
463 static int request_frame(AVFilterLink *link)
464 {
465     BufferSourceContext *c = link->src->priv;
466     AVFrame *frame;
467     int ret;
468
469     if (!av_fifo_size(c->fifo)) {
470         if (c->eof)
471             return AVERROR_EOF;
472         c->nb_failed_requests++;
473         return AVERROR(EAGAIN);
474     }
475     av_fifo_generic_read(c->fifo, &frame, sizeof(frame), NULL);
476
477     ret = ff_filter_frame(link, frame);
478
479     return ret;
480 }
481
482 static int poll_frame(AVFilterLink *link)
483 {
484     BufferSourceContext *c = link->src->priv;
485     int size = av_fifo_size(c->fifo);
486     if (!size && c->eof)
487         return AVERROR_EOF;
488     return size/sizeof(AVFrame*);
489 }
490
491 static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
492     {
493         .name          = "default",
494         .type          = AVMEDIA_TYPE_VIDEO,
495         .request_frame = request_frame,
496         .poll_frame    = poll_frame,
497         .config_props  = config_props,
498     },
499     { NULL }
500 };
501
502 AVFilter ff_vsrc_buffer = {
503     .name      = "buffer",
504     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
505     .priv_size = sizeof(BufferSourceContext),
506     .query_formats = query_formats,
507
508     .init      = init_video,
509     .uninit    = uninit,
510
511     .inputs    = NULL,
512     .outputs   = avfilter_vsrc_buffer_outputs,
513     .priv_class = &buffer_class,
514 };
515
516 static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
517     {
518         .name          = "default",
519         .type          = AVMEDIA_TYPE_AUDIO,
520         .request_frame = request_frame,
521         .poll_frame    = poll_frame,
522         .config_props  = config_props,
523     },
524     { NULL }
525 };
526
527 AVFilter ff_asrc_abuffer = {
528     .name          = "abuffer",
529     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
530     .priv_size     = sizeof(BufferSourceContext),
531     .query_formats = query_formats,
532
533     .init      = init_audio,
534     .uninit    = uninit,
535
536     .inputs    = NULL,
537     .outputs   = avfilter_asrc_abuffer_outputs,
538     .priv_class = &abuffer_class,
539 };