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.

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