lavfi.c 18 KB

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