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.

517 lines
16KB

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