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