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.

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