3 * Copyright (c) 2012 Nicolas George
5 * This file is part of FFmpeg.
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.
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.
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
23 #include "libavutil/avutil.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/opt.h"
28 #include "avio_internal.h"
34 AVBitStreamFilterContext **bsfs; ///< bitstream filters per stream
36 /** map from input to output streams indexes,
37 * disabled output streams are set to -1 */
42 typedef struct TeeContext {
45 TeeSlave slaves[MAX_SLAVES];
48 static const char *const slave_delim = "|";
49 static const char *const slave_opt_open = "[";
50 static const char *const slave_opt_close = "]";
51 static const char *const slave_opt_delim = ":]"; /* must have the close too */
52 static const char *const slave_bsfs_spec_sep = "/";
53 static const char *const slave_select_sep = ",";
55 static const AVClass tee_muxer_class = {
56 .class_name = "Tee muxer",
57 .item_name = av_default_item_name,
58 .version = LIBAVUTIL_VERSION_INT,
61 static int parse_slave_options(void *log, char *slave,
62 AVDictionary **options, char **filename)
68 if (!strspn(slave, slave_opt_open)) {
73 if (strspn(p, slave_opt_close)) {
74 *filename = (char *)p + 1;
78 ret = av_opt_get_key_value(&p, "=", slave_opt_delim, 0, &key, &val);
80 av_log(log, AV_LOG_ERROR, "No option found near \"%s\"\n", p);
83 ret = av_dict_set(options, key, val,
84 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
87 if (strspn(p, slave_opt_close))
91 *filename = (char *)p + 1;
95 av_dict_free(options);
100 * Parse list of bitstream filters and add them to the list of filters
101 * pointed to by bsfs.
103 * The list must be specified in the form:
104 * BSFS ::= BSF[,BSFS]
106 static int parse_bsfs(void *log_ctx, const char *bsfs_spec,
107 AVBitStreamFilterContext **bsfs)
109 char *bsf_name, *buf, *dup, *saveptr;
112 if (!(dup = buf = av_strdup(bsfs_spec)))
113 return AVERROR(ENOMEM);
115 while (bsf_name = av_strtok(buf, ",", &saveptr)) {
116 AVBitStreamFilterContext *bsf = av_bitstream_filter_init(bsf_name);
119 av_log(log_ctx, AV_LOG_ERROR,
120 "Cannot initialize bitstream filter with name '%s', "
121 "unknown filter or internal error happened\n",
123 ret = AVERROR_UNKNOWN;
127 /* append bsf context to the list of bsf contexts */
139 static int close_slave(TeeSlave *tee_slave)
141 AVFormatContext *avf;
145 avf = tee_slave->avf;
149 if (tee_slave->header_written)
150 ret = av_write_trailer(avf);
152 if (tee_slave->bsfs) {
153 for (i = 0; i < avf->nb_streams; ++i) {
154 AVBitStreamFilterContext *bsf_next, *bsf = tee_slave->bsfs[i];
156 bsf_next = bsf->next;
157 av_bitstream_filter_close(bsf);
162 av_freep(&tee_slave->stream_map);
163 av_freep(&tee_slave->bsfs);
165 ff_format_io_close(avf, &avf->pb);
166 avformat_free_context(avf);
167 tee_slave->avf = NULL;
171 static void close_slaves(AVFormatContext *avf)
173 TeeContext *tee = avf->priv_data;
176 for (i = 0; i < tee->nb_slaves; i++) {
177 close_slave(&tee->slaves[i]);
181 static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
184 AVDictionary *options = NULL;
185 AVDictionaryEntry *entry;
187 char *format = NULL, *select = NULL;
188 AVFormatContext *avf2 = NULL;
192 char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
194 if ((ret = parse_slave_options(avf, slave, &options, &filename)) < 0)
197 #define STEAL_OPTION(option, field) do { \
198 if ((entry = av_dict_get(options, option, NULL, 0))) { \
199 field = entry->value; \
200 entry->value = NULL; /* prevent it from being freed */ \
201 av_dict_set(&options, option, NULL, 0); \
205 STEAL_OPTION("f", format);
206 STEAL_OPTION("select", select);
208 ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);
211 tee_slave->avf = avf2;
212 av_dict_copy(&avf2->metadata, avf->metadata, 0);
213 avf2->opaque = avf->opaque;
214 avf2->io_open = avf->io_open;
215 avf2->io_close = avf->io_close;
217 tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
218 if (!tee_slave->stream_map) {
219 ret = AVERROR(ENOMEM);
224 for (i = 0; i < avf->nb_streams; i++) {
225 st = avf->streams[i];
227 tmp_select = av_strdup(select); // av_strtok is destructive so we regenerate it in each loop
229 ret = AVERROR(ENOMEM);
233 first_subselect = tmp_select;
234 next_subselect = NULL;
235 while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
236 first_subselect = NULL;
238 ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
240 av_log(avf, AV_LOG_ERROR,
241 "Invalid stream specifier '%s' for output '%s'\n",
246 fullret = 1; // match
250 av_freep(&tmp_select);
252 if (fullret == 0) { /* no match */
253 tee_slave->stream_map[i] = -1;
257 tee_slave->stream_map[i] = stream_count++;
259 if (!(st2 = avformat_new_stream(avf2, NULL))) {
260 ret = AVERROR(ENOMEM);
264 st2->r_frame_rate = st->r_frame_rate;
265 st2->time_base = st->time_base;
266 st2->start_time = st->start_time;
267 st2->duration = st->duration;
268 st2->nb_frames = st->nb_frames;
269 st2->disposition = st->disposition;
270 st2->sample_aspect_ratio = st->sample_aspect_ratio;
271 st2->avg_frame_rate = st->avg_frame_rate;
272 av_dict_copy(&st2->metadata, st->metadata, 0);
273 if ((ret = avcodec_parameters_copy(st2->codecpar, st->codecpar)) < 0)
277 if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
278 if ((ret = avf2->io_open(avf2, &avf2->pb, filename, AVIO_FLAG_WRITE, NULL)) < 0) {
279 av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",
280 slave, av_err2str(ret));
285 if ((ret = avformat_write_header(avf2, &options)) < 0) {
286 av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
287 slave, av_err2str(ret));
290 tee_slave->header_written = 1;
292 tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(TeeSlave));
293 if (!tee_slave->bsfs) {
294 ret = AVERROR(ENOMEM);
299 while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
300 const char *spec = entry->key + strlen("bsfs");
302 if (strspn(spec, slave_bsfs_spec_sep) != 1) {
303 av_log(avf, AV_LOG_ERROR,
304 "Specifier separator in '%s' is '%c', but only characters '%s' "
305 "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
306 ret = AVERROR(EINVAL);
309 spec++; /* consume separator */
312 for (i = 0; i < avf2->nb_streams; i++) {
313 ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
315 av_log(avf, AV_LOG_ERROR,
316 "Invalid stream specifier '%s' in bsfs option '%s' for slave "
317 "output '%s'\n", spec, entry->key, filename);
322 av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
323 "output '%s'\n", spec, entry->value, i, filename);
324 if (tee_slave->bsfs[i]) {
325 av_log(avf, AV_LOG_WARNING,
326 "Duplicate bsfs specification associated to stream %d of slave "
327 "output '%s', filters will be ignored\n", i, filename);
330 ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
332 av_log(avf, AV_LOG_ERROR,
333 "Error parsing bitstream filter sequence '%s' associated to "
334 "stream %d of slave output '%s'\n", entry->value, i, filename);
340 av_dict_set(&options, entry->key, NULL, 0);
345 while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
346 av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
347 ret = AVERROR_OPTION_NOT_FOUND;
354 av_dict_free(&options);
355 av_freep(&tmp_select);
359 static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
362 av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
363 slave->avf->filename, slave->avf->oformat->name);
364 for (i = 0; i < slave->avf->nb_streams; i++) {
365 AVStream *st = slave->avf->streams[i];
366 AVBitStreamFilterContext *bsf = slave->bsfs[i];
368 av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
369 i, avcodec_get_name(st->codecpar->codec_id),
370 av_get_media_type_string(st->codecpar->codec_type));
372 av_log(log_ctx, log_level, " bsfs:");
374 av_log(log_ctx, log_level, "%s%s",
375 bsf->filter->name, bsf->next ? "," : "");
379 av_log(log_ctx, log_level, "\n");
383 static int tee_write_header(AVFormatContext *avf)
385 TeeContext *tee = avf->priv_data;
386 unsigned nb_slaves = 0, i;
387 const char *filename = avf->filename;
388 char *slaves[MAX_SLAVES];
392 if (nb_slaves == MAX_SLAVES) {
393 av_log(avf, AV_LOG_ERROR, "Maximum %d slave muxers reached.\n",
395 ret = AVERROR_PATCHWELCOME;
398 if (!(slaves[nb_slaves++] = av_get_token(&filename, slave_delim))) {
399 ret = AVERROR(ENOMEM);
402 if (strspn(filename, slave_delim))
406 tee->nb_slaves = nb_slaves;
408 for (i = 0; i < nb_slaves; i++) {
409 if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0)
411 log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
412 av_freep(&slaves[i]);
415 for (i = 0; i < avf->nb_streams; i++) {
417 for (j = 0; j < tee->nb_slaves; j++)
418 mapped += tee->slaves[j].stream_map[i] >= 0;
420 av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
421 "to any slave.\n", i);
426 for (i = 0; i < nb_slaves; i++)
427 av_freep(&slaves[i]);
432 static int tee_write_trailer(AVFormatContext *avf)
434 TeeContext *tee = avf->priv_data;
435 int ret_all = 0, ret;
438 for (i = 0; i < tee->nb_slaves; i++) {
439 if ((ret = close_slave(&tee->slaves[i])) < 0)
446 static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
448 TeeContext *tee = avf->priv_data;
449 AVFormatContext *avf2;
451 int ret_all = 0, ret;
456 for (i = 0; i < tee->nb_slaves; i++) {
457 avf2 = tee->slaves[i].avf;
458 s = pkt->stream_index;
459 s2 = tee->slaves[i].stream_map[s];
463 if ((ret = av_copy_packet(&pkt2, pkt)) < 0 ||
464 (ret = av_dup_packet(&pkt2))< 0)
469 tb = avf ->streams[s ]->time_base;
470 tb2 = avf2->streams[s2]->time_base;
471 pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
472 pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
473 pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
474 pkt2.stream_index = s2;
476 if ((ret = av_apply_bitstream_filters(avf2->streams[s2]->codec, &pkt2,
477 tee->slaves[i].bsfs[s2])) < 0 ||
478 (ret = av_interleaved_write_frame(avf2, &pkt2)) < 0)
485 AVOutputFormat ff_tee_muxer = {
487 .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
488 .priv_data_size = sizeof(TeeContext),
489 .write_header = tee_write_header,
490 .write_trailer = tee_write_trailer,
491 .write_packet = tee_write_packet,
492 .priv_class = &tee_muxer_class,
493 .flags = AVFMT_NOFILE,