lavfi.c 18 KB

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