lavfi.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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/imgutils.h"
  30. #include "libavutil/internal.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/buffersink.h"
  38. #include "libavformat/avio_internal.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. int *sink_stream_subcc_map;
  52. int nb_sinks;
  53. AVPacket subcc_packet;
  54. } LavfiContext;
  55. av_cold static int lavfi_read_close(AVFormatContext *avctx)
  56. {
  57. LavfiContext *lavfi = avctx->priv_data;
  58. av_freep(&lavfi->sink_stream_map);
  59. av_freep(&lavfi->sink_eof);
  60. av_freep(&lavfi->stream_sink_map);
  61. av_freep(&lavfi->sink_stream_subcc_map);
  62. av_freep(&lavfi->sinks);
  63. avfilter_graph_free(&lavfi->graph);
  64. return 0;
  65. }
  66. static int create_subcc_streams(AVFormatContext *avctx)
  67. {
  68. LavfiContext *lavfi = avctx->priv_data;
  69. AVStream *st;
  70. int stream_idx, sink_idx;
  71. AVRational *time_base;
  72. for (stream_idx = 0; stream_idx < lavfi->nb_sinks; stream_idx++) {
  73. sink_idx = lavfi->stream_sink_map[stream_idx];
  74. if (lavfi->sink_stream_subcc_map[sink_idx]) {
  75. lavfi->sink_stream_subcc_map[sink_idx] = avctx->nb_streams;
  76. if (!(st = avformat_new_stream(avctx, NULL)))
  77. return AVERROR(ENOMEM);
  78. st->codecpar->codec_id = AV_CODEC_ID_EIA_608;
  79. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  80. time_base = &avctx->streams[stream_idx]->time_base;
  81. st->time_base.num = time_base->num;
  82. st->time_base.den = time_base->den;
  83. } else {
  84. lavfi->sink_stream_subcc_map[sink_idx] = -1;
  85. }
  86. }
  87. return 0;
  88. }
  89. av_cold static int lavfi_read_header(AVFormatContext *avctx)
  90. {
  91. LavfiContext *lavfi = avctx->priv_data;
  92. AVFilterInOut *input_links = NULL, *output_links = NULL, *inout;
  93. const AVFilter *buffersink, *abuffersink;
  94. enum AVMediaType type;
  95. int ret = 0, i, n;
  96. #define FAIL(ERR) { ret = ERR; goto end; }
  97. buffersink = avfilter_get_by_name("buffersink");
  98. abuffersink = avfilter_get_by_name("abuffersink");
  99. if (lavfi->graph_filename && lavfi->graph_str) {
  100. av_log(avctx, AV_LOG_ERROR,
  101. "Only one of the graph or graph_file options must be specified\n");
  102. FAIL(AVERROR(EINVAL));
  103. }
  104. if (lavfi->graph_filename) {
  105. AVBPrint graph_file_pb;
  106. AVIOContext *avio = NULL;
  107. AVDictionary *options = NULL;
  108. if (avctx->protocol_whitelist && (ret = av_dict_set(&options, "protocol_whitelist", avctx->protocol_whitelist, 0)) < 0)
  109. goto end;
  110. ret = avio_open2(&avio, lavfi->graph_filename, AVIO_FLAG_READ, &avctx->interrupt_callback, &options);
  111. av_dict_free(&options);
  112. if (ret < 0)
  113. goto end;
  114. av_bprint_init(&graph_file_pb, 0, AV_BPRINT_SIZE_UNLIMITED);
  115. ret = avio_read_to_bprint(avio, &graph_file_pb, INT_MAX);
  116. avio_closep(&avio);
  117. if (ret) {
  118. av_bprint_finalize(&graph_file_pb, NULL);
  119. goto end;
  120. }
  121. if ((ret = av_bprint_finalize(&graph_file_pb, &lavfi->graph_str)))
  122. goto end;
  123. }
  124. if (!lavfi->graph_str)
  125. lavfi->graph_str = av_strdup(avctx->url);
  126. /* parse the graph, create a stream for each open output */
  127. if (!(lavfi->graph = avfilter_graph_alloc()))
  128. FAIL(AVERROR(ENOMEM));
  129. if ((ret = avfilter_graph_parse_ptr(lavfi->graph, lavfi->graph_str,
  130. &input_links, &output_links, avctx)) < 0)
  131. goto end;
  132. if (input_links) {
  133. av_log(avctx, AV_LOG_ERROR,
  134. "Open inputs in the filtergraph are not acceptable\n");
  135. FAIL(AVERROR(EINVAL));
  136. }
  137. /* count the outputs */
  138. for (n = 0, inout = output_links; inout; n++, inout = inout->next);
  139. lavfi->nb_sinks = n;
  140. if (!(lavfi->sink_stream_map = av_malloc(sizeof(int) * n)))
  141. FAIL(AVERROR(ENOMEM));
  142. if (!(lavfi->sink_eof = av_mallocz(sizeof(int) * n)))
  143. FAIL(AVERROR(ENOMEM));
  144. if (!(lavfi->stream_sink_map = av_malloc(sizeof(int) * n)))
  145. FAIL(AVERROR(ENOMEM));
  146. if (!(lavfi->sink_stream_subcc_map = av_malloc(sizeof(int) * n)))
  147. FAIL(AVERROR(ENOMEM));
  148. for (i = 0; i < n; i++)
  149. lavfi->stream_sink_map[i] = -1;
  150. /* parse the output link names - they need to be of the form out0, out1, ...
  151. * create a mapping between them and the streams */
  152. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  153. int stream_idx = 0, suffix = 0, use_subcc = 0;
  154. sscanf(inout->name, "out%n%d%n", &suffix, &stream_idx, &suffix);
  155. if (!suffix) {
  156. av_log(avctx, AV_LOG_ERROR,
  157. "Invalid outpad name '%s'\n", inout->name);
  158. FAIL(AVERROR(EINVAL));
  159. }
  160. if (inout->name[suffix]) {
  161. if (!strcmp(inout->name + suffix, "+subcc")) {
  162. use_subcc = 1;
  163. } else {
  164. av_log(avctx, AV_LOG_ERROR,
  165. "Invalid outpad suffix '%s'\n", inout->name);
  166. FAIL(AVERROR(EINVAL));
  167. }
  168. }
  169. if ((unsigned)stream_idx >= n) {
  170. av_log(avctx, AV_LOG_ERROR,
  171. "Invalid index was specified in output '%s', "
  172. "must be a non-negative value < %d\n",
  173. inout->name, n);
  174. FAIL(AVERROR(EINVAL));
  175. }
  176. if (lavfi->stream_sink_map[stream_idx] != -1) {
  177. av_log(avctx, AV_LOG_ERROR,
  178. "An output with stream index %d was already specified\n",
  179. stream_idx);
  180. FAIL(AVERROR(EINVAL));
  181. }
  182. lavfi->sink_stream_map[i] = stream_idx;
  183. lavfi->stream_sink_map[stream_idx] = i;
  184. lavfi->sink_stream_subcc_map[i] = !!use_subcc;
  185. }
  186. /* for each open output create a corresponding stream */
  187. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  188. AVStream *st;
  189. if (!(st = avformat_new_stream(avctx, NULL)))
  190. FAIL(AVERROR(ENOMEM));
  191. st->id = i;
  192. }
  193. /* create a sink for each output and connect them to the graph */
  194. lavfi->sinks = av_malloc_array(lavfi->nb_sinks, sizeof(AVFilterContext *));
  195. if (!lavfi->sinks)
  196. FAIL(AVERROR(ENOMEM));
  197. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  198. AVFilterContext *sink;
  199. type = avfilter_pad_get_type(inout->filter_ctx->output_pads, inout->pad_idx);
  200. if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
  201. type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
  202. av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
  203. FAIL(AVERROR_FILTER_NOT_FOUND);
  204. }
  205. if (type == AVMEDIA_TYPE_VIDEO) {
  206. ret = avfilter_graph_create_filter(&sink, buffersink,
  207. inout->name, NULL,
  208. NULL, lavfi->graph);
  209. if (ret < 0)
  210. goto end;
  211. } else if (type == AVMEDIA_TYPE_AUDIO) {
  212. static const enum AVSampleFormat sample_fmts[] = {
  213. AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32,
  214. AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_DBL,
  215. };
  216. ret = avfilter_graph_create_filter(&sink, abuffersink,
  217. inout->name, NULL,
  218. NULL, lavfi->graph);
  219. if (ret >= 0)
  220. ret = av_opt_set_bin(sink, "sample_fmts", (const uint8_t*)sample_fmts,
  221. sizeof(sample_fmts), AV_OPT_SEARCH_CHILDREN);
  222. if (ret < 0)
  223. goto end;
  224. ret = av_opt_set_int(sink, "all_channel_counts", 1,
  225. AV_OPT_SEARCH_CHILDREN);
  226. if (ret < 0)
  227. goto end;
  228. } else {
  229. av_log(avctx, AV_LOG_ERROR,
  230. "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
  231. FAIL(AVERROR(EINVAL));
  232. }
  233. lavfi->sinks[i] = sink;
  234. if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)
  235. goto end;
  236. }
  237. /* configure the graph */
  238. if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)
  239. goto end;
  240. if (lavfi->dump_graph) {
  241. char *dump = avfilter_graph_dump(lavfi->graph, lavfi->dump_graph);
  242. if (dump != NULL) {
  243. fputs(dump, stderr);
  244. fflush(stderr);
  245. av_free(dump);
  246. } else {
  247. FAIL(AVERROR(ENOMEM));
  248. }
  249. }
  250. /* fill each stream with the information in the corresponding sink */
  251. for (i = 0; i < lavfi->nb_sinks; i++) {
  252. AVFilterContext *sink = lavfi->sinks[lavfi->stream_sink_map[i]];
  253. AVRational time_base = av_buffersink_get_time_base(sink);
  254. AVRational frame_rate = av_buffersink_get_frame_rate(sink);
  255. AVStream *st = avctx->streams[i];
  256. AVCodecParameters *const par = st->codecpar;
  257. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  258. par->codec_type = av_buffersink_get_type(sink);
  259. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  260. par->codec_id = AV_CODEC_ID_WRAPPED_AVFRAME;
  261. par->format = av_buffersink_get_format(sink);
  262. par->width = av_buffersink_get_w(sink);
  263. par->height = av_buffersink_get_h(sink);
  264. avctx->probesize = FFMAX(avctx->probesize, sizeof(AVFrame) * 30);
  265. st ->sample_aspect_ratio =
  266. par->sample_aspect_ratio = av_buffersink_get_sample_aspect_ratio(sink);
  267. if (frame_rate.num > 0 && frame_rate.den > 0) {
  268. st->avg_frame_rate = frame_rate;
  269. st->r_frame_rate = frame_rate;
  270. }
  271. } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
  272. par->sample_rate = av_buffersink_get_sample_rate(sink);
  273. ret = av_buffersink_get_ch_layout(sink, &par->ch_layout);
  274. if (ret < 0)
  275. goto end;
  276. par->format = av_buffersink_get_format(sink);
  277. par->codec_id = av_get_pcm_codec(par->format, -1);
  278. if (par->codec_id == AV_CODEC_ID_NONE)
  279. av_log(avctx, AV_LOG_ERROR,
  280. "Could not find PCM codec for sample format %s.\n",
  281. av_get_sample_fmt_name(par->format));
  282. }
  283. }
  284. if ((ret = create_subcc_streams(avctx)) < 0)
  285. goto end;
  286. end:
  287. avfilter_inout_free(&input_links);
  288. avfilter_inout_free(&output_links);
  289. return ret;
  290. }
  291. static int create_subcc_packet(AVFormatContext *avctx, AVFrame *frame,
  292. int sink_idx)
  293. {
  294. LavfiContext *lavfi = avctx->priv_data;
  295. AVFrameSideData *sd;
  296. int stream_idx, ret;
  297. if ((stream_idx = lavfi->sink_stream_subcc_map[sink_idx]) < 0)
  298. return 0;
  299. if (!(sd = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)))
  300. return 0;
  301. if ((ret = av_new_packet(&lavfi->subcc_packet, sd->size)) < 0)
  302. return ret;
  303. memcpy(lavfi->subcc_packet.data, sd->data, sd->size);
  304. lavfi->subcc_packet.stream_index = stream_idx;
  305. lavfi->subcc_packet.pts = frame->pts;
  306. lavfi->subcc_packet.pos = frame->pkt_pos;
  307. return 0;
  308. }
  309. static void lavfi_free_frame(void *opaque, uint8_t *data)
  310. {
  311. AVFrame *frame = (AVFrame*)data;
  312. av_frame_free(&frame);
  313. }
  314. static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  315. {
  316. LavfiContext *lavfi = avctx->priv_data;
  317. double min_pts = DBL_MAX;
  318. int stream_idx, min_pts_sink_idx = 0;
  319. AVFrame *frame;
  320. AVDictionary *frame_metadata;
  321. int ret, i;
  322. AVStream *st;
  323. if (lavfi->subcc_packet.size) {
  324. av_packet_move_ref(pkt, &lavfi->subcc_packet);
  325. return pkt->size;
  326. }
  327. frame = av_frame_alloc();
  328. if (!frame)
  329. return AVERROR(ENOMEM);
  330. /* iterate through all the graph sinks. Select the sink with the
  331. * minimum PTS */
  332. for (i = 0; i < lavfi->nb_sinks; i++) {
  333. AVRational tb = av_buffersink_get_time_base(lavfi->sinks[i]);
  334. double d;
  335. if (lavfi->sink_eof[i])
  336. continue;
  337. ret = av_buffersink_get_frame_flags(lavfi->sinks[i], frame,
  338. AV_BUFFERSINK_FLAG_PEEK);
  339. if (ret == AVERROR_EOF) {
  340. ff_dlog(avctx, "EOF sink_idx:%d\n", i);
  341. lavfi->sink_eof[i] = 1;
  342. continue;
  343. } else if (ret < 0)
  344. goto fail;
  345. d = av_rescale_q_rnd(frame->pts, tb, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  346. ff_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
  347. av_frame_unref(frame);
  348. if (d < min_pts) {
  349. min_pts = d;
  350. min_pts_sink_idx = i;
  351. }
  352. }
  353. if (min_pts == DBL_MAX) {
  354. ret = AVERROR_EOF;
  355. goto fail;
  356. }
  357. ff_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
  358. av_buffersink_get_frame_flags(lavfi->sinks[min_pts_sink_idx], frame, 0);
  359. stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
  360. st = avctx->streams[stream_idx];
  361. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  362. pkt->buf = av_buffer_create((uint8_t*)frame, sizeof(*frame),
  363. &lavfi_free_frame, NULL, 0);
  364. if (!pkt->buf) {
  365. ret = AVERROR(ENOMEM);
  366. goto fail;
  367. }
  368. pkt->data = pkt->buf->data;
  369. pkt->size = pkt->buf->size;
  370. pkt->flags |= AV_PKT_FLAG_TRUSTED;
  371. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  372. int size = frame->nb_samples * av_get_bytes_per_sample(frame->format) *
  373. frame->ch_layout.nb_channels;
  374. if ((ret = av_new_packet(pkt, size)) < 0)
  375. goto fail;
  376. memcpy(pkt->data, frame->data[0], size);
  377. }
  378. frame_metadata = frame->metadata;
  379. if (frame_metadata) {
  380. size_t size;
  381. uint8_t *metadata = av_packet_pack_dictionary(frame_metadata, &size);
  382. if (!metadata) {
  383. ret = AVERROR(ENOMEM);
  384. goto fail;
  385. }
  386. if ((ret = av_packet_add_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
  387. metadata, size)) < 0) {
  388. av_freep(&metadata);
  389. goto fail;
  390. }
  391. }
  392. if ((ret = create_subcc_packet(avctx, frame, min_pts_sink_idx)) < 0) {
  393. goto fail;
  394. }
  395. pkt->stream_index = stream_idx;
  396. pkt->pts = frame->pts;
  397. pkt->pos = frame->pkt_pos;
  398. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
  399. av_frame_free(&frame);
  400. return pkt->size;
  401. fail:
  402. av_frame_free(&frame);
  403. return ret;
  404. }
  405. #define OFFSET(x) offsetof(LavfiContext, x)
  406. #define DEC AV_OPT_FLAG_DECODING_PARAM
  407. static const AVOption options[] = {
  408. { "graph", "set libavfilter graph", OFFSET(graph_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  409. { "graph_file","set libavfilter graph filename", OFFSET(graph_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
  410. { "dumpgraph", "dump graph to stderr", OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  411. { NULL },
  412. };
  413. static const AVClass lavfi_class = {
  414. .class_name = "lavfi indev",
  415. .item_name = av_default_item_name,
  416. .option = options,
  417. .version = LIBAVUTIL_VERSION_INT,
  418. .category = AV_CLASS_CATEGORY_DEVICE_INPUT,
  419. };
  420. const AVInputFormat ff_lavfi_demuxer = {
  421. .name = "lavfi",
  422. .long_name = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
  423. .priv_data_size = sizeof(LavfiContext),
  424. .read_header = lavfi_read_header,
  425. .read_packet = lavfi_read_packet,
  426. .read_close = lavfi_read_close,
  427. .flags = AVFMT_NOFILE,
  428. .priv_class = &lavfi_class,
  429. .flags_internal = FF_FMT_INIT_CLEANUP,
  430. };