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.

498 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, *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_close(avf2->pb);
  269. avf2->pb = NULL;
  270. avformat_free_context(avf2);
  271. tee->slaves[i].avf = NULL;
  272. }
  273. }
  274. static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
  275. {
  276. int i;
  277. av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
  278. slave->avf->filename, slave->avf->oformat->name);
  279. for (i = 0; i < slave->avf->nb_streams; i++) {
  280. AVStream *st = slave->avf->streams[i];
  281. AVBitStreamFilterContext *bsf = slave->bsfs[i];
  282. av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
  283. i, avcodec_get_name(st->codec->codec_id),
  284. av_get_media_type_string(st->codec->codec_type));
  285. if (bsf) {
  286. av_log(log_ctx, log_level, " bsfs:");
  287. while (bsf) {
  288. av_log(log_ctx, log_level, "%s%s",
  289. bsf->filter->name, bsf->next ? "," : "");
  290. bsf = bsf->next;
  291. }
  292. }
  293. av_log(log_ctx, log_level, "\n");
  294. }
  295. }
  296. static int tee_write_header(AVFormatContext *avf)
  297. {
  298. TeeContext *tee = avf->priv_data;
  299. unsigned nb_slaves = 0, i;
  300. const char *filename = avf->filename;
  301. char *slaves[MAX_SLAVES];
  302. int ret;
  303. while (*filename) {
  304. if (nb_slaves == MAX_SLAVES) {
  305. av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",
  306. MAX_SLAVES);
  307. ret = AVERROR_PATCHWELCOME;
  308. goto fail;
  309. }
  310. if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {
  311. ret = AVERROR(ENOMEM);
  312. goto fail;
  313. }
  314. if (strspn(filename, slave_delim))
  315. filename++;
  316. }
  317. for (i = 0; i < nb_slaves; i++) {
  318. if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)
  319. goto fail;
  320. log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
  321. av_freep(&slaves[i]);
  322. }
  323. tee->nb_slaves = nb_slaves;
  324. for (i = 0; i < avf->nb_streams; i++) {
  325. int j, mapped = 0;
  326. for (j = 0; j < tee->nb_slaves; j++)
  327. mapped += tee->slaves[j].stream_map[i] >= 0;
  328. if (!mapped)
  329. av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
  330. "to any slave.\n", i);
  331. }
  332. return 0;
  333. fail:
  334. for (i = 0; i < nb_slaves; i++)
  335. av_freep(&slaves[i]);
  336. close_slaves(avf);
  337. return ret;
  338. }
  339. static int filter_packet(void *log_ctx, AVPacket *pkt,
  340. AVFormatContext *fmt_ctx, AVBitStreamFilterContext *bsf_ctx)
  341. {
  342. AVCodecContext *enc_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  343. int ret = 0;
  344. while (bsf_ctx) {
  345. AVPacket new_pkt = *pkt;
  346. ret = av_bitstream_filter_filter(bsf_ctx, enc_ctx, NULL,
  347. &new_pkt.data, &new_pkt.size,
  348. pkt->data, pkt->size,
  349. pkt->flags & AV_PKT_FLAG_KEY);
  350. if (ret == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
  351. if ((ret = av_copy_packet(&new_pkt, pkt)) < 0)
  352. break;
  353. ret = 1;
  354. }
  355. if (ret > 0) {
  356. av_free_packet(pkt);
  357. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  358. av_buffer_default_free, NULL, 0);
  359. if (!new_pkt.buf)
  360. break;
  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. *pkt = new_pkt;
  369. bsf_ctx = bsf_ctx->next;
  370. }
  371. return ret;
  372. }
  373. static int tee_write_trailer(AVFormatContext *avf)
  374. {
  375. TeeContext *tee = avf->priv_data;
  376. AVFormatContext *avf2;
  377. int ret_all = 0, ret;
  378. unsigned i;
  379. for (i = 0; i < tee->nb_slaves; i++) {
  380. avf2 = tee->slaves[i].avf;
  381. if ((ret = av_write_trailer(avf2)) < 0)
  382. if (!ret_all)
  383. ret_all = ret;
  384. if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
  385. if ((ret = avio_close(avf2->pb)) < 0)
  386. if (!ret_all)
  387. ret_all = ret;
  388. avf2->pb = NULL;
  389. }
  390. }
  391. close_slaves(avf);
  392. return ret_all;
  393. }
  394. static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
  395. {
  396. TeeContext *tee = avf->priv_data;
  397. AVFormatContext *avf2;
  398. AVPacket pkt2;
  399. int ret_all = 0, ret;
  400. unsigned i, s;
  401. int s2;
  402. AVRational tb, tb2;
  403. for (i = 0; i < tee->nb_slaves; i++) {
  404. avf2 = tee->slaves[i].avf;
  405. s = pkt->stream_index;
  406. s2 = tee->slaves[i].stream_map[s];
  407. if (s2 < 0)
  408. continue;
  409. if ((ret = av_copy_packet(&pkt2, pkt)) < 0 ||
  410. (ret = av_dup_packet(&pkt2))< 0)
  411. if (!ret_all) {
  412. ret = ret_all;
  413. continue;
  414. }
  415. tb = avf ->streams[s ]->time_base;
  416. tb2 = avf2->streams[s2]->time_base;
  417. pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
  418. pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
  419. pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
  420. pkt2.stream_index = s2;
  421. filter_packet(avf2, &pkt2, avf2, tee->slaves[i].bsfs[s2]);
  422. if ((ret = av_interleaved_write_frame(avf2, &pkt2)) < 0)
  423. if (!ret_all)
  424. ret_all = ret;
  425. }
  426. return ret_all;
  427. }
  428. AVOutputFormat ff_tee_muxer = {
  429. .name = "tee",
  430. .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
  431. .priv_data_size = sizeof(TeeContext),
  432. .write_header = tee_write_header,
  433. .write_trailer = tee_write_trailer,
  434. .write_packet = tee_write_packet,
  435. .priv_class = &tee_muxer_class,
  436. .flags = AVFMT_NOFILE,
  437. };