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