lavfi.c 13 KB

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