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.

496 lines
15KB

  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, *saveptr;
  94. int ret = 0;
  95. if (!(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(buf);
  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. tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
  141. if (!tee_slave->stream_map) {
  142. ret = AVERROR(ENOMEM);
  143. goto end;
  144. }
  145. stream_count = 0;
  146. for (i = 0; i < avf->nb_streams; i++) {
  147. st = avf->streams[i];
  148. if (select) {
  149. ret = avformat_match_stream_specifier(avf, avf->streams[i], select);
  150. if (ret < 0) {
  151. av_log(avf, AV_LOG_ERROR,
  152. "Invalid stream specifier '%s' for output '%s'\n",
  153. select, slave);
  154. goto end;
  155. }
  156. if (ret == 0) { /* no match */
  157. tee_slave->stream_map[i] = -1;
  158. continue;
  159. }
  160. }
  161. tee_slave->stream_map[i] = stream_count++;
  162. if (!(st2 = avformat_new_stream(avf2, NULL))) {
  163. ret = AVERROR(ENOMEM);
  164. goto end;
  165. }
  166. st2->id = st->id;
  167. st2->r_frame_rate = st->r_frame_rate;
  168. st2->time_base = st->time_base;
  169. st2->start_time = st->start_time;
  170. st2->duration = st->duration;
  171. st2->nb_frames = st->nb_frames;
  172. st2->disposition = st->disposition;
  173. st2->sample_aspect_ratio = st->sample_aspect_ratio;
  174. st2->avg_frame_rate = st->avg_frame_rate;
  175. av_dict_copy(&st2->metadata, st->metadata, 0);
  176. if ((ret = avcodec_copy_context(st2->codec, st->codec)) < 0)
  177. goto end;
  178. }
  179. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  180. if ((ret = avio_open(&avf2->pb, filename, AVIO_FLAG_WRITE)) < 0) {
  181. av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",
  182. slave, av_err2str(ret));
  183. goto end;
  184. }
  185. }
  186. if ((ret = avformat_write_header(avf2, &options)) < 0) {
  187. av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
  188. slave, av_err2str(ret));
  189. goto end;
  190. }
  191. tee_slave->avf = avf2;
  192. tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(TeeSlave));
  193. if (!tee_slave->bsfs) {
  194. ret = AVERROR(ENOMEM);
  195. goto end;
  196. }
  197. entry = NULL;
  198. while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
  199. const char *spec = entry->key + strlen("bsfs");
  200. if (*spec) {
  201. if (strspn(spec, slave_bsfs_spec_sep) != 1) {
  202. av_log(avf, AV_LOG_ERROR,
  203. "Specifier separator in '%s' is '%c', but only characters '%s' "
  204. "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
  205. return AVERROR(EINVAL);
  206. }
  207. spec++; /* consume separator */
  208. }
  209. for (i = 0; i < avf2->nb_streams; i++) {
  210. ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
  211. if (ret < 0) {
  212. av_log(avf, AV_LOG_ERROR,
  213. "Invalid stream specifier '%s' in bsfs option '%s' for slave "
  214. "output '%s'\n", spec, entry->key, filename);
  215. goto end;
  216. }
  217. if (ret > 0) {
  218. av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
  219. "output '%s'\n", spec, entry->value, i, filename);
  220. if (tee_slave->bsfs[i]) {
  221. av_log(avf, AV_LOG_WARNING,
  222. "Duplicate bsfs specification associated to stream %d of slave "
  223. "output '%s', filters will be ignored\n", i, filename);
  224. continue;
  225. }
  226. ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
  227. if (ret < 0) {
  228. av_log(avf, AV_LOG_ERROR,
  229. "Error parsing bitstream filter sequence '%s' associated to "
  230. "stream %d of slave output '%s'\n", entry->value, i, filename);
  231. goto end;
  232. }
  233. }
  234. }
  235. av_dict_set(&options, entry->key, NULL, 0);
  236. }
  237. if (options) {
  238. entry = NULL;
  239. while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
  240. av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
  241. ret = AVERROR_OPTION_NOT_FOUND;
  242. goto end;
  243. }
  244. end:
  245. av_free(format);
  246. av_dict_free(&options);
  247. return ret;
  248. }
  249. static void close_slaves(AVFormatContext *avf)
  250. {
  251. TeeContext *tee = avf->priv_data;
  252. AVFormatContext *avf2;
  253. unsigned i, j;
  254. for (i = 0; i < tee->nb_slaves; i++) {
  255. avf2 = tee->slaves[i].avf;
  256. for (j = 0; j < avf2->nb_streams; j++) {
  257. AVBitStreamFilterContext *bsf_next, *bsf = tee->slaves[i].bsfs[j];
  258. while (bsf) {
  259. bsf_next = bsf->next;
  260. av_bitstream_filter_close(bsf);
  261. bsf = bsf_next;
  262. }
  263. }
  264. av_freep(&tee->slaves[i].stream_map);
  265. avio_close(avf2->pb);
  266. avf2->pb = NULL;
  267. avformat_free_context(avf2);
  268. tee->slaves[i].avf = NULL;
  269. }
  270. }
  271. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  272. {
  273. int i;
  274. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  275. slave->avf->filename, slave->avf->oformat->name);
  276. for (i = 0; i < slave->avf->nb_streams; i++) {
  277. AVStream *st = slave->avf->streams[i];
  278. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  279. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  280. i, avcodec_get_name(st->codec->codec_id),
  281. av_get_media_type_string(st->codec->codec_type));
  282. if (bsf) {
  283. av_log(log_ctx, log_level, " bsfs:");
  284. while (bsf) {
  285. av_log(log_ctx, log_level, "%s%s",
  286. bsf->filter->name, bsf->next ? "," : "");
  287. bsf = bsf->next;
  288. }
  289. }
  290. av_log(log_ctx, log_level, "\n");
  291. }
  292. }
  293. static int tee_write_header(AVFormatContext *avf)
  294. {
  295. TeeContext *tee = avf->priv_data;
  296. unsigned nb_slaves = 0, i;
  297. const char *filename = avf->filename;
  298. char *slaves[MAX_SLAVES];
  299. int ret;
  300. while (*filename) {
  301. if (nb_slaves == MAX_SLAVES) {
  302. av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",
  303. MAX_SLAVES);
  304. ret = AVERROR_PATCHWELCOME;
  305. goto fail;
  306. }
  307. if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {
  308. ret = AVERROR(ENOMEM);
  309. goto fail;
  310. }
  311. if (strspn(filename, slave_delim))
  312. filename++;
  313. }
  314. for (i = 0; i < nb_slaves; i++) {
  315. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)
  316. goto fail;
  317. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  318. av_freep(&slaves[i]);
  319. }
  320. tee->nb_slaves = nb_slaves;
  321. for (i = 0; i < avf->nb_streams; i++) {
  322. int j, mapped = 0;
  323. for (j = 0; j < tee->nb_slaves; j++)
  324. mapped += tee->slaves[j].stream_map[i] >= 0;
  325. if (!mapped)
  326. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  327. "to any slave.\n", i);
  328. }
  329. return 0;
  330. fail:
  331. for (i = 0; i < nb_slaves; i++)
  332. av_freep(&slaves[i]);
  333. close_slaves(avf);
  334. return ret;
  335. }
  336. static int filter_packet(void *log_ctx, AVPacket *pkt,
  337. AVFormatContext *fmt_ctx, AVBitStreamFilterContext *bsf_ctx)
  338. {
  339. AVCodecContext *enc_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  340. int ret;
  341. while (bsf_ctx) {
  342. AVPacket new_pkt = *pkt;
  343. ret = av_bitstream_filter_filter(bsf_ctx, enc_ctx, NULL,
  344. &new_pkt.data, &new_pkt.size,
  345. pkt->data, pkt->size,
  346. pkt->flags & AV_PKT_FLAG_KEY);
  347. if (ret == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
  348. if ((ret = av_copy_packet(&new_pkt, pkt)) < 0)
  349. break;
  350. ret = 1;
  351. }
  352. if (ret > 0) {
  353. av_free_packet(pkt);
  354. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  355. av_buffer_default_free, NULL, 0);
  356. if (!new_pkt.buf)
  357. break;
  358. }
  359. *pkt = new_pkt;
  360. bsf_ctx = bsf_ctx->next;
  361. }
  362. if (ret < 0) {
  363. av_log(log_ctx, AV_LOG_ERROR,
  364. "Failed to filter bitstream with filter %s for stream %d in file '%s' with codec %s\n",
  365. bsf_ctx->filter->name, pkt->stream_index, fmt_ctx->filename,
  366. avcodec_get_name(enc_ctx->codec_id));
  367. }
  368. return ret;
  369. }
  370. static int tee_write_trailer(AVFormatContext *avf)
  371. {
  372. TeeContext *tee = avf->priv_data;
  373. AVFormatContext *avf2;
  374. int ret_all = 0, ret;
  375. unsigned i;
  376. for (i = 0; i < tee->nb_slaves; i++) {
  377. avf2 = tee->slaves[i].avf;
  378. if ((ret = av_write_trailer(avf2)) < 0)
  379. if (!ret_all)
  380. ret_all = ret;
  381. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  382. if ((ret = avio_close(avf2->pb)) < 0)
  383. if (!ret_all)
  384. ret_all = ret;
  385. avf2->pb = NULL;
  386. }
  387. }
  388. close_slaves(avf);
  389. return ret_all;
  390. }
  391. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  392. {
  393. TeeContext *tee = avf->priv_data;
  394. AVFormatContext *avf2;
  395. AVPacket pkt2;
  396. int ret_all = 0, ret;
  397. unsigned i, s;
  398. int s2;
  399. AVRational tb, tb2;
  400. for (i = 0; i < tee->nb_slaves; i++) {
  401. avf2 = tee->slaves[i].avf;
  402. s = pkt->stream_index;
  403. s2 = tee->slaves[i].stream_map[s];
  404. if (s2 < 0)
  405. continue;
  406. if ((ret = av_copy_packet(&pkt2, pkt)) < 0 ||
  407. (ret = av_dup_packet(&pkt2))< 0)
  408. if (!ret_all) {
  409. ret = ret_all;
  410. continue;
  411. }
  412. tb = avf ->streams[s ]->time_base;
  413. tb2 = avf2->streams[s2]->time_base;
  414. pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
  415. pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
  416. pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
  417. pkt2.stream_index = s2;
  418. filter_packet(avf2, &pkt2, avf2, tee->slaves[i].bsfs[s2]);
  419. if ((ret = av_interleaved_write_frame(avf2, &pkt2)) < 0)
  420. if (!ret_all)
  421. ret_all = ret;
  422. }
  423. return ret_all;
  424. }
  425. AVOutputFormat ff_tee_muxer = {
  426. .name = "tee",
  427. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  428. .priv_data_size = sizeof(TeeContext),
  429. .write_header = tee_write_header,
  430. .write_trailer = tee_write_trailer,
  431. .write_packet = tee_write_packet,
  432. .priv_class = &tee_muxer_class,
  433. .flags = AVFMT_NOFILE,
  434. };