]> git.sesse.net Git - ffmpeg/blob - libavfilter/buffersrc.c
lavfi: switch to AVFrame.
[ffmpeg] / libavfilter / buffersrc.c
1 /*
2  * Copyright (c) 2008 Vitor Sessak
3  *
4  * This file is part of Libav.
5  *
6  * Libav 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  * Libav 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 Libav; 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
40 typedef struct {
41     const AVClass    *class;
42     AVFifoBuffer     *fifo;
43     AVRational        time_base;     ///< time_base to set in the output link
44
45     /* video only */
46     int               h, w;
47     enum AVPixelFormat  pix_fmt;
48     AVRational        pixel_aspect;
49
50     /* audio only */
51     int sample_rate;
52     enum AVSampleFormat sample_fmt;
53     char               *sample_fmt_str;
54     uint64_t channel_layout;
55     char    *channel_layout_str;
56
57     int eof;
58 } BufferSourceContext;
59
60 #define CHECK_VIDEO_PARAM_CHANGE(s, c, width, height, format)\
61     if (c->w != width || c->h != height || c->pix_fmt != format) {\
62         av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
63         return AVERROR(EINVAL);\
64     }
65
66 #define CHECK_AUDIO_PARAM_CHANGE(s, c, srate, ch_layout, format)\
67     if (c->sample_fmt != format || c->sample_rate != srate ||\
68         c->channel_layout != ch_layout) {\
69         av_log(s, AV_LOG_ERROR, "Changing frame properties on the fly is not supported.\n");\
70         return AVERROR(EINVAL);\
71     }
72
73 int av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame)
74 {
75     AVFrame *copy;
76     int ret = 0;
77
78     if (!(copy = av_frame_alloc()))
79         return AVERROR(ENOMEM);
80     ret = av_frame_ref(copy, frame);
81     if (ret >= 0)
82         ret = av_buffersrc_add_frame(ctx, copy);
83
84     av_frame_free(&copy);
85     return ret;
86 }
87
88 int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
89 {
90     BufferSourceContext *s = ctx->priv;
91     AVFrame *copy;
92     int ret;
93
94     if (!frame) {
95         s->eof = 1;
96         return 0;
97     } else if (s->eof)
98         return AVERROR(EINVAL);
99
100     switch (ctx->outputs[0]->type) {
101     case AVMEDIA_TYPE_VIDEO:
102         CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,
103                                  frame->format);
104         break;
105     case AVMEDIA_TYPE_AUDIO:
106         CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,
107                                  frame->format);
108         break;
109     default:
110         return AVERROR(EINVAL);
111     }
112
113     if (!av_fifo_space(s->fifo) &&
114         (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +
115                                          sizeof(copy))) < 0)
116         return ret;
117
118     if (!(copy = av_frame_alloc()))
119         return AVERROR(ENOMEM);
120     av_frame_move_ref(copy, frame);
121
122     if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {
123         av_frame_move_ref(frame, copy);
124         av_frame_free(&copy);
125         return ret;
126     }
127
128     return 0;
129 }
130
131 #if FF_API_AVFILTERBUFFER
132 static void compat_free_buffer(void *opaque, uint8_t *data)
133 {
134     AVFilterBufferRef *buf = opaque;
135     avfilter_unref_buffer(buf);
136 }
137
138 static void compat_unref_buffer(void *opaque, uint8_t *data)
139 {
140     AVBufferRef *buf = opaque;
141     av_buffer_unref(&buf);
142 }
143
144 int av_buffersrc_buffer(AVFilterContext *ctx, AVFilterBufferRef *buf)
145 {
146     BufferSourceContext *s = ctx->priv;
147     AVFrame *frame = NULL;
148     AVBufferRef *dummy_buf = NULL;
149     int ret = 0, planes, i;
150
151     if (!buf) {
152         s->eof = 1;
153         return 0;
154     } else if (s->eof)
155         return AVERROR(EINVAL);
156
157     frame = av_frame_alloc();
158     if (!frame)
159         return AVERROR(ENOMEM);
160
161     dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, buf, 0);
162     if (!dummy_buf) {
163         ret = AVERROR(ENOMEM);
164         goto fail;
165     }
166
167     if ((ret = avfilter_copy_buf_props(frame, buf)) < 0)
168         goto fail;
169
170 #define WRAP_PLANE(ref_out, data, data_size)                            \
171 do {                                                                    \
172     AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \
173     if (!dummy_ref) {                                                   \
174         ret = AVERROR(ENOMEM);                                          \
175         goto fail;                                                      \
176     }                                                                   \
177     ref_out = av_buffer_create(data, data_size, compat_unref_buffer,    \
178                                dummy_ref, 0);                           \
179     if (!ref_out) {                                                     \
180         av_frame_unref(frame);                                          \
181         ret = AVERROR(ENOMEM);                                          \
182         goto fail;                                                      \
183     }                                                                   \
184 } while (0)
185
186     if (ctx->outputs[0]->type  == AVMEDIA_TYPE_VIDEO) {
187         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
188
189         if (!desc) {
190             ret = AVERROR(EINVAL);
191             goto fail;
192         }
193         planes = (desc->flags & PIX_FMT_PLANAR) ? desc->nb_components : 1;
194
195         for (i = 0; i < planes; i++) {
196             int h_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
197             int plane_size = (frame->width >> h_shift) * frame->linesize[i];
198
199             WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);
200         }
201     } else {
202         int planar = av_sample_fmt_is_planar(frame->format);
203         int channels = av_get_channel_layout_nb_channels(frame->channel_layout);
204
205         planes = planar ? channels : 1;
206
207         if (planes > FF_ARRAY_ELEMS(frame->buf)) {
208             frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);
209             frame->extended_buf = av_mallocz(sizeof(*frame->extended_buf) *
210                                              frame->nb_extended_buf);
211             if (!frame->extended_buf) {
212                 ret = AVERROR(ENOMEM);
213                 goto fail;
214             }
215         }
216
217         for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)
218             WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);
219
220         for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)
221             WRAP_PLANE(frame->extended_buf[i],
222                        frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],
223                        frame->linesize[0]);
224     }
225
226     ret = av_buffersrc_add_frame(ctx, frame);
227
228 fail:
229     av_buffer_unref(&dummy_buf);
230     av_frame_free(&frame);
231
232     return ret;
233 }
234 #endif
235
236 static av_cold int init_video(AVFilterContext *ctx, const char *args)
237 {
238     BufferSourceContext *c = ctx->priv;
239     char pix_fmt_str[128];
240     int n = 0;
241
242     if (!args ||
243         (n = sscanf(args, "%d:%d:%127[^:]:%d:%d:%d:%d", &c->w, &c->h, pix_fmt_str,
244                     &c->time_base.num, &c->time_base.den,
245                     &c->pixel_aspect.num, &c->pixel_aspect.den)) != 7) {
246         av_log(ctx, AV_LOG_ERROR, "Expected 7 arguments, but %d found in '%s'\n", n, args);
247         return AVERROR(EINVAL);
248     }
249     if ((c->pix_fmt = av_get_pix_fmt(pix_fmt_str)) == AV_PIX_FMT_NONE) {
250         char *tail;
251         c->pix_fmt = strtol(pix_fmt_str, &tail, 10);
252         if (*tail || c->pix_fmt < 0 || c->pix_fmt >= AV_PIX_FMT_NB) {
253             av_log(ctx, AV_LOG_ERROR, "Invalid pixel format string '%s'\n", pix_fmt_str);
254             return AVERROR(EINVAL);
255         }
256     }
257
258     if (!(c->fifo = av_fifo_alloc(sizeof(AVFrame*))))
259         return AVERROR(ENOMEM);
260
261     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d pixfmt:%s\n", c->w, c->h, av_get_pix_fmt_name(c->pix_fmt));
262     return 0;
263 }
264
265 #define OFFSET(x) offsetof(BufferSourceContext, x)
266 #define A AV_OPT_FLAG_AUDIO_PARAM
267 static const AVOption audio_options[] = {
268     { "time_base",      NULL, OFFSET(time_base),           AV_OPT_TYPE_RATIONAL, { .dbl = 0 }, 0, INT_MAX, A },
269     { "sample_rate",    NULL, OFFSET(sample_rate),         AV_OPT_TYPE_INT,      { .i64 = 0 }, 0, INT_MAX, A },
270     { "sample_fmt",     NULL, OFFSET(sample_fmt_str),      AV_OPT_TYPE_STRING,             .flags = A },
271     { "channel_layout", NULL, OFFSET(channel_layout_str),  AV_OPT_TYPE_STRING,             .flags = A },
272     { NULL },
273 };
274
275 static const AVClass abuffer_class = {
276     .class_name = "abuffer source",
277     .item_name  = av_default_item_name,
278     .option     = audio_options,
279     .version    = LIBAVUTIL_VERSION_INT,
280 };
281
282 static av_cold int init_audio(AVFilterContext *ctx, const char *args)
283 {
284     BufferSourceContext *s = ctx->priv;
285     int ret = 0;
286
287     s->class = &abuffer_class;
288     av_opt_set_defaults(s);
289
290     if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
291         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: %s.\n", args);
292         goto fail;
293     }
294
295     s->sample_fmt = av_get_sample_fmt(s->sample_fmt_str);
296     if (s->sample_fmt == AV_SAMPLE_FMT_NONE) {
297         av_log(ctx, AV_LOG_ERROR, "Invalid sample format %s.\n",
298                s->sample_fmt_str);
299         ret = AVERROR(EINVAL);
300         goto fail;
301     }
302
303     s->channel_layout = av_get_channel_layout(s->channel_layout_str);
304     if (!s->channel_layout) {
305         av_log(ctx, AV_LOG_ERROR, "Invalid channel layout %s.\n",
306                s->channel_layout_str);
307         ret = AVERROR(EINVAL);
308         goto fail;
309     }
310
311     if (!(s->fifo = av_fifo_alloc(sizeof(AVFrame*)))) {
312         ret = AVERROR(ENOMEM);
313         goto fail;
314     }
315
316     if (!s->time_base.num)
317         s->time_base = (AVRational){1, s->sample_rate};
318
319     av_log(ctx, AV_LOG_VERBOSE, "tb:%d/%d samplefmt:%s samplerate: %d "
320            "ch layout:%s\n", s->time_base.num, s->time_base.den, s->sample_fmt_str,
321            s->sample_rate, s->channel_layout_str);
322
323 fail:
324     av_opt_free(s);
325     return ret;
326 }
327
328 static av_cold void uninit(AVFilterContext *ctx)
329 {
330     BufferSourceContext *s = ctx->priv;
331     while (s->fifo && av_fifo_size(s->fifo)) {
332         AVFrame *frame;
333         av_fifo_generic_read(s->fifo, &frame, sizeof(frame), NULL);
334         av_frame_free(&frame);
335     }
336     av_fifo_free(s->fifo);
337     s->fifo = NULL;
338 }
339
340 static int query_formats(AVFilterContext *ctx)
341 {
342     BufferSourceContext *c = ctx->priv;
343     AVFilterChannelLayouts *channel_layouts = NULL;
344     AVFilterFormats *formats = NULL;
345     AVFilterFormats *samplerates = NULL;
346
347     switch (ctx->outputs[0]->type) {
348     case AVMEDIA_TYPE_VIDEO:
349         ff_add_format(&formats, c->pix_fmt);
350         ff_set_common_formats(ctx, formats);
351         break;
352     case AVMEDIA_TYPE_AUDIO:
353         ff_add_format(&formats,           c->sample_fmt);
354         ff_set_common_formats(ctx, formats);
355
356         ff_add_format(&samplerates,       c->sample_rate);
357         ff_set_common_samplerates(ctx, samplerates);
358
359         ff_add_channel_layout(&channel_layouts, c->channel_layout);
360         ff_set_common_channel_layouts(ctx, channel_layouts);
361         break;
362     default:
363         return AVERROR(EINVAL);
364     }
365
366     return 0;
367 }
368
369 static int config_props(AVFilterLink *link)
370 {
371     BufferSourceContext *c = link->src->priv;
372
373     switch (link->type) {
374     case AVMEDIA_TYPE_VIDEO:
375         link->w = c->w;
376         link->h = c->h;
377         link->sample_aspect_ratio = c->pixel_aspect;
378         break;
379     case AVMEDIA_TYPE_AUDIO:
380         link->channel_layout = c->channel_layout;
381         link->sample_rate    = c->sample_rate;
382         break;
383     default:
384         return AVERROR(EINVAL);
385     }
386
387     link->time_base = c->time_base;
388     return 0;
389 }
390
391 static int request_frame(AVFilterLink *link)
392 {
393     BufferSourceContext *c = link->src->priv;
394     AVFrame *frame;
395     int ret = 0;
396
397     if (!av_fifo_size(c->fifo)) {
398         if (c->eof)
399             return AVERROR_EOF;
400         return AVERROR(EAGAIN);
401     }
402     av_fifo_generic_read(c->fifo, &frame, sizeof(frame), NULL);
403
404     ff_filter_frame(link, frame);
405
406     return ret;
407 }
408
409 static int poll_frame(AVFilterLink *link)
410 {
411     BufferSourceContext *c = link->src->priv;
412     int size = av_fifo_size(c->fifo);
413     if (!size && c->eof)
414         return AVERROR_EOF;
415     return size/sizeof(AVFrame*);
416 }
417
418 static const AVFilterPad avfilter_vsrc_buffer_outputs[] = {
419     {
420         .name          = "default",
421         .type          = AVMEDIA_TYPE_VIDEO,
422         .request_frame = request_frame,
423         .poll_frame    = poll_frame,
424         .config_props  = config_props,
425     },
426     { NULL }
427 };
428
429 AVFilter avfilter_vsrc_buffer = {
430     .name      = "buffer",
431     .description = NULL_IF_CONFIG_SMALL("Buffer video frames, and make them accessible to the filterchain."),
432     .priv_size = sizeof(BufferSourceContext),
433     .query_formats = query_formats,
434
435     .init      = init_video,
436     .uninit    = uninit,
437
438     .inputs    = NULL,
439     .outputs   = avfilter_vsrc_buffer_outputs,
440 };
441
442 static const AVFilterPad avfilter_asrc_abuffer_outputs[] = {
443     {
444         .name          = "default",
445         .type          = AVMEDIA_TYPE_AUDIO,
446         .request_frame = request_frame,
447         .poll_frame    = poll_frame,
448         .config_props  = config_props,
449     },
450     { NULL }
451 };
452
453 AVFilter avfilter_asrc_abuffer = {
454     .name          = "abuffer",
455     .description   = NULL_IF_CONFIG_SMALL("Buffer audio frames, and make them accessible to the filterchain."),
456     .priv_size     = sizeof(BufferSourceContext),
457     .query_formats = query_formats,
458
459     .init      = init_audio,
460     .uninit    = uninit,
461
462     .inputs    = NULL,
463     .outputs   = avfilter_asrc_abuffer_outputs,
464 };