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.

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