]> git.sesse.net Git - ffmpeg/blob - libavdevice/lavfi.c
avdevice/lavfi: add io.h, should fix msvc build
[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 #include <fcntl.h>              /* O_RDONLY */
30
31 #include "libavutil/bprint.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/file.h"
34 #include "libavutil/log.h"
35 #include "libavutil/mem.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavfilter/avfilter.h"
40 #include "libavfilter/avfiltergraph.h"
41 #include "libavfilter/buffersink.h"
42 #include "libavformat/internal.h"
43 #include "avdevice.h"
44
45 #if HAVE_UNISTD_H
46 #include <unistd.h>             /* close() */
47 #endif
48 #if HAVE_IO_H
49 #include <io.h>
50 #endif
51
52 typedef struct {
53     AVClass *class;          ///< class for private options
54     char          *graph_str;
55     char          *graph_filename;
56     char          *dump_graph;
57     AVFilterGraph *graph;
58     AVFilterContext **sinks;
59     int *sink_stream_map;
60     int *sink_eof;
61     int *stream_sink_map;
62     AVFrame *decoded_frame;
63 } LavfiContext;
64
65 static int *create_all_formats(int n)
66 {
67     int i, j, *fmts, count = 0;
68
69     for (i = 0; i < n; i++) {
70         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
71         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
72             count++;
73     }
74
75     if (!(fmts = av_malloc((count+1) * sizeof(int))))
76         return NULL;
77     for (j = 0, i = 0; i < n; i++) {
78         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
79         if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
80             fmts[j++] = i;
81     }
82     fmts[j] = -1;
83     return fmts;
84 }
85
86 av_cold static int lavfi_read_close(AVFormatContext *avctx)
87 {
88     LavfiContext *lavfi = avctx->priv_data;
89
90     av_freep(&lavfi->sink_stream_map);
91     av_freep(&lavfi->sink_eof);
92     av_freep(&lavfi->stream_sink_map);
93     av_freep(&lavfi->sinks);
94     avfilter_graph_free(&lavfi->graph);
95     av_frame_free(&lavfi->decoded_frame);
96
97     return 0;
98 }
99
100 av_cold static int lavfi_read_header(AVFormatContext *avctx)
101 {
102     LavfiContext *lavfi = avctx->priv_data;
103     AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
104     AVFilter *buffersink, *abuffersink;
105     int *pix_fmts = create_all_formats(AV_PIX_FMT_NB);
106     enum AVMediaType type;
107     int ret = 0, i, n;
108
109 #define FAIL(ERR) { ret = ERR; goto end; }
110
111     if (!pix_fmts)
112         FAIL(AVERROR(ENOMEM));
113
114     avfilter_register_all();
115
116     buffersink = avfilter_get_by_name("buffersink");
117     abuffersink = avfilter_get_by_name("abuffersink");
118
119     if (lavfi->graph_filename && lavfi->graph_str) {
120         av_log(avctx, AV_LOG_ERROR,
121                "Only one of the graph or graph_file options must be specified\n");
122         FAIL(AVERROR(EINVAL));
123     }
124
125     if (lavfi->graph_filename) {
126         AVBPrint graph_file_pb;
127         int fd = avpriv_open(lavfi->graph_filename, O_RDONLY);
128         if (fd == -1)
129             FAIL(AVERROR(EINVAL));
130         av_bprint_init(&graph_file_pb, 0, AV_BPRINT_SIZE_UNLIMITED);
131         ret = av_bprint_fd_contents(&graph_file_pb, fd);
132         av_bprint_chars(&graph_file_pb, '\0', 1);
133         close(fd);
134         if (!ret && !av_bprint_is_complete(&graph_file_pb))
135             ret = AVERROR(ENOMEM);
136         if (ret) {
137             av_bprint_finalize(&graph_file_pb, NULL);
138             FAIL(ret);
139         }
140         if ((ret = av_bprint_finalize(&graph_file_pb, &lavfi->graph_str)))
141             FAIL(ret);
142     }
143
144     if (!lavfi->graph_str)
145         lavfi->graph_str = av_strdup(avctx->filename);
146
147     /* parse the graph, create a stream for each open output */
148     if (!(lavfi->graph = avfilter_graph_alloc()))
149         FAIL(AVERROR(ENOMEM));
150
151     if ((ret = avfilter_graph_parse_ptr(lavfi->graph, lavfi->graph_str,
152                                     &input_links, &output_links, avctx)) < 0)
153         FAIL(ret);
154
155     if (input_links) {
156         av_log(avctx, AV_LOG_ERROR,
157                "Open inputs in the filtergraph are not acceptable\n");
158         FAIL(AVERROR(EINVAL));
159     }
160
161     /* count the outputs */
162     for (n = 0, inout = output_links; inout; n++, inout = inout->next);
163
164     if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))
165         FAIL(AVERROR(ENOMEM));
166     if (!(lavfi->sink_eof = av_mallocz(sizeof(int) * n)))
167         FAIL(AVERROR(ENOMEM));
168     if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))
169         FAIL(AVERROR(ENOMEM));
170
171     for (i = 0; i < n; i++)
172         lavfi->stream_sink_map[i] = -1;
173
174     /* parse the output link names - they need to be of the form out0, out1, ...
175      * create a mapping between them and the streams */
176     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
177         int stream_idx;
178         if (!strcmp(inout->name, "out"))
179             stream_idx = 0;
180         else if (sscanf(inout->name, "out%d\n", &stream_idx) != 1) {
181             av_log(avctx,  AV_LOG_ERROR,
182                    "Invalid outpad name '%s'\n", inout->name);
183             FAIL(AVERROR(EINVAL));
184         }
185
186         if ((unsigned)stream_idx >= n) {
187             av_log(avctx, AV_LOG_ERROR,
188                    "Invalid index was specified in output '%s', "
189                    "must be a non-negative value < %d\n",
190                    inout->name, n);
191             FAIL(AVERROR(EINVAL));
192         }
193
194         /* is an audio or video output? */
195         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
196         if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
197             av_log(avctx,  AV_LOG_ERROR,
198                    "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
199             FAIL(AVERROR(EINVAL));
200         }
201
202         if (lavfi->stream_sink_map[stream_idx] != -1) {
203             av_log(avctx,  AV_LOG_ERROR,
204                    "An output with stream index %d was already specified\n",
205                    stream_idx);
206             FAIL(AVERROR(EINVAL));
207         }
208         lavfi->sink_stream_map[i] = stream_idx;
209         lavfi->stream_sink_map[stream_idx] = i;
210     }
211
212     /* for each open output create a corresponding stream */
213     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
214         AVStream *st;
215         if (!(st = avformat_new_stream(avctx, NULL)))
216             FAIL(AVERROR(ENOMEM));
217         st->id = i;
218     }
219
220     /* create a sink for each output and connect them to the graph */
221     lavfi->sinks = av_malloc_array(avctx->nb_streams, sizeof(AVFilterContext *));
222     if (!lavfi->sinks)
223         FAIL(AVERROR(ENOMEM));
224
225     for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
226         AVFilterContext *sink;
227
228         type = inout->filter_ctx->output_pads[inout->pad_idx].type;
229
230         if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
231             type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
232                 av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
233                 FAIL(AVERROR_FILTER_NOT_FOUND);
234         }
235
236         if (type == AVMEDIA_TYPE_VIDEO) {
237             ret = avfilter_graph_create_filter(&sink, buffersink,
238                                                inout->name, NULL,
239                                                NULL, lavfi->graph);
240             if (ret >= 0)
241                 ret = av_opt_set_int_list(sink, "pix_fmts", pix_fmts,  AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
242             if (ret < 0)
243                 goto end;
244         } else if (type == AVMEDIA_TYPE_AUDIO) {
245             enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_U8,
246                                                   AV_SAMPLE_FMT_S16,
247                                                   AV_SAMPLE_FMT_S32,
248                                                   AV_SAMPLE_FMT_FLT,
249                                                   AV_SAMPLE_FMT_DBL, -1 };
250
251             ret = avfilter_graph_create_filter(&sink, abuffersink,
252                                                inout->name, NULL,
253                                                NULL, lavfi->graph);
254             if (ret >= 0)
255                 ret = av_opt_set_int_list(sink, "sample_fmts", sample_fmts,  AV_SAMPLE_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
256             if (ret < 0)
257                 goto end;
258             ret = av_opt_set_int(sink, "all_channel_counts", 1,
259                                  AV_OPT_SEARCH_CHILDREN);
260             if (ret < 0)
261                 goto end;
262         }
263
264         lavfi->sinks[i] = sink;
265         if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)
266             FAIL(ret);
267     }
268
269     /* configure the graph */
270     if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)
271         FAIL(ret);
272
273     if (lavfi->dump_graph) {
274         char *dump = avfilter_graph_dump(lavfi->graph, lavfi->dump_graph);
275         fputs(dump, stderr);
276         fflush(stderr);
277         av_free(dump);
278     }
279
280     /* fill each stream with the information in the corresponding sink */
281     for (i = 0; i < avctx->nb_streams; i++) {
282         AVFilterLink *link = lavfi->sinks[lavfi->stream_sink_map[i]]->inputs[0];
283         AVStream *st = avctx->streams[i];
284         st->codec->codec_type = link->type;
285         avpriv_set_pts_info(st, 64, link->time_base.num, link->time_base.den);
286         if (link->type == AVMEDIA_TYPE_VIDEO) {
287             st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
288             st->codec->pix_fmt    = link->format;
289             st->codec->time_base  = link->time_base;
290             st->codec->width      = link->w;
291             st->codec->height     = link->h;
292             st       ->sample_aspect_ratio =
293             st->codec->sample_aspect_ratio = link->sample_aspect_ratio;
294             avctx->probesize = FFMAX(avctx->probesize,
295                                      link->w * link->h *
296                                      av_get_padded_bits_per_pixel(av_pix_fmt_desc_get(link->format)) *
297                                      30);
298         } else if (link->type == AVMEDIA_TYPE_AUDIO) {
299             st->codec->codec_id    = av_get_pcm_codec(link->format, -1);
300             st->codec->channels    = avfilter_link_get_channels(link);
301             st->codec->sample_fmt  = link->format;
302             st->codec->sample_rate = link->sample_rate;
303             st->codec->time_base   = link->time_base;
304             st->codec->channel_layout = link->channel_layout;
305             if (st->codec->codec_id == AV_CODEC_ID_NONE)
306                 av_log(avctx, AV_LOG_ERROR,
307                        "Could not find PCM codec for sample format %s.\n",
308                        av_get_sample_fmt_name(link->format));
309         }
310     }
311
312     if (!(lavfi->decoded_frame = av_frame_alloc()))
313         FAIL(AVERROR(ENOMEM));
314
315 end:
316     av_free(pix_fmts);
317     avfilter_inout_free(&input_links);
318     avfilter_inout_free(&output_links);
319     if (ret < 0)
320         lavfi_read_close(avctx);
321     return ret;
322 }
323
324 static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)
325 {
326     LavfiContext *lavfi = avctx->priv_data;
327     double min_pts = DBL_MAX;
328     int stream_idx, min_pts_sink_idx = 0;
329     AVFrame *frame = lavfi->decoded_frame;
330     AVPicture pict;
331     AVDictionary *frame_metadata;
332     int ret, i;
333     int size = 0;
334
335     /* iterate through all the graph sinks. Select the sink with the
336      * minimum PTS */
337     for (i = 0; i < avctx->nb_streams; i++) {
338         AVRational tb = lavfi->sinks[i]->inputs[0]->time_base;
339         double d;
340         int ret;
341
342         if (lavfi->sink_eof[i])
343             continue;
344
345         ret = av_buffersink_get_frame_flags(lavfi->sinks[i], frame,
346                                             AV_BUFFERSINK_FLAG_PEEK);
347         if (ret == AVERROR_EOF) {
348             av_dlog(avctx, "EOF sink_idx:%d\n", i);
349             lavfi->sink_eof[i] = 1;
350             continue;
351         } else if (ret < 0)
352             return ret;
353         d = av_rescale_q(frame->pts, tb, AV_TIME_BASE_Q);
354         av_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
355         av_frame_unref(frame);
356
357         if (d < min_pts) {
358             min_pts = d;
359             min_pts_sink_idx = i;
360         }
361     }
362     if (min_pts == DBL_MAX)
363         return AVERROR_EOF;
364
365     av_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
366
367     av_buffersink_get_frame_flags(lavfi->sinks[min_pts_sink_idx], frame, 0);
368     stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
369
370     if (frame->width /* FIXME best way of testing a video */) {
371         size = avpicture_get_size(frame->format, frame->width, frame->height);
372         if ((ret = av_new_packet(pkt, size)) < 0)
373             return ret;
374
375         memcpy(pict.data,     frame->data,     4*sizeof(frame->data[0]));
376         memcpy(pict.linesize, frame->linesize, 4*sizeof(frame->linesize[0]));
377
378         avpicture_layout(&pict, frame->format, frame->width, frame->height,
379                          pkt->data, size);
380     } else if (av_frame_get_channels(frame) /* FIXME test audio */) {
381         size = frame->nb_samples * av_get_bytes_per_sample(frame->format) *
382                                    av_frame_get_channels(frame);
383         if ((ret = av_new_packet(pkt, size)) < 0)
384             return ret;
385         memcpy(pkt->data, frame->data[0], size);
386     }
387
388     frame_metadata = av_frame_get_metadata(frame);
389     if (frame_metadata) {
390         uint8_t *metadata;
391         AVDictionaryEntry *e = NULL;
392         AVBPrint meta_buf;
393
394         av_bprint_init(&meta_buf, 0, AV_BPRINT_SIZE_UNLIMITED);
395         while ((e = av_dict_get(frame_metadata, "", e, AV_DICT_IGNORE_SUFFIX))) {
396             av_bprintf(&meta_buf, "%s", e->key);
397             av_bprint_chars(&meta_buf, '\0', 1);
398             av_bprintf(&meta_buf, "%s", e->value);
399             av_bprint_chars(&meta_buf, '\0', 1);
400         }
401         if (!av_bprint_is_complete(&meta_buf) ||
402             !(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
403                                                  meta_buf.len))) {
404             av_bprint_finalize(&meta_buf, NULL);
405             return AVERROR(ENOMEM);
406         }
407         memcpy(metadata, meta_buf.str, meta_buf.len);
408         av_bprint_finalize(&meta_buf, NULL);
409     }
410
411     pkt->stream_index = stream_idx;
412     pkt->pts = frame->pts;
413     pkt->pos = av_frame_get_pkt_pos(frame);
414     pkt->size = size;
415     av_frame_unref(frame);
416     return size;
417 }
418
419 #define OFFSET(x) offsetof(LavfiContext, x)
420
421 #define DEC AV_OPT_FLAG_DECODING_PARAM
422
423 static const AVOption options[] = {
424     { "graph",     "set libavfilter graph", OFFSET(graph_str),  AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
425     { "graph_file","set libavfilter graph filename", OFFSET(graph_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
426     { "dumpgraph", "dump graph to stderr",  OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
427     { NULL },
428 };
429
430 static const AVClass lavfi_class = {
431     .class_name = "lavfi indev",
432     .item_name  = av_default_item_name,
433     .option     = options,
434     .version    = LIBAVUTIL_VERSION_INT,
435     .category   = AV_CLASS_CATEGORY_DEVICE_INPUT,
436 };
437
438 AVInputFormat ff_lavfi_demuxer = {
439     .name           = "lavfi",
440     .long_name      = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
441     .priv_data_size = sizeof(LavfiContext),
442     .read_header    = lavfi_read_header,
443     .read_packet    = lavfi_read_packet,
444     .read_close     = lavfi_read_close,
445     .flags          = AVFMT_NOFILE,
446     .priv_class     = &lavfi_class,
447 };