tee.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * Tee pseudo-muxer
  3. * Copyright (c) 2012 Nicolas George
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public License
  9. * as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with FFmpeg; if not, write to the Free Software * Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avutil.h"
  22. #include "libavutil/avstring.h"
  23. #include "libavutil/opt.h"
  24. #include "avformat.h"
  25. #define MAX_SLAVES 16
  26. typedef struct {
  27. AVFormatContext *avf;
  28. AVBitStreamFilterContext **bsfs; ///< bitstream filters per stream
  29. /** map from input to output streams indexes,
  30. * disabled output streams are set to -1 */
  31. int *stream_map;
  32. } TeeSlave;
  33. typedef struct TeeContext {
  34. const AVClass *class;
  35. unsigned nb_slaves;
  36. TeeSlave slaves[MAX_SLAVES];
  37. } TeeContext;
  38. static const char *const slave_delim = "|";
  39. static const char *const slave_opt_open = "[";
  40. static const char *const slave_opt_close = "]";
  41. static const char *const slave_opt_delim = ":]"; /* must have the close too */
  42. static const char *const slave_bsfs_spec_sep = "/";
  43. static const AVClass tee_muxer_class = {
  44. .class_name = "Tee muxer",
  45. .item_name = av_default_item_name,
  46. .version = LIBAVUTIL_VERSION_INT,
  47. };
  48. static int parse_slave_options(void *log, char *slave,
  49. AVDictionary **options, char **filename)
  50. {
  51. const char *p;
  52. char *key, *val;
  53. int ret;
  54. if (!strspn(slave, slave_opt_open)) {
  55. *filename = slave;
  56. return 0;
  57. }
  58. p = slave + 1;
  59. if (strspn(p, slave_opt_close)) {
  60. *filename = (char *)p + 1;
  61. return 0;
  62. }
  63. while (1) {
  64. ret = av_opt_get_key_value(&p, "=", slave_opt_delim, 0, &key, &val);
  65. if (ret < 0) {
  66. av_log(log, AV_LOG_ERROR, "No option found near \"%s\"\n", p);
  67. goto fail;
  68. }
  69. ret = av_dict_set(options, key, val,
  70. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  71. if (ret < 0)
  72. goto fail;
  73. if (strspn(p, slave_opt_close))
  74. break;
  75. p++;
  76. }
  77. *filename = (char *)p + 1;
  78. return 0;
  79. fail:
  80. av_dict_free(options);
  81. return ret;
  82. }
  83. /**
  84. * Parse list of bitstream filters and add them to the list of filters
  85. * pointed to by bsfs.
  86. *
  87. * The list must be specified in the form:
  88. * BSFS ::= BSF[,BSFS]
  89. */
  90. static int parse_bsfs(void *log_ctx, const char *bsfs_spec,
  91. AVBitStreamFilterContext **bsfs)
  92. {
  93. char *bsf_name, *buf, *dup, *saveptr;
  94. int ret = 0;
  95. if (!(dup = buf = av_strdup(bsfs_spec)))
  96. return AVERROR(ENOMEM);
  97. while (bsf_name = av_strtok(buf, ",", &saveptr)) {
  98. AVBitStreamFilterContext *bsf = av_bitstream_filter_init(bsf_name);
  99. if (!bsf) {
  100. av_log(log_ctx, AV_LOG_ERROR,
  101. "Cannot initialize bitstream filter with name '%s', "
  102. "unknown filter or internal error happened\n",
  103. bsf_name);
  104. ret = AVERROR_UNKNOWN;
  105. goto end;
  106. }
  107. /* append bsf context to the list of bsf contexts */
  108. *bsfs = bsf;
  109. bsfs = &bsf->next;
  110. buf = NULL;
  111. }
  112. end:
  113. av_free(dup);
  114. return ret;
  115. }
  116. static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
  117. {
  118. int i, ret;
  119. AVDictionary *options = NULL;
  120. AVDictionaryEntry *entry;
  121. char *filename;
  122. char *format = NULL, *select = NULL;
  123. AVFormatContext *avf2 = NULL;
  124. AVStream *st, *st2;
  125. int stream_count;
  126. if ((ret = parse_slave_options(avf, slave, &options, &filename)) < 0)
  127. return ret;
  128. #define STEAL_OPTION(option, field) do { \
  129. if ((entry = av_dict_get(options, option, NULL, 0))) { \
  130. field = entry->value; \
  131. entry->value = NULL; /* prevent it from being freed */ \
  132. av_dict_set(&options, option, NULL, 0); \
  133. } \
  134. } while (0)
  135. STEAL_OPTION("f", format);
  136. STEAL_OPTION("select", select);
  137. ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);
  138. if (ret < 0)
  139. goto end;
  140. av_dict_copy(&avf2->metadata, avf->metadata, 0);
  141. tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
  142. if (!tee_slave->stream_map) {
  143. ret = AVERROR(ENOMEM);
  144. goto end;
  145. }
  146. stream_count = 0;
  147. for (i = 0; i < avf->nb_streams; i++) {
  148. st = avf->streams[i];
  149. if (select) {
  150. ret = avformat_match_stream_specifier(avf, avf->streams[i], select);
  151. if (ret < 0) {
  152. av_log(avf, AV_LOG_ERROR,
  153. "Invalid stream specifier '%s' for output '%s'\n",
  154. select, slave);
  155. goto end;
  156. }
  157. if (ret == 0) { /* no match */
  158. tee_slave->stream_map[i] = -1;
  159. continue;
  160. }
  161. }
  162. tee_slave->stream_map[i] = stream_count++;
  163. if (!(st2 = avformat_new_stream(avf2, NULL))) {
  164. ret = AVERROR(ENOMEM);
  165. goto end;
  166. }
  167. st2->id = st->id;
  168. st2->r_frame_rate = st->r_frame_rate;
  169. st2->time_base = st->time_base;
  170. st2->start_time = st->start_time;
  171. st2->duration = st->duration;
  172. st2->nb_frames = st->nb_frames;
  173. st2->disposition = st->disposition;
  174. st2->sample_aspect_ratio = st->sample_aspect_ratio;
  175. st2->avg_frame_rate = st->avg_frame_rate;
  176. av_dict_copy(&st2->metadata, st->metadata, 0);
  177. if ((ret = avcodec_copy_context(st2->codec, st->codec)) < 0)
  178. goto end;
  179. }
  180. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  181. if ((ret = avio_open(&avf2->pb, filename, AVIO_FLAG_WRITE)) < 0) {
  182. av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",
  183. slave, av_err2str(ret));
  184. goto end;
  185. }
  186. }
  187. if ((ret = avformat_write_header(avf2, &options)) < 0) {
  188. av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
  189. slave, av_err2str(ret));
  190. goto end;
  191. }
  192. tee_slave->avf = avf2;
  193. tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(TeeSlave));
  194. if (!tee_slave->bsfs) {
  195. ret = AVERROR(ENOMEM);
  196. goto end;
  197. }
  198. entry = NULL;
  199. while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
  200. const char *spec = entry->key + strlen("bsfs");
  201. if (*spec) {
  202. if (strspn(spec, slave_bsfs_spec_sep) != 1) {
  203. av_log(avf, AV_LOG_ERROR,
  204. "Specifier separator in '%s' is '%c', but only characters '%s' "
  205. "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
  206. return AVERROR(EINVAL);
  207. }
  208. spec++; /* consume separator */
  209. }
  210. for (i = 0; i < avf2->nb_streams; i++) {
  211. ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
  212. if (ret < 0) {
  213. av_log(avf, AV_LOG_ERROR,
  214. "Invalid stream specifier '%s' in bsfs option '%s' for slave "
  215. "output '%s'\n", spec, entry->key, filename);
  216. goto end;
  217. }
  218. if (ret > 0) {
  219. av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
  220. "output '%s'\n", spec, entry->value, i, filename);
  221. if (tee_slave->bsfs[i]) {
  222. av_log(avf, AV_LOG_WARNING,
  223. "Duplicate bsfs specification associated to stream %d of slave "
  224. "output '%s', filters will be ignored\n", i, filename);
  225. continue;
  226. }
  227. ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
  228. if (ret < 0) {
  229. av_log(avf, AV_LOG_ERROR,
  230. "Error parsing bitstream filter sequence '%s' associated to "
  231. "stream %d of slave output '%s'\n", entry->value, i, filename);
  232. goto end;
  233. }
  234. }
  235. }
  236. av_dict_set(&options, entry->key, NULL, 0);
  237. }
  238. if (options) {
  239. entry = NULL;
  240. while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
  241. av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
  242. ret = AVERROR_OPTION_NOT_FOUND;
  243. goto end;
  244. }
  245. end:
  246. av_free(format);
  247. av_free(select);
  248. av_dict_free(&options);
  249. return ret;
  250. }
  251. static void close_slaves(AVFormatContext *avf)
  252. {
  253. TeeContext *tee = avf->priv_data;
  254. AVFormatContext *avf2;
  255. unsigned i, j;
  256. for (i = 0; i < tee->nb_slaves; i++) {
  257. avf2 = tee->slaves[i].avf;
  258. for (j = 0; j < avf2->nb_streams; j++) {
  259. AVBitStreamFilterContext *bsf_next, *bsf = tee->slaves[i].bsfs[j];
  260. while (bsf) {
  261. bsf_next = bsf->next;
  262. av_bitstream_filter_close(bsf);
  263. bsf = bsf_next;
  264. }
  265. }
  266. av_freep(&tee->slaves[i].stream_map);
  267. av_freep(&tee->slaves[i].bsfs);
  268. avio_closep(&avf2->pb);
  269. avformat_free_context(avf2);
  270. tee->slaves[i].avf = NULL;
  271. }
  272. }
  273. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  274. {
  275. int i;
  276. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  277. slave->avf->filename, slave->avf->oformat->name);
  278. for (i = 0; i < slave->avf->nb_streams; i++) {
  279. AVStream *st = slave->avf->streams[i];
  280. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  281. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  282. i, avcodec_get_name(st->codec->codec_id),
  283. av_get_media_type_string(st->codec->codec_type));
  284. if (bsf) {
  285. av_log(log_ctx, log_level, " bsfs:");
  286. while (bsf) {
  287. av_log(log_ctx, log_level, "%s%s",
  288. bsf->filter->name, bsf->next ? "," : "");
  289. bsf = bsf->next;
  290. }
  291. }
  292. av_log(log_ctx, log_level, "\n");
  293. }
  294. }
  295. static int tee_write_header(AVFormatContext *avf)
  296. {
  297. TeeContext *tee = avf->priv_data;
  298. unsigned nb_slaves = 0, i;
  299. const char *filename = avf->filename;
  300. char *slaves[MAX_SLAVES];
  301. int ret;
  302. while (*filename) {
  303. if (nb_slaves == MAX_SLAVES) {
  304. av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",
  305. MAX_SLAVES);
  306. ret = AVERROR_PATCHWELCOME;
  307. goto fail;
  308. }
  309. if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {
  310. ret = AVERROR(ENOMEM);
  311. goto fail;
  312. }
  313. if (strspn(filename, slave_delim))
  314. filename++;
  315. }
  316. for (i = 0; i < nb_slaves; i++) {
  317. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)
  318. goto fail;
  319. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  320. av_freep(&slaves[i]);
  321. }
  322. tee->nb_slaves = nb_slaves;
  323. for (i = 0; i < avf->nb_streams; i++) {
  324. int j, mapped = 0;
  325. for (j = 0; j < tee->nb_slaves; j++)
  326. mapped += tee->slaves[j].stream_map[i] >= 0;
  327. if (!mapped)
  328. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  329. "to any slave.\n", i);
  330. }
  331. return 0;
  332. fail:
  333. for (i = 0; i < nb_slaves; i++)
  334. av_freep(&slaves[i]);
  335. close_slaves(avf);
  336. return ret;
  337. }
  338. static int filter_packet(void *log_ctx, AVPacket *pkt,
  339. AVFormatContext *fmt_ctx, AVBitStreamFilterContext *bsf_ctx)
  340. {
  341. AVCodecContext *enc_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  342. int ret = 0;
  343. while (bsf_ctx) {
  344. AVPacket new_pkt = *pkt;
  345. ret = av_bitstream_filter_filter(bsf_ctx, enc_ctx, NULL,
  346. &new_pkt.data, &new_pkt.size,
  347. pkt->data, pkt->size,
  348. pkt->flags & AV_PKT_FLAG_KEY);
  349. if (ret == 0 && new_pkt.data != pkt->data) {
  350. if ((ret = av_copy_packet(&new_pkt, pkt)) < 0)
  351. break;
  352. ret = 1;
  353. }
  354. if (ret > 0) {
  355. av_free_packet(pkt);
  356. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  357. av_buffer_default_free, NULL, 0);
  358. if (!new_pkt.buf)
  359. break;
  360. }
  361. if (ret < 0) {
  362. av_log(log_ctx, AV_LOG_ERROR,
  363. "Failed to filter bitstream with filter %s for stream %d in file '%s' with codec %s\n",
  364. bsf_ctx->filter->name, pkt->stream_index, fmt_ctx->filename,
  365. avcodec_get_name(enc_ctx->codec_id));
  366. }
  367. *pkt = new_pkt;
  368. bsf_ctx = bsf_ctx->next;
  369. }
  370. return ret;
  371. }
  372. static int tee_write_trailer(AVFormatContext *avf)
  373. {
  374. TeeContext *tee = avf->priv_data;
  375. AVFormatContext *avf2;
  376. int ret_all = 0, ret;
  377. unsigned i;
  378. for (i = 0; i < tee->nb_slaves; i++) {
  379. avf2 = tee->slaves[i].avf;
  380. if ((ret = av_write_trailer(avf2)) < 0)
  381. if (!ret_all)
  382. ret_all = ret;
  383. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  384. if ((ret = avio_closep(&avf2->pb)) < 0)
  385. if (!ret_all)
  386. ret_all = ret;
  387. }
  388. }
  389. close_slaves(avf);
  390. return ret_all;
  391. }
  392. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  393. {
  394. TeeContext *tee = avf->priv_data;
  395. AVFormatContext *avf2;
  396. AVPacket pkt2;
  397. int ret_all = 0, ret;
  398. unsigned i, s;
  399. int s2;
  400. AVRational tb, tb2;
  401. for (i = 0; i < tee->nb_slaves; i++) {
  402. avf2 = tee->slaves[i].avf;
  403. s = pkt->stream_index;
  404. s2 = tee->slaves[i].stream_map[s];
  405. if (s2 < 0)
  406. continue;
  407. if ((ret = av_copy_packet(&pkt2, pkt)) < 0 ||
  408. (ret = av_dup_packet(&pkt2))< 0)
  409. if (!ret_all) {
  410. ret_all = ret;
  411. continue;
  412. }
  413. tb = avf ->streams[s ]->time_base;
  414. tb2 = avf2->streams[s2]->time_base;
  415. pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
  416. pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
  417. pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
  418. pkt2.stream_index = s2;
  419. filter_packet(avf2, &pkt2, avf2, tee->slaves[i].bsfs[s2]);
  420. if ((ret = av_interleaved_write_frame(avf2, &pkt2)) < 0)
  421. if (!ret_all)
  422. ret_all = ret;
  423. }
  424. return ret_all;
  425. }
  426. AVOutputFormat ff_tee_muxer = {
  427. .name = "tee",
  428. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  429. .priv_data_size = sizeof(TeeContext),
  430. .write_header = tee_write_header,
  431. .write_trailer = tee_write_trailer,
  432. .write_packet = tee_write_packet,
  433. .priv_class = &tee_muxer_class,
  434. .flags = AVFMT_NOFILE,
  435. };