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