lavfi.c 17 KB

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