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