lavfi.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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/demux.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. if (!inout->name) {
  155. av_log(avctx, AV_LOG_ERROR, "Missing %d outpad name\n", i);
  156. FAIL(AVERROR(EINVAL));
  157. }
  158. sscanf(inout->name, "out%n%d%n", &suffix, &stream_idx, &suffix);
  159. if (!suffix) {
  160. av_log(avctx, AV_LOG_ERROR,
  161. "Invalid outpad name '%s'\n", inout->name);
  162. FAIL(AVERROR(EINVAL));
  163. }
  164. if (inout->name[suffix]) {
  165. if (!strcmp(inout->name + suffix, "+subcc")) {
  166. use_subcc = 1;
  167. } else {
  168. av_log(avctx, AV_LOG_ERROR,
  169. "Invalid outpad suffix '%s'\n", inout->name);
  170. FAIL(AVERROR(EINVAL));
  171. }
  172. }
  173. if ((unsigned)stream_idx >= n) {
  174. av_log(avctx, AV_LOG_ERROR,
  175. "Invalid index was specified in output '%s', "
  176. "must be a non-negative value < %d\n",
  177. inout->name, n);
  178. FAIL(AVERROR(EINVAL));
  179. }
  180. if (lavfi->stream_sink_map[stream_idx] != -1) {
  181. av_log(avctx, AV_LOG_ERROR,
  182. "An output with stream index %d was already specified\n",
  183. stream_idx);
  184. FAIL(AVERROR(EINVAL));
  185. }
  186. lavfi->sink_stream_map[i] = stream_idx;
  187. lavfi->stream_sink_map[stream_idx] = i;
  188. lavfi->sink_stream_subcc_map[i] = !!use_subcc;
  189. }
  190. /* for each open output create a corresponding stream */
  191. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  192. AVStream *st;
  193. if (!(st = avformat_new_stream(avctx, NULL)))
  194. FAIL(AVERROR(ENOMEM));
  195. st->id = i;
  196. }
  197. /* create a sink for each output and connect them to the graph */
  198. lavfi->sinks = av_malloc_array(lavfi->nb_sinks, sizeof(AVFilterContext *));
  199. if (!lavfi->sinks)
  200. FAIL(AVERROR(ENOMEM));
  201. for (i = 0, inout = output_links; inout; i++, inout = inout->next) {
  202. AVFilterContext *sink;
  203. type = avfilter_pad_get_type(inout->filter_ctx->output_pads, inout->pad_idx);
  204. if (type == AVMEDIA_TYPE_VIDEO && ! buffersink ||
  205. type == AVMEDIA_TYPE_AUDIO && ! abuffersink) {
  206. av_log(avctx, AV_LOG_ERROR, "Missing required buffersink filter, aborting.\n");
  207. FAIL(AVERROR_FILTER_NOT_FOUND);
  208. }
  209. if (type == AVMEDIA_TYPE_VIDEO) {
  210. ret = avfilter_graph_create_filter(&sink, buffersink,
  211. inout->name, NULL,
  212. NULL, lavfi->graph);
  213. if (ret < 0)
  214. goto end;
  215. } else if (type == AVMEDIA_TYPE_AUDIO) {
  216. static const enum AVSampleFormat sample_fmts[] = {
  217. AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32,
  218. AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_DBL,
  219. };
  220. ret = avfilter_graph_create_filter(&sink, abuffersink,
  221. inout->name, NULL,
  222. NULL, lavfi->graph);
  223. if (ret >= 0)
  224. ret = av_opt_set_bin(sink, "sample_fmts", (const uint8_t*)sample_fmts,
  225. sizeof(sample_fmts), AV_OPT_SEARCH_CHILDREN);
  226. if (ret < 0)
  227. goto end;
  228. ret = av_opt_set_int(sink, "all_channel_counts", 1,
  229. AV_OPT_SEARCH_CHILDREN);
  230. if (ret < 0)
  231. goto end;
  232. } else {
  233. av_log(avctx, AV_LOG_ERROR,
  234. "Output '%s' is not a video or audio output, not yet supported\n", inout->name);
  235. FAIL(AVERROR(EINVAL));
  236. }
  237. lavfi->sinks[i] = sink;
  238. if ((ret = avfilter_link(inout->filter_ctx, inout->pad_idx, sink, 0)) < 0)
  239. goto end;
  240. }
  241. /* configure the graph */
  242. if ((ret = avfilter_graph_config(lavfi->graph, avctx)) < 0)
  243. goto end;
  244. if (lavfi->dump_graph) {
  245. char *dump = avfilter_graph_dump(lavfi->graph, lavfi->dump_graph);
  246. if (dump != NULL) {
  247. fputs(dump, stderr);
  248. fflush(stderr);
  249. av_free(dump);
  250. } else {
  251. FAIL(AVERROR(ENOMEM));
  252. }
  253. }
  254. /* fill each stream with the information in the corresponding sink */
  255. for (i = 0; i < lavfi->nb_sinks; i++) {
  256. AVFilterContext *sink = lavfi->sinks[lavfi->stream_sink_map[i]];
  257. AVRational time_base = av_buffersink_get_time_base(sink);
  258. AVRational frame_rate = av_buffersink_get_frame_rate(sink);
  259. AVStream *st = avctx->streams[i];
  260. AVCodecParameters *const par = st->codecpar;
  261. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  262. par->codec_type = av_buffersink_get_type(sink);
  263. if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
  264. par->codec_id = AV_CODEC_ID_WRAPPED_AVFRAME;
  265. par->format = av_buffersink_get_format(sink);
  266. par->width = av_buffersink_get_w(sink);
  267. par->height = av_buffersink_get_h(sink);
  268. avctx->probesize = FFMAX(avctx->probesize, sizeof(AVFrame) * 30);
  269. st ->sample_aspect_ratio =
  270. par->sample_aspect_ratio = av_buffersink_get_sample_aspect_ratio(sink);
  271. if (frame_rate.num > 0 && frame_rate.den > 0) {
  272. st->avg_frame_rate = frame_rate;
  273. st->r_frame_rate = frame_rate;
  274. }
  275. } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
  276. par->sample_rate = av_buffersink_get_sample_rate(sink);
  277. ret = av_buffersink_get_ch_layout(sink, &par->ch_layout);
  278. if (ret < 0)
  279. goto end;
  280. par->format = av_buffersink_get_format(sink);
  281. par->codec_id = av_get_pcm_codec(par->format, -1);
  282. if (par->codec_id == AV_CODEC_ID_NONE)
  283. av_log(avctx, AV_LOG_ERROR,
  284. "Could not find PCM codec for sample format %s.\n",
  285. av_get_sample_fmt_name(par->format));
  286. }
  287. }
  288. if ((ret = create_subcc_streams(avctx)) < 0)
  289. goto end;
  290. end:
  291. avfilter_inout_free(&input_links);
  292. avfilter_inout_free(&output_links);
  293. return ret;
  294. }
  295. static int create_subcc_packet(AVFormatContext *avctx, AVFrame *frame,
  296. int sink_idx)
  297. {
  298. LavfiContext *lavfi = avctx->priv_data;
  299. AVFrameSideData *sd;
  300. int stream_idx, ret;
  301. if ((stream_idx = lavfi->sink_stream_subcc_map[sink_idx]) < 0)
  302. return 0;
  303. if (!(sd = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)))
  304. return 0;
  305. if ((ret = av_new_packet(&lavfi->subcc_packet, sd->size)) < 0)
  306. return ret;
  307. memcpy(lavfi->subcc_packet.data, sd->data, sd->size);
  308. lavfi->subcc_packet.stream_index = stream_idx;
  309. lavfi->subcc_packet.pts = frame->pts;
  310. #if FF_API_FRAME_PKT
  311. FF_DISABLE_DEPRECATION_WARNINGS
  312. lavfi->subcc_packet.pos = frame->pkt_pos;
  313. FF_ENABLE_DEPRECATION_WARNINGS
  314. #endif
  315. return 0;
  316. }
  317. static void lavfi_free_frame(void *opaque, uint8_t *data)
  318. {
  319. AVFrame *frame = (AVFrame*)data;
  320. av_frame_free(&frame);
  321. }
  322. static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  323. {
  324. LavfiContext *lavfi = avctx->priv_data;
  325. double min_pts = DBL_MAX;
  326. int stream_idx, min_pts_sink_idx = 0;
  327. AVFrame *frame, *frame_to_free;
  328. AVDictionary *frame_metadata;
  329. int ret, i;
  330. AVStream *st;
  331. if (lavfi->subcc_packet.size) {
  332. av_packet_move_ref(pkt, &lavfi->subcc_packet);
  333. return pkt->size;
  334. }
  335. frame = av_frame_alloc();
  336. if (!frame)
  337. return AVERROR(ENOMEM);
  338. frame_to_free = frame;
  339. /* iterate through all the graph sinks. Select the sink with the
  340. * minimum PTS */
  341. for (i = 0; i < lavfi->nb_sinks; i++) {
  342. AVRational tb = av_buffersink_get_time_base(lavfi->sinks[i]);
  343. double d;
  344. if (lavfi->sink_eof[i])
  345. continue;
  346. ret = av_buffersink_get_frame_flags(lavfi->sinks[i], frame,
  347. AV_BUFFERSINK_FLAG_PEEK);
  348. if (ret == AVERROR_EOF) {
  349. ff_dlog(avctx, "EOF sink_idx:%d\n", i);
  350. lavfi->sink_eof[i] = 1;
  351. continue;
  352. } else if (ret < 0)
  353. goto fail;
  354. d = av_rescale_q_rnd(frame->pts, tb, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  355. ff_dlog(avctx, "sink_idx:%d time:%f\n", i, d);
  356. av_frame_unref(frame);
  357. if (d < min_pts) {
  358. min_pts = d;
  359. min_pts_sink_idx = i;
  360. }
  361. }
  362. if (min_pts == DBL_MAX) {
  363. ret = AVERROR_EOF;
  364. goto fail;
  365. }
  366. ff_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);
  367. av_buffersink_get_frame_flags(lavfi->sinks[min_pts_sink_idx], frame, 0);
  368. stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];
  369. st = avctx->streams[stream_idx];
  370. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  371. pkt->buf = av_buffer_create((uint8_t*)frame, sizeof(*frame),
  372. &lavfi_free_frame, NULL, 0);
  373. if (!pkt->buf) {
  374. ret = AVERROR(ENOMEM);
  375. goto fail;
  376. }
  377. frame_to_free = NULL;
  378. pkt->data = pkt->buf->data;
  379. pkt->size = pkt->buf->size;
  380. pkt->flags |= AV_PKT_FLAG_TRUSTED;
  381. } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  382. int size = frame->nb_samples * av_get_bytes_per_sample(frame->format) *
  383. frame->ch_layout.nb_channels;
  384. if ((ret = av_new_packet(pkt, size)) < 0)
  385. goto fail;
  386. memcpy(pkt->data, frame->data[0], size);
  387. }
  388. frame_metadata = frame->metadata;
  389. if (frame_metadata) {
  390. size_t size;
  391. uint8_t *metadata = av_packet_pack_dictionary(frame_metadata, &size);
  392. if (!metadata) {
  393. ret = AVERROR(ENOMEM);
  394. goto fail;
  395. }
  396. if ((ret = av_packet_add_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,
  397. metadata, size)) < 0) {
  398. av_freep(&metadata);
  399. goto fail;
  400. }
  401. }
  402. if ((ret = create_subcc_packet(avctx, frame, min_pts_sink_idx)) < 0) {
  403. goto fail;
  404. }
  405. pkt->stream_index = stream_idx;
  406. pkt->pts = frame->pts;
  407. #if FF_API_FRAME_PKT
  408. FF_DISABLE_DEPRECATION_WARNINGS
  409. pkt->pos = frame->pkt_pos;
  410. FF_ENABLE_DEPRECATION_WARNINGS
  411. #endif
  412. av_frame_free(&frame_to_free);
  413. return pkt->size;
  414. fail:
  415. av_frame_free(&frame_to_free);
  416. return ret;
  417. }
  418. #define OFFSET(x) offsetof(LavfiContext, x)
  419. #define DEC AV_OPT_FLAG_DECODING_PARAM
  420. static const AVOption options[] = {
  421. { "graph", "set libavfilter graph", OFFSET(graph_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  422. { "graph_file","set libavfilter graph filename", OFFSET(graph_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
  423. { "dumpgraph", "dump graph to stderr", OFFSET(dump_graph), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  424. { NULL },
  425. };
  426. static const AVClass lavfi_class = {
  427. .class_name = "lavfi indev",
  428. .item_name = av_default_item_name,
  429. .option = options,
  430. .version = LIBAVUTIL_VERSION_INT,
  431. .category = AV_CLASS_CATEGORY_DEVICE_INPUT,
  432. };
  433. const FFInputFormat ff_lavfi_demuxer = {
  434. .p.name = "lavfi",
  435. .p.long_name = NULL_IF_CONFIG_SMALL("Libavfilter virtual input device"),
  436. .p.flags = AVFMT_NOFILE,
  437. .p.priv_class = &lavfi_class,
  438. .priv_data_size = sizeof(LavfiContext),
  439. .read_header = lavfi_read_header,
  440. .read_packet = lavfi_read_packet,
  441. .read_close = lavfi_read_close,
  442. .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
  443. };