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.

400 lines
14KB

  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/log.h"
  28. #include "libavutil/mem.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/parseutils.h"
  31. #include "libavutil/pixdesc.h"
  32. #include "libavutil/audioconvert.h"
  33. #include "libavfilter/avfilter.h"
  34. #include "libavfilter/avfiltergraph.h"
  35. #include "libavfilter/buffersink.h"
  36. #include "libavformat/internal.h"
  37. #include "avdevice.h"
  38. typedef struct {
  39. AVClass *class; ///< class for private options
  40. char *graph_str;
  41. char *dump_graph;
  42. AVFilterGraph *graph;
  43. AVFilterContext **sinks;
  44. int *sink_stream_map;
  45. int *sink_eof;
  46. int *stream_sink_map;
  47. } LavfiContext;
  48. static int *create_all_formats(int n)
  49. {
  50. int i, j, *fmts, count = 0;
  51. for (i = 0; i < n; i++) {
  52. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
  53. if (!(desc->flags & PIX_FMT_HWACCEL))
  54. count++;
  55. }
  56. if (!(fmts = av_malloc((count+1) * sizeof(int))))
  57. return NULL;
  58. for (j = 0, i = 0; i < n; i++) {
  59. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(i);
  60. if (!(desc->flags & PIX_FMT_HWACCEL))
  61. fmts[j++] = i;
  62. }
  63. fmts[j] = -1;
  64. return fmts;
  65. }
  66. av_cold static int lavfi_read_close(AVFormatContext *avctx)
  67. {
  68. LavfiContext *lavfi = avctx->priv_data;
  69. av_freep(&lavfi->sink_stream_map);
  70. av_freep(&lavfi->sink_eof);
  71. av_freep(&lavfi->stream_sink_map);
  72. av_freep(&lavfi->sinks);
  73. avfilter_graph_free(&lavfi->graph);
  74. return 0;
  75. }
  76. av_cold static int lavfi_read_header(AVFormatContext *avctx)
  77. {
  78. LavfiContext *lavfi = avctx->priv_data;
  79. AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
  80. AVFilter *buffersink, *abuffersink;
  81. int *pix_fmts = create_all_formats(AV_PIX_FMT_NB);
  82. enum AVMediaType type;
  83. int ret = 0, i, n;
  84. #define FAIL(ERR) { ret = ERR; goto end; }
  85. if (!pix_fmts)
  86. FAIL(AVERROR(ENOMEM));
  87. avfilter_register_all();
  88. buffersink = avfilter_get_by_name("ffbuffersink");
  89. abuffersink = avfilter_get_by_name("ffabuffersink");
  90. if (!lavfi->graph_str)
  91. lavfi->graph_str = av_strdup(avctx->filename);
  92. /* parse the graph, create a stream for each open output */
  93. if (!(lavfi->graph = avfilter_graph_alloc()))
  94. FAIL(AVERROR(ENOMEM));
  95. if ((ret = avfilter_graph_parse(lavfi->graph, lavfi->graph_str,
  96. &input_links, &output_links, avctx)) < 0)
  97. FAIL(ret);
  98. if (input_links) {
  99. av_log(avctx, AV_LOG_ERROR,
  100. "Open inputs in the filtergraph are not acceptable\n");
  101. FAIL(AVERROR(EINVAL));
  102. }
  103. /* count the outputs */
  104. for (n = 0, inout = output_links; inout; n++, inout = inout->next);
  105. if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))
  106. FAIL(AVERROR(ENOMEM));
  107. if (!(lavfi->sink_eof = av_mallocz(sizeof(int) * n)))
  108. FAIL(AVERROR(ENOMEM));
  109. if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))
  110. FAIL(AVERROR(ENOMEM));
  111. for (i = 0; i < n; i++)
  112. lavfi->stream_sink_map[i] = -1;
  113. /* parse the output link names - they need to be of the form out0, out1, ...
  114. * create a mapping between them and the streams */
  115. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  116. int stream_idx;
  117. if (!strcmp(inout->name, "out"))
  118. stream_idx = 0;
  119. else if (sscanf(inout->name, "out%d\n", &stream_idx) != 1) {
  120. av_log(avctx, AV_LOG_ERROR,
  121. "Invalid outpad name '%s'\n", inout->name);
  122. FAIL(AVERROR(EINVAL));
  123. }
  124. if ((unsigned)stream_idx >= n) {
  125. av_log(avctx, AV_LOG_ERROR,
  126. "Invalid index was specified in output '%s', "
  127. "must be a non-negative value < %d\n",
  128. inout->name, n);
  129. FAIL(AVERROR(EINVAL));
  130. }
  131. /* is an audio or video output? */
  132. type = inout->filter_ctx->output_pads[inout->pad_idx].type;
  133. if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
  134. av_log(avctx, AV_LOG_ERROR,
  135. "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
  136. FAIL(AVERROR(EINVAL));
  137. }
  138. if (lavfi->stream_sink_map[stream_idx] != -1) {
  139. av_log(avctx, AV_LOG_ERROR,
  140. "An output with stream index %d was already specified\n",
  141. stream_idx);
  142. FAIL(AVERROR(EINVAL));
  143. }
  144. lavfi->sink_stream_map[i] = stream_idx;
  145. lavfi->stream_sink_map[stream_idx] = i;
  146. }
  147. /* for each open output create a corresponding stream */
  148. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  149. AVStream *st;
  150. if (!(st = avformat_new_stream(avctx, NULL)))
  151. FAIL(AVERROR(ENOMEM));
  152. st->id = i;
  153. }
  154. /* create a sink for each output and connect them to the graph */
  155. lavfi->sinks = av_malloc(sizeof(AVFilterContext *) * avctx->nb_streams);
  156. if (!lavfi->sinks)
  157. FAIL(AVERROR(ENOMEM));
  158. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  159. AVFilterContext *sink;
  160. type = inout->filter_ctx->output_pads[inout->pad_idx].type;
  161. if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
  162. type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
  163. av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
  164. FAIL(AVERROR_FILTER_NOT_FOUND);
  165. }
  166. if (type == AVMEDIA_TYPE_VIDEO) {
  167. AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
  168. buffersink_params->pixel_fmts = pix_fmts;
  169. ret = avfilter_graph_create_filter(&sink, buffersink,
  170. inout->name, NULL,
  171. buffersink_params, lavfi->graph);
  172. av_freep(&buffersink_params);
  173. if (ret < 0)
  174. goto end;
  175. } else if (type == AVMEDIA_TYPE_AUDIO) {
  176. enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_U8,
  177. AV_SAMPLE_FMT_S16,
  178. AV_SAMPLE_FMT_S32,
  179. AV_SAMPLE_FMT_FLT,
  180. AV_SAMPLE_FMT_DBL, -1 };
  181. AVABufferSinkParams *abuffersink_params = av_abuffersink_params_alloc();
  182. abuffersink_params->sample_fmts = sample_fmts;
  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 = AV_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 == AV_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;
  253. if (lavfi->sink_eof[i])
  254. continue;
  255. ret = av_buffersink_get_buffer_ref(lavfi->sinks[i],
  256. &ref, AV_BUFFERSINK_FLAG_PEEK);
  257. if (ret == AVERROR_EOF) {
  258. av_dlog(avctx, "EOF sink_idx:%d\n", i);
  259. lavfi->sink_eof[i] = 1;
  260. continue;
  261. } else if (ret < 0)
  262. return ret;
  263. d = av_rescale_q(ref->pts, tb, AV_TIME_BASE_Q);
  264. av_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
  265. if (d < min_pts) {
  266. min_pts = d;
  267. min_pts_sink_idx = i;
  268. }
  269. }
  270. if (min_pts == DBL_MAX)
  271. return AVERROR_EOF;
  272. av_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
  273. av_buffersink_get_buffer_ref(lavfi->sinks[min_pts_sink_idx], &ref, 0);
  274. stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
  275. if (ref->video) {
  276. size = avpicture_get_size(ref->format, ref->video->w, ref->video->h);
  277. if ((ret = av_new_packet(pkt, size)) < 0)
  278. return ret;
  279. memcpy(pict.data, ref->data, 4*sizeof(ref->data[0]));
  280. memcpy(pict.linesize, ref->linesize, 4*sizeof(ref->linesize[0]));
  281. avpicture_layout(&pict, ref->format, ref->video->w,
  282. ref->video->h, pkt->data, size);
  283. } else if (ref->audio) {
  284. size = ref->audio->nb_samples *
  285. av_get_bytes_per_sample(ref->format) *
  286. av_get_channel_layout_nb_channels(ref->audio->channel_layout);
  287. if ((ret = av_new_packet(pkt, size)) < 0)
  288. return ret;
  289. memcpy(pkt->data, ref->data[0], size);
  290. }
  291. if (ref->metadata) {
  292. uint8_t *metadata;
  293. AVDictionaryEntry *e = NULL;
  294. AVBPrint meta_buf;
  295. av_bprint_init(&meta_buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  296. while ((e = av_dict_get(ref->metadata, "", e, AV_DICT_IGNORE_SUFFIX))) {
  297. av_bprintf(&meta_buf, "%s", e->key);
  298. av_bprint_chars(&meta_buf, '\0', 1);
  299. av_bprintf(&meta_buf, "%s", e->value);
  300. av_bprint_chars(&meta_buf, '\0', 1);
  301. }
  302. if (!av_bprint_is_complete(&meta_buf) ||
  303. !(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
  304. meta_buf.len))) {
  305. av_bprint_finalize(&meta_buf, NULL);
  306. return AVERROR(ENOMEM);
  307. }
  308. memcpy(metadata, meta_buf.str, meta_buf.len);
  309. av_bprint_finalize(&meta_buf, NULL);
  310. }
  311. pkt->stream_index = stream_idx;
  312. pkt->pts = ref->pts;
  313. pkt->pos = ref->pos;
  314. pkt->size = size;
  315. avfilter_unref_buffer(ref);
  316. return size;
  317. }
  318. #define OFFSET(x) offsetof(LavfiContext, x)
  319. #define DEC AV_OPT_FLAG_DECODING_PARAM
  320. static const AVOption options[] = {
  321. { "graph", "set libavfilter graph", OFFSET(graph_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  322. { "dumpgraph", "dump graph to stderr", OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  323. { NULL },
  324. };
  325. static const AVClass lavfi_class = {
  326. .class_name = "lavfi indev",
  327. .item_name = av_default_item_name,
  328. .option = options,
  329. .version = LIBAVUTIL_VERSION_INT,
  330. };
  331. AVInputFormat ff_lavfi_demuxer = {
  332. .name = "lavfi",
  333. .long_name = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
  334. .priv_data_size = sizeof(LavfiContext),
  335. .read_header = lavfi_read_header,
  336. .read_packet = lavfi_read_packet,
  337. .read_close = lavfi_read_close,
  338. .flags = AVFMT_NOFILE,
  339. .priv_class = &lavfi_class,
  340. };