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