You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

442 lines
16KB

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