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