You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

516 lines
18KB

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