src_buffer: introduce av_buffersrc_add_ref().
[ffmpeg.git] / libavfilter / src_buffer.c
1 /*
2  * Copyright (c) 2008 Vitor Sessak
3  * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
4  * Copyright (c) 2011 Mina Nagy Zaki
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * memory buffer source filter
26  */
27
28 #include "avfilter.h"
29 #include "internal.h"
30 #include "avcodec.h"
31 #include "buffersrc.h"
32 #include "vsrc_buffer.h"
33 #include "asrc_abuffer.h"
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/fifo.h"
37 #include "libavutil/imgutils.h"
38
39 typedef struct {
40     AVFifoBuffer     *fifo;
41     AVRational        time_base;     ///< time_base to set in the output link
42     int eof;
43     unsigned          nb_failed_requests;
44
45     /* Video only */
46     AVFilterContext  *scale;
47     int               h, w;
48     enum PixelFormat  pix_fmt;
49     AVRational        sample_aspect_ratio;
50     char              sws_param[256];
51
52     /* Audio only */
53     // Audio format of incoming buffers
54     int sample_rate;
55     unsigned int sample_format;
56     int64_t channel_layout;
57     int packing_format;
58
59     // Normalization filters
60     AVFilterContext *aconvert;
61     AVFilterContext *aresample;
62 } BufferSourceContext;
63
64 #define FIFO_SIZE 8
65
66 #define CHECK_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_ERROR, "Changing frame properties on the fly is not supported.\n");\
69         return AVERROR(EINVAL);\
70     }
71
72 int av_buffersrc_add_ref(AVFilterContext *buffer_filter,
73                          AVFilterBufferRef *picref, int flags)
74 {
75     BufferSourceContext *c = buffer_filter->priv;
76     AVFilterLink *outlink = buffer_filter->outputs[0];
77     AVFilterBufferRef *buf;
78     int ret;
79
80     if (!picref) {
81         c->eof = 1;
82         return 0;
83     } else if (c->eof)
84         return AVERROR(EINVAL);
85
86     if (!av_fifo_space(c->fifo) &&
87         (ret = av_fifo_realloc2(c->fifo, av_fifo_size(c->fifo) +
88                                          sizeof(buf))) < 0)
89         return ret;
90
91     if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {
92         /* TODO reindent */
93     if (picref->video->w != c->w || picref->video->h != c->h || picref->format != c->pix_fmt) {
94         AVFilterContext *scale = buffer_filter->outputs[0]->dst;
95         AVFilterLink *link;
96         char scale_param[1024];
97
98         av_log(buffer_filter, AV_LOG_INFO,
99                "Buffer video input changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
100                c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name,
101                picref->video->w, picref->video->h, av_pix_fmt_descriptors[picref->format].name);
102
103         if (!scale || strcmp(scale->filter->name, "scale")) {
104             AVFilter *f = avfilter_get_by_name("scale");
105
106             av_log(buffer_filter, AV_LOG_INFO, "Inserting scaler filter\n");
107             if ((ret = avfilter_open(&scale, f, "Input equalizer")) < 0)
108                 return ret;
109
110             c->scale = scale;
111
112             snprintf(scale_param, sizeof(scale_param)-1, "%d:%d:%s", c->w, c->h, c->sws_param);
113             if ((ret = avfilter_init_filter(scale, scale_param, NULL)) < 0) {
114                 return ret;
115             }
116
117             if ((ret = avfilter_insert_filter(buffer_filter->outputs[0], scale, 0, 0)) < 0) {
118                 return ret;
119             }
120             scale->outputs[0]->time_base = scale->inputs[0]->time_base;
121
122             scale->outputs[0]->format= c->pix_fmt;
123         } else if (!strcmp(scale->filter->name, "scale")) {
124             snprintf(scale_param, sizeof(scale_param)-1, "%d:%d:%s",
125                      scale->outputs[0]->w, scale->outputs[0]->h, c->sws_param);
126             scale->filter->init(scale, scale_param, NULL);
127         }
128
129         c->pix_fmt = scale->inputs[0]->format = picref->format;
130         c->w       = scale->inputs[0]->w      = picref->video->w;
131         c->h       = scale->inputs[0]->h      = picref->video->h;
132
133         link = scale->outputs[0];
134         if ((ret =  link->srcpad->config_props(link)) < 0)
135             return ret;
136     }
137     }
138
139     if (flags & AV_BUFFERSRC_FLAG_NO_COPY) {
140         buf = picref;
141     } else {
142     buf = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,
143                                     picref->video->w, picref->video->h);
144     av_image_copy(buf->data, buf->linesize,
145                   (void*)picref->data, picref->linesize,
146                   picref->format, picref->video->w, picref->video->h);
147     avfilter_copy_buffer_ref_props(buf, picref);
148
149     }
150
151     if ((ret = av_fifo_generic_write(c->fifo, &buf, sizeof(buf), NULL)) < 0) {
152         if (buf != picref)
153             avfilter_unref_buffer(buf);
154         return ret;
155     }
156     c->nb_failed_requests = 0;
157
158     return 0;
159 }
160
161 int av_vsrc_buffer_add_video_buffer_ref(AVFilterContext *buffer_filter,
162                                         AVFilterBufferRef *picref, int flags)
163 {
164     return av_buffersrc_add_ref(buffer_filter, picref, 0);
165 }
166
167 int av_buffersrc_buffer(AVFilterContext *s, AVFilterBufferRef *buf)
168 {
169     return av_buffersrc_add_ref(s, buf, AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
170                                         AV_BUFFERSRC_FLAG_NO_COPY);
171 }
172
173 #if CONFIG_AVCODEC
174 #include "avcodec.h"
175
176 int av_vsrc_buffer_add_frame(AVFilterContext *buffer_src,
177                              const AVFrame *frame, int flags)
178 {
179     BufferSourceContext *c = buffer_src->priv;
180     AVFilterBufferRef *picref;
181     int ret;
182
183     if (!frame) {
184         c->eof = 1;
185         return 0;
186     } else if (c->eof)
187         return AVERROR(EINVAL);
188
189     picref = avfilter_get_video_buffer_ref_from_frame(frame, AV_PERM_WRITE);
190     if (!picref)
191         return AVERROR(ENOMEM);
192     ret = av_vsrc_buffer_add_video_buffer_ref(buffer_src, picref, flags);
193     picref->buf->data[0] = NULL;
194     avfilter_unref_buffer(picref);
195
196     return ret;
197 }
198 #endif
199
200 unsigned av_vsrc_buffer_get_nb_failed_requests(AVFilterContext *buffer_src)
201 {
202     return ((BufferSourceContext *)buffer_src->priv)->nb_failed_requests;
203 }
204
205 static av_cold int init_video(AVFilterContext *ctx, const char *args, void *opaque)
206 {
207     BufferSourceContext *c = ctx->priv;
208     char pix_fmt_str[128];
209     int ret, n = 0;
210     *c->sws_param = 0;
211
212     if (!args ||
213         (n = sscanf(args, "%d:%d:%127[^:]:%d:%d:%d:%d:%255c", &c->w, &c->h, pix_fmt_str,
214                     &c->time_base.num, &c->time_base.den,
215                     &c->sample_aspect_ratio.num, &c->sample_aspect_ratio.den, c->sws_param)) < 7) {
216         av_log(ctx, AV_LOG_ERROR, "Expected at least 7 arguments, but only %d found in '%s'\n", n, args);
217         return AVERROR(EINVAL);
218     }
219
220     if ((ret = ff_parse_pixel_format(&c->pix_fmt, pix_fmt_str, ctx)) < 0)
221         return ret;
222
223     if (!(c->fifo = av_fifo_alloc(sizeof(AVFilterBufferRef*))))
224         return AVERROR(ENOMEM);
225
226     av_log(ctx, AV_LOG_INFO, "w:%d h:%d pixfmt:%s tb:%d/%d sar:%d/%d sws_param:%s\n",
227            c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name,
228            c->time_base.num, c->time_base.den,
229            c->sample_aspect_ratio.num, c->sample_aspect_ratio.den, c->sws_param);
230     return 0;
231 }
232
233 static av_cold int init_audio(AVFilterContext *ctx, const char *args0, void *opaque)
234 {
235     BufferSourceContext *abuffer = ctx->priv;
236     char *arg = NULL, *ptr, chlayout_str[16];
237     char *args = av_strdup(args0);
238     int ret;
239
240     arg = av_strtok(args, ":", &ptr);
241
242 #define ADD_FORMAT(fmt_name)                                            \
243     if (!arg)                                                           \
244         goto arg_fail;                                                  \
245     if ((ret = ff_parse_##fmt_name(&abuffer->fmt_name, arg, ctx)) < 0) { \
246         av_freep(&args);                                                \
247         return ret;                                                     \
248     }                                                                   \
249     if (*args)                                                          \
250         arg = av_strtok(NULL, ":", &ptr)
251
252     ADD_FORMAT(sample_rate);
253     ADD_FORMAT(sample_format);
254     ADD_FORMAT(channel_layout);
255     ADD_FORMAT(packing_format);
256
257     abuffer->fifo = av_fifo_alloc(FIFO_SIZE*sizeof(AVFilterBufferRef*));
258     if (!abuffer->fifo) {
259         av_log(ctx, AV_LOG_ERROR, "Failed to allocate fifo, filter init failed.\n");
260         return AVERROR(ENOMEM);
261     }
262
263     av_get_channel_layout_string(chlayout_str, sizeof(chlayout_str),
264                                  -1, abuffer->channel_layout);
265     av_log(ctx, AV_LOG_INFO, "format:%s layout:%s rate:%d\n",
266            av_get_sample_fmt_name(abuffer->sample_format), chlayout_str,
267            abuffer->sample_rate);
268     av_freep(&args);
269
270     return 0;
271
272 arg_fail:
273     av_log(ctx, AV_LOG_ERROR, "Invalid arguments, must be of the form "
274                               "sample_rate:sample_fmt:channel_layout:packing\n");
275     av_freep(&args);
276     return AVERROR(EINVAL);
277 }
278
279 static av_cold void uninit(AVFilterContext *ctx)
280 {
281     BufferSourceContext *s = ctx->priv;
282     while (s->fifo && av_fifo_size(s->fifo)) {
283         AVFilterBufferRef *buf;
284         av_fifo_generic_read(s->fifo, &buf, sizeof(buf), NULL);
285         avfilter_unref_buffer(buf);
286     }
287     av_fifo_free(s->fifo);
288     s->fifo = NULL;
289     avfilter_free(s->scale);
290     s->scale = NULL;
291 }
292
293 static int query_formats_video(AVFilterContext *ctx)
294 {
295     BufferSourceContext *c = ctx->priv;
296     enum PixelFormat pix_fmts[] = { c->pix_fmt, PIX_FMT_NONE };
297
298     avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
299     return 0;
300 }
301
302 static int query_formats_audio(AVFilterContext *ctx)
303 {
304     BufferSourceContext *abuffer = ctx->priv;
305     AVFilterFormats *formats;
306
307     formats = NULL;
308     avfilter_add_format(&formats, abuffer->sample_format);
309     avfilter_set_common_sample_formats(ctx, formats);
310
311     formats = NULL;
312     avfilter_add_format(&formats, abuffer->channel_layout);
313     avfilter_set_common_channel_layouts(ctx, formats);
314
315     formats = NULL;
316     avfilter_add_format(&formats, abuffer->packing_format);
317     avfilter_set_common_packing_formats(ctx, formats);
318
319     return 0;
320 }
321
322 static int config_output_video(AVFilterLink *link)
323 {
324     BufferSourceContext *c = link->src->priv;
325
326     link->w = c->w;
327     link->h = c->h;
328     link->sample_aspect_ratio = c->sample_aspect_ratio;
329     link->time_base = c->time_base;
330
331     return 0;
332 }
333
334 static int config_output_audio(AVFilterLink *outlink)
335 {
336     BufferSourceContext *abuffer = outlink->src->priv;
337     outlink->sample_rate = abuffer->sample_rate;
338     return 0;
339 }
340
341 static int request_frame(AVFilterLink *link)
342 {
343     BufferSourceContext *c = link->src->priv;
344     AVFilterBufferRef *buf;
345
346     if (!av_fifo_size(c->fifo)) {
347         if (c->eof)
348             return AVERROR_EOF;
349         c->nb_failed_requests++;
350         return AVERROR(EAGAIN);
351     }
352     av_fifo_generic_read(c->fifo, &buf, sizeof(buf), NULL);
353
354     switch (link->type) {
355     case AVMEDIA_TYPE_VIDEO:
356         /* TODO reindent */
357     avfilter_start_frame(link, avfilter_ref_buffer(buf, ~0));
358     avfilter_draw_slice(link, 0, link->h, 1);
359     avfilter_end_frame(link);
360     avfilter_unref_buffer(buf);
361         break;
362     case AVMEDIA_TYPE_AUDIO:
363         avfilter_filter_samples(link, avfilter_ref_buffer(buf, ~0));
364         avfilter_unref_buffer(buf);
365         break;
366     default:
367         return AVERROR(ENOSYS);
368     }
369     return 0;
370 }
371
372 static int poll_frame(AVFilterLink *link)
373 {
374     BufferSourceContext *c = link->src->priv;
375     int size = av_fifo_size(c->fifo);
376     if (!size && c->eof)
377         return AVERROR_EOF;
378     return size/sizeof(AVFilterBufferRef*);
379 }
380
381 static void buf_free(AVFilterBuffer *ptr)
382 {
383     av_free(ptr);
384     return;
385 }
386
387 static void set_link_source(AVFilterContext *src, AVFilterLink *link)
388 {
389     link->src       = src;
390     link->srcpad    = &(src->output_pads[0]);
391     src->outputs[0] = link;
392 }
393
394 static int reconfigure_filter(BufferSourceContext *abuffer, AVFilterContext *filt_ctx)
395 {
396     int ret;
397     AVFilterLink * const inlink  = filt_ctx->inputs[0];
398     AVFilterLink * const outlink = filt_ctx->outputs[0];
399
400     inlink->format         = abuffer->sample_format;
401     inlink->channel_layout = abuffer->channel_layout;
402     inlink->planar         = abuffer->packing_format;
403     inlink->sample_rate    = abuffer->sample_rate;
404
405     filt_ctx->filter->uninit(filt_ctx);
406     memset(filt_ctx->priv, 0, filt_ctx->filter->priv_size);
407     if ((ret = filt_ctx->filter->init(filt_ctx, NULL , NULL)) < 0)
408         return ret;
409     if ((ret = inlink->srcpad->config_props(inlink)) < 0)
410         return ret;
411     return outlink->srcpad->config_props(outlink);
412 }
413
414 static int insert_filter(BufferSourceContext *abuffer,
415                          AVFilterLink *link, AVFilterContext **filt_ctx,
416                          const char *filt_name)
417 {
418     int ret;
419
420     if ((ret = avfilter_open(filt_ctx, avfilter_get_by_name(filt_name), NULL)) < 0)
421         return ret;
422
423     link->src->outputs[0] = NULL;
424     if ((ret = avfilter_link(link->src, 0, *filt_ctx, 0)) < 0) {
425         link->src->outputs[0] = link;
426         return ret;
427     }
428
429     set_link_source(*filt_ctx, link);
430
431     if ((ret = reconfigure_filter(abuffer, *filt_ctx)) < 0) {
432         avfilter_free(*filt_ctx);
433         return ret;
434     }
435
436     return 0;
437 }
438
439 static void remove_filter(AVFilterContext **filt_ctx)
440 {
441     AVFilterLink *outlink = (*filt_ctx)->outputs[0];
442     AVFilterContext *src  = (*filt_ctx)->inputs[0]->src;
443
444     (*filt_ctx)->outputs[0] = NULL;
445     avfilter_free(*filt_ctx);
446     *filt_ctx = NULL;
447
448     set_link_source(src, outlink);
449 }
450
451 static inline void log_input_change(void *ctx, AVFilterLink *link, AVFilterBufferRef *ref)
452 {
453     char old_layout_str[16], new_layout_str[16];
454     av_get_channel_layout_string(old_layout_str, sizeof(old_layout_str),
455                                  -1, link->channel_layout);
456     av_get_channel_layout_string(new_layout_str, sizeof(new_layout_str),
457                                  -1, ref->audio->channel_layout);
458     av_log(ctx, AV_LOG_INFO,
459            "Audio input format changed: "
460            "%s:%s:%d -> %s:%s:%d, normalizing\n",
461            av_get_sample_fmt_name(link->format),
462            old_layout_str, (int)link->sample_rate,
463            av_get_sample_fmt_name(ref->format),
464            new_layout_str, ref->audio->sample_rate);
465 }
466
467 int av_asrc_buffer_add_audio_buffer_ref(AVFilterContext *ctx,
468                                         AVFilterBufferRef *samplesref,
469                                         int av_unused flags)
470 {
471     BufferSourceContext *abuffer = ctx->priv;
472     AVFilterLink *link;
473     int ret, logged = 0;
474
475     if (av_fifo_space(abuffer->fifo) < sizeof(samplesref)) {
476         av_log(ctx, AV_LOG_ERROR,
477                "Buffering limit reached. Please consume some available frames "
478                "before adding new ones.\n");
479         return AVERROR(EINVAL);
480     }
481
482     // Normalize input
483
484     link = ctx->outputs[0];
485     if (samplesref->audio->sample_rate != link->sample_rate) {
486
487         log_input_change(ctx, link, samplesref);
488         logged = 1;
489
490         abuffer->sample_rate = samplesref->audio->sample_rate;
491
492         if (!abuffer->aresample) {
493             ret = insert_filter(abuffer, link, &abuffer->aresample, "aresample");
494             if (ret < 0) return ret;
495         } else {
496             link = abuffer->aresample->outputs[0];
497             if (samplesref->audio->sample_rate == link->sample_rate)
498                 remove_filter(&abuffer->aresample);
499             else
500                 if ((ret = reconfigure_filter(abuffer, abuffer->aresample)) < 0)
501                     return ret;
502         }
503     }
504
505     link = ctx->outputs[0];
506     if (samplesref->format                != link->format         ||
507         samplesref->audio->channel_layout != link->channel_layout ||
508         samplesref->audio->planar         != link->planar) {
509
510         if (!logged) log_input_change(ctx, link, samplesref);
511
512         abuffer->sample_format  = samplesref->format;
513         abuffer->channel_layout = samplesref->audio->channel_layout;
514         abuffer->packing_format = samplesref->audio->planar;
515
516         if (!abuffer->aconvert) {
517             ret = insert_filter(abuffer, link, &abuffer->aconvert, "aconvert");
518             if (ret < 0) return ret;
519         } else {
520             link = abuffer->aconvert->outputs[0];
521             if (samplesref->format                == link->format         &&
522                 samplesref->audio->channel_layout == link->channel_layout &&
523                 samplesref->audio->planar         == link->planar
524                )
525                 remove_filter(&abuffer->aconvert);
526             else
527                 if ((ret = reconfigure_filter(abuffer, abuffer->aconvert)) < 0)
528                     return ret;
529         }
530     }
531
532     if (sizeof(samplesref) != av_fifo_generic_write(abuffer->fifo, &samplesref,
533                                                     sizeof(samplesref), NULL)) {
534         av_log(ctx, AV_LOG_ERROR, "Error while writing to FIFO\n");
535         return AVERROR(EINVAL);
536     }
537
538     return 0;
539 }
540
541 int av_asrc_buffer_add_samples(AVFilterContext *ctx,
542                                uint8_t *data[8], int linesize[8],
543                                int nb_samples, int sample_rate,
544                                int sample_fmt, int64_t channel_layout, int planar,
545                                int64_t pts, int av_unused flags)
546 {
547     AVFilterBufferRef *samplesref;
548
549     samplesref = avfilter_get_audio_buffer_ref_from_arrays(
550                      data, linesize, AV_PERM_WRITE,
551                      nb_samples,
552                      sample_fmt, channel_layout, planar);
553     if (!samplesref)
554         return AVERROR(ENOMEM);
555
556     samplesref->buf->free  = buf_free;
557     samplesref->pts = pts;
558     samplesref->audio->sample_rate = sample_rate;
559
560     return av_asrc_buffer_add_audio_buffer_ref(ctx, samplesref, 0);
561 }
562
563 int av_asrc_buffer_add_buffer(AVFilterContext *ctx,
564                               uint8_t *buf, int buf_size, int sample_rate,
565                               int sample_fmt, int64_t channel_layout, int planar,
566                               int64_t pts, int av_unused flags)
567 {
568     uint8_t *data[8] = {0};
569     int linesize[8];
570     int nb_channels = av_get_channel_layout_nb_channels(channel_layout),
571         nb_samples  = buf_size / nb_channels / av_get_bytes_per_sample(sample_fmt);
572
573     av_samples_fill_arrays(data, linesize,
574                            buf, nb_channels, nb_samples,
575                            sample_fmt, 16);
576
577     return av_asrc_buffer_add_samples(ctx,
578                                       data, linesize, nb_samples,
579                                       sample_rate,
580                                       sample_fmt, channel_layout, planar,
581                                       pts, flags);
582 }
583
584 AVFilter avfilter_vsrc_buffer = {
585     .name      = "buffer",
586     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
587     .priv_size = sizeof(BufferSourceContext),
588     .query_formats = query_formats_video,
589
590     .init      = init_video,
591     .uninit    = uninit,
592
593     .inputs    = (const AVFilterPad[]) {{ .name = NULL }},
594     .outputs   = (const AVFilterPad[]) {{ .name      = "default",
595                                     .type            = AVMEDIA_TYPE_VIDEO,
596                                     .request_frame   = request_frame,
597                                     .poll_frame      = poll_frame,
598                                     .config_props    = config_output_video, },
599                                   { .name = NULL}},
600 };
601
602 #ifdef CONFIG_ABUFFER_FILTER
603
604 AVFilter avfilter_asrc_abuffer = {
605     .name        = "abuffer",
606     .description = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
607     .priv_size   = sizeof(BufferSourceContext),
608     .query_formats = query_formats_audio,
609
610     .init        = init_audio,
611     .uninit      = uninit,
612
613     .inputs      = (const AVFilterPad[]) {{ .name = NULL }},
614     .outputs     = (const AVFilterPad[]) {{ .name      = "default",
615                                       .type            = AVMEDIA_TYPE_AUDIO,
616                                       .request_frame   = request_frame,
617                                       .poll_frame      = poll_frame,
618                                       .config_props    = config_output_audio, },
619                                     { .name = NULL}},
620 };
621
622 #endif