]> git.sesse.net Git - ffmpeg/blob - libavdevice/lavfi.c
lavf-regression: minimal metadata test.
[ffmpeg] / libavdevice / lavfi.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
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  * libavfilter virtual input device
24  */
25
26 /* #define DEBUG */
27
28 #include "float.h"              /* DBL_MIN, DBL_MAX */
29
30 #include "libavutil/log.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/parseutils.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavfilter/avfilter.h"
36 #include "libavfilter/avfiltergraph.h"
37 #include "libavfilter/buffersink.h"
38 #include "libavformat/internal.h"
39 #include "avdevice.h"
40
41 typedef struct {
42     AVClass *class;          ///< class for private options
43     char          *graph_str;
44     AVFilterGraph *graph;
45     AVFilterContext **sinks;
46     int *sink_stream_map;
47     int *stream_sink_map;
48 } LavfiContext;
49
50 static int *create_all_formats(int n)
51 {
52     int i, j, *fmts, count = 0;
53
54     for (i = 0; i < n; i++)
55         if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
56             count++;
57
58     if (!(fmts = av_malloc((count+1) * sizeof(int))))
59         return NULL;
60     for (j = 0, i = 0; i < n; i++) {
61         if (!(av_pix_fmt_descriptors[i].flags & PIX_FMT_HWACCEL))
62             fmts[j++] = i;
63     }
64     fmts[j] = -1;
65     return fmts;
66 }
67
68 av_cold static int lavfi_read_close(AVFormatContext *avctx)
69 {
70     LavfiContext *lavfi = avctx->priv_data;
71
72     av_freep(&lavfi->sink_stream_map);
73     av_freep(&lavfi->stream_sink_map);
74     avfilter_graph_free(&lavfi->graph);
75
76     return 0;
77 }
78
79 av_cold static int lavfi_read_header(AVFormatContext *avctx,
80                                      AVFormatParameters *ap)
81 {
82     LavfiContext *lavfi = avctx->priv_data;
83     AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
84     AVFilter *buffersink, *abuffersink;
85     int *pix_fmts = create_all_formats(PIX_FMT_NB);
86     enum AVMediaType type;
87     int ret = 0, i, n;
88
89 #define FAIL(ERR) { ret = ERR; goto end; }
90
91     avfilter_register_all();
92
93     buffersink = avfilter_get_by_name("buffersink");
94     abuffersink = avfilter_get_by_name("abuffersink");
95
96     if (!lavfi->graph_str)
97         lavfi->graph_str = av_strdup(avctx->filename);
98
99     /* parse the graph, create a stream for each open output */
100     if (!(lavfi->graph = avfilter_graph_alloc()))
101         FAIL(AVERROR(ENOMEM));
102
103     if ((ret = avfilter_graph_parse(lavfi->graph, lavfi->graph_str,
104                                     &input_links, &output_links, avctx)) < 0)
105         FAIL(ret);
106
107     if (input_links) {
108         av_log(avctx, AV_LOG_ERROR,
109                "Open inputs in the filtergraph are not acceptable\n");
110         FAIL(AVERROR(EINVAL));
111     }
112
113     /* count the outputs */
114     for (n = 0, inout = output_links; inout; n++, inout = inout->next);
115
116     if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))
117         FAIL(AVERROR(ENOMEM));
118     if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))
119         FAIL(AVERROR(ENOMEM));
120
121     for (i = 0; i < n; i++)
122         lavfi->stream_sink_map[i] = -1;
123
124     /* parse the output link names - they need to be of the form out0, out1, ...
125      * create a mapping between them and the streams */
126     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
127         int stream_idx;
128         if (!strcmp(inout->name, "out"))
129             stream_idx = 0;
130         else if (sscanf(inout->name, "out%d\n", &stream_idx) != 1) {
131             av_log(avctx,  AV_LOG_ERROR,
132                    "Invalid outpad name '%s'\n", inout->name);
133             FAIL(AVERROR(EINVAL));
134         }
135
136         if ((unsigned)stream_idx >= n) {
137             av_log(avctx, AV_LOG_ERROR,
138                    "Invalid index was specified in output '%s', "
139                    "must be a non-negative value < %d\n",
140                    inout->name, n);
141             FAIL(AVERROR(EINVAL));
142         }
143
144         /* is a video output? */
145         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
146         if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
147             av_log(avctx,  AV_LOG_ERROR,
148                    "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
149             FAIL(AVERROR(EINVAL));
150         }
151
152         if (lavfi->stream_sink_map[stream_idx] != -1) {
153             av_log(avctx,  AV_LOG_ERROR,
154                    "An with stream index %d was already specified\n",
155                    stream_idx);
156             FAIL(AVERROR(EINVAL));
157         }
158         lavfi->sink_stream_map[i] = stream_idx;
159         lavfi->stream_sink_map[stream_idx] = i;
160     }
161
162     /* for each open output create a corresponding stream */
163     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
164         AVStream *st;
165         if (!(st = avformat_new_stream(avctx, NULL)))
166             FAIL(AVERROR(ENOMEM));
167         st->id = i;
168     }
169
170     /* create a sink for each output and connect them to the graph */
171     lavfi->sinks = av_malloc(sizeof(AVFilterContext *) * avctx->nb_streams);
172     if (!lavfi->sinks)
173         FAIL(AVERROR(ENOMEM));
174
175     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
176         AVFilterContext *sink;
177
178         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
179
180         if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
181             type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
182                 av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
183                 FAIL(AVERROR_FILTER_NOT_FOUND);
184         }
185
186         if (type == AVMEDIA_TYPE_VIDEO) {
187         AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
188         buffersink_params->pixel_fmts = pix_fmts;
189
190 #if FF_API_OLD_VSINK_API
191         ret = avfilter_graph_create_filter(&sink, buffersink,
192                                            inout->name, NULL,
193                                            pix_fmts, lavfi->graph);
194 #else
195         buffersink_params->pixel_fmts = pix_fmts;
196         ret = avfilter_graph_create_filter(&sink, buffersink,
197                                            inout->name, NULL,
198                                            buffersink_params, lavfi->graph);
199 #endif
200         av_freep(&buffersink_params);
201
202         if (ret < 0)
203             goto end;
204         } else if (type == AVMEDIA_TYPE_AUDIO) {
205             enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, -1 };
206             const int packing_fmts[] = { AVFILTER_PACKED, -1 };
207             const int64_t *chlayouts = avfilter_all_channel_layouts;
208             AVABufferSinkParams *abuffersink_params = av_abuffersink_params_alloc();
209             abuffersink_params->sample_fmts = sample_fmts;
210             abuffersink_params->packing_fmts = packing_fmts;
211             abuffersink_params->channel_layouts = chlayouts;
212
213             ret = avfilter_graph_create_filter(&sink, abuffersink,
214                                                inout->name, NULL,
215                                                abuffersink_params, lavfi->graph);
216             av_free(abuffersink_params);
217             if (ret < 0)
218                 goto end;
219         }
220
221         lavfi->sinks[i] = sink;
222         if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)
223             FAIL(ret);
224     }
225
226     /* configure the graph */
227     if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)
228         FAIL(ret);
229
230     /* fill each stream with the information in the corresponding sink */
231     for (i = 0; i < avctx->nb_streams; i++) {
232         AVFilterLink *link = lavfi->sinks[lavfi->stream_sink_map[i]]->inputs[0];
233         AVStream *st = avctx->streams[i];
234         st->codec->codec_type = link->type;
235         avpriv_set_pts_info(st, 64, link->time_base.num, link->time_base.den);
236         if (link->type == AVMEDIA_TYPE_VIDEO) {
237             st->codec->codec_id   = CODEC_ID_RAWVIDEO;
238             st->codec->pix_fmt    = link->format;
239             st->codec->time_base  = link->time_base;
240             st->codec->width      = link->w;
241             st->codec->height     = link->h;
242             st       ->sample_aspect_ratio =
243             st->codec->sample_aspect_ratio = link->sample_aspect_ratio;
244         } else if (link->type == AVMEDIA_TYPE_AUDIO) {
245             st->codec->codec_id    = CODEC_ID_PCM_S16LE;
246             st->codec->channels    = av_get_channel_layout_nb_channels(link->channel_layout);
247             st->codec->sample_fmt  = link->format;
248             st->codec->sample_rate = link->sample_rate;
249             st->codec->time_base   = link->time_base;
250             st->codec->channel_layout = link->channel_layout;
251         }
252     }
253
254 end:
255     avfilter_inout_free(&input_links);
256     avfilter_inout_free(&output_links);
257     if (ret < 0)
258         lavfi_read_close(avctx);
259     return ret;
260 }
261
262 static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)
263 {
264     LavfiContext *lavfi = avctx->priv_data;
265     double min_pts = DBL_MAX;
266     int stream_idx, min_pts_sink_idx = 0;
267     AVFilterBufferRef *ref;
268     AVPicture pict;
269     int ret, i, size;
270
271     /* iterate through all the graph sinks. Select the sink with the
272      * minimum PTS */
273     for (i = 0; i < avctx->nb_streams; i++) {
274         AVRational tb = lavfi->sinks[i]->inputs[0]->time_base;
275         double d;
276         int ret = av_buffersink_get_buffer_ref(lavfi->sinks[i],
277                                                &ref, AV_BUFFERSINK_FLAG_PEEK);
278         if (ret < 0)
279             return ret;
280         d = av_rescale_q(ref->pts, tb, AV_TIME_BASE_Q);
281         av_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
282
283         if (d < min_pts) {
284             min_pts = d;
285             min_pts_sink_idx = i;
286         }
287     }
288     av_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
289
290     av_buffersink_get_buffer_ref(lavfi->sinks[min_pts_sink_idx], &ref, 0);
291     stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
292
293     if (ref->video) {
294         size = avpicture_get_size(ref->format, ref->video->w, ref->video->h);
295         if ((ret = av_new_packet(pkt, size)) < 0)
296             return ret;
297
298         memcpy(pict.data,     ref->data,     4*sizeof(ref->data[0]));
299         memcpy(pict.linesize, ref->linesize, 4*sizeof(ref->linesize[0]));
300
301         avpicture_layout(&pict, ref->format, ref->video->w,
302                          ref->video->h, pkt->data, size);
303     } else if (ref->audio) {
304         size = ref->audio->nb_samples *
305             av_get_bytes_per_sample(ref->format) *
306             av_get_channel_layout_nb_channels(ref->audio->channel_layout);
307         if ((ret = av_new_packet(pkt, size)) < 0)
308             return ret;
309         memcpy(pkt->data, ref->data[0], size);
310     }
311
312     pkt->stream_index = stream_idx;
313     pkt->pts = ref->pts;
314     pkt->pos = ref->pos;
315     pkt->size = size;
316     avfilter_unref_buffer(ref);
317
318     return size;
319 }
320
321 #define OFFSET(x) offsetof(LavfiContext, x)
322
323 #define DEC AV_OPT_FLAG_DECODING_PARAM
324
325 static const AVOption options[] = {
326     { "graph", "Libavfilter graph", OFFSET(graph_str),  AV_OPT_TYPE_STRING, {.str = NULL }, 0,  0, DEC },
327     { NULL },
328 };
329
330 static const AVClass lavfi_class = {
331     .class_name = "lavfi indev",
332     .item_name  = av_default_item_name,
333     .option     = options,
334     .version    = LIBAVUTIL_VERSION_INT,
335 };
336
337 AVInputFormat ff_lavfi_demuxer = {
338     .name           = "lavfi",
339     .long_name      = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
340     .priv_data_size = sizeof(LavfiContext),
341     .read_header    = lavfi_read_header,
342     .read_packet    = lavfi_read_packet,
343     .read_close     = lavfi_read_close,
344     .flags          = AVFMT_NOFILE,
345     .priv_class     = &lavfi_class,
346 };