lavfi.c 18 KB

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