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.

429 lines
15KB

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