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