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.

497 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. 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_dict_free(&options);
  248. return ret;
  249. }
  250. static void close_slaves(AVFormatContext *avf)
  251. {
  252. TeeContext *tee = avf->priv_data;
  253. AVFormatContext *avf2;
  254. unsigned i, j;
  255. for (i = 0; i < tee->nb_slaves; i++) {
  256. avf2 = tee->slaves[i].avf;
  257. for (j = 0; j < avf2->nb_streams; j++) {
  258. AVBitStreamFilterContext *bsf_next, *bsf = tee->slaves[i].bsfs[j];
  259. while (bsf) {
  260. bsf_next = bsf->next;
  261. av_bitstream_filter_close(bsf);
  262. bsf = bsf_next;
  263. }
  264. }
  265. av_freep(&tee->slaves[i].stream_map);
  266. avio_close(avf2->pb);
  267. avf2->pb = NULL;
  268. avformat_free_context(avf2);
  269. tee->slaves[i].avf = NULL;
  270. }
  271. }
  272. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  273. {
  274. int i;
  275. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  276. slave->avf->filename, slave->avf->oformat->name);
  277. for (i = 0; i < slave->avf->nb_streams; i++) {
  278. AVStream *st = slave->avf->streams[i];
  279. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  280. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  281. i, avcodec_get_name(st->codec->codec_id),
  282. av_get_media_type_string(st->codec->codec_type));
  283. if (bsf) {
  284. av_log(log_ctx, log_level, " bsfs:");
  285. while (bsf) {
  286. av_log(log_ctx, log_level, "%s%s",
  287. bsf->filter->name, bsf->next ? "," : "");
  288. bsf = bsf->next;
  289. }
  290. }
  291. av_log(log_ctx, log_level, "\n");
  292. }
  293. }
  294. static int tee_write_header(AVFormatContext *avf)
  295. {
  296. TeeContext *tee = avf->priv_data;
  297. unsigned nb_slaves = 0, i;
  298. const char *filename = avf->filename;
  299. char *slaves[MAX_SLAVES];
  300. int ret;
  301. while (*filename) {
  302. if (nb_slaves == MAX_SLAVES) {
  303. av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",
  304. MAX_SLAVES);
  305. ret = AVERROR_PATCHWELCOME;
  306. goto fail;
  307. }
  308. if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {
  309. ret = AVERROR(ENOMEM);
  310. goto fail;
  311. }
  312. if (strspn(filename, slave_delim))
  313. filename++;
  314. }
  315. for (i = 0; i < nb_slaves; i++) {
  316. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)
  317. goto fail;
  318. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  319. av_freep(&slaves[i]);
  320. }
  321. tee->nb_slaves = nb_slaves;
  322. for (i = 0; i < avf->nb_streams; i++) {
  323. int j, mapped = 0;
  324. for (j = 0; j < tee->nb_slaves; j++)
  325. mapped += tee->slaves[j].stream_map[i] >= 0;
  326. if (!mapped)
  327. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  328. "to any slave.\n", i);
  329. }
  330. return 0;
  331. fail:
  332. for (i = 0; i < nb_slaves; i++)
  333. av_freep(&slaves[i]);
  334. close_slaves(avf);
  335. return ret;
  336. }
  337. static int filter_packet(void *log_ctx, AVPacket *pkt,
  338. AVFormatContext *fmt_ctx, AVBitStreamFilterContext *bsf_ctx)
  339. {
  340. AVCodecContext *enc_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  341. int ret = 0;
  342. while (bsf_ctx) {
  343. AVPacket new_pkt = *pkt;
  344. ret = av_bitstream_filter_filter(bsf_ctx, enc_ctx, NULL,
  345. &new_pkt.data, &new_pkt.size,
  346. pkt->data, pkt->size,
  347. pkt->flags & AV_PKT_FLAG_KEY);
  348. if (ret == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
  349. if ((ret = av_copy_packet(&new_pkt, pkt)) < 0)
  350. break;
  351. ret = 1;
  352. }
  353. if (ret > 0) {
  354. av_free_packet(pkt);
  355. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  356. av_buffer_default_free, NULL, 0);
  357. if (!new_pkt.buf)
  358. break;
  359. }
  360. *pkt = new_pkt;
  361. bsf_ctx = bsf_ctx->next;
  362. }
  363. if (ret < 0) {
  364. av_log(log_ctx, AV_LOG_ERROR,
  365. "Failed to filter bitstream with filter %s for stream %d in file '%s' with codec %s\n",
  366. bsf_ctx->filter->name, pkt->stream_index, fmt_ctx->filename,
  367. avcodec_get_name(enc_ctx->codec_id));
  368. }
  369. return ret;
  370. }
  371. static int tee_write_trailer(AVFormatContext *avf)
  372. {
  373. TeeContext *tee = avf->priv_data;
  374. AVFormatContext *avf2;
  375. int ret_all = 0, ret;
  376. unsigned i;
  377. for (i = 0; i < tee->nb_slaves; i++) {
  378. avf2 = tee->slaves[i].avf;
  379. if ((ret = av_write_trailer(avf2)) < 0)
  380. if (!ret_all)
  381. ret_all = ret;
  382. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  383. if ((ret = avio_close(avf2->pb)) < 0)
  384. if (!ret_all)
  385. ret_all = ret;
  386. avf2->pb = NULL;
  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 = ret_all;
  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. };