lavfi.c 13 KB

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