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