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