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.

451 lines
14KB

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