lavfi.c 15 KB

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