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"
31 ON_SLAVE_FAILURE_ABORT = 1,
32 ON_SLAVE_FAILURE_IGNORE = 2
35 #define DEFAULT_SLAVE_FAILURE_POLICY ON_SLAVE_FAILURE_ABORT
39 AVBitStreamFilterContext **bsfs; ///< bitstream filters per stream
41 SlaveFailurePolicy on_fail;
43 /** map from input to output streams indexes,
44 * disabled output streams are set to -1 */
49 typedef struct TeeContext {
56 static const char *const slave_delim = "|";
57 static const char *const slave_opt_open = "[";
58 static const char *const slave_opt_close = "]";
59 static const char *const slave_opt_delim = ":]"; /* must have the close too */
60 static const char *const slave_bsfs_spec_sep = "/";
61 static const char *const slave_select_sep = ",";
63 static const AVClass tee_muxer_class = {
64 .class_name = "Tee muxer",
65 .item_name = av_default_item_name,
66 .version = LIBAVUTIL_VERSION_INT,
69 static int parse_slave_options(void *log, char *slave,
70 AVDictionary **options, char **filename)
76 if (!strspn(slave, slave_opt_open)) {
81 if (strspn(p, slave_opt_close)) {
82 *filename = (char *)p + 1;
86 ret = av_opt_get_key_value(&p, "=", slave_opt_delim, 0, &key, &val);
88 av_log(log, AV_LOG_ERROR, "No option found near \"%s\"\n", p);
91 ret = av_dict_set(options, key, val,
92 AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
95 if (strspn(p, slave_opt_close))
99 *filename = (char *)p + 1;
103 av_dict_free(options);
108 * Parse list of bitstream filters and add them to the list of filters
109 * pointed to by bsfs.
111 * The list must be specified in the form:
112 * BSFS ::= BSF[,BSFS]
114 static int parse_bsfs(void *log_ctx, const char *bsfs_spec,
115 AVBitStreamFilterContext **bsfs)
117 char *bsf_name, *buf, *dup, *saveptr;
120 if (!(dup = buf = av_strdup(bsfs_spec)))
121 return AVERROR(ENOMEM);
123 while (bsf_name = av_strtok(buf, ",", &saveptr)) {
124 AVBitStreamFilterContext *bsf = av_bitstream_filter_init(bsf_name);
127 av_log(log_ctx, AV_LOG_ERROR,
128 "Cannot initialize bitstream filter with name '%s', "
129 "unknown filter or internal error happened\n",
131 ret = AVERROR_UNKNOWN;
135 /* append bsf context to the list of bsf contexts */
147 static inline int parse_slave_failure_policy_option(const char *opt, TeeSlave *tee_slave)
150 tee_slave->on_fail = DEFAULT_SLAVE_FAILURE_POLICY;
152 } else if (!av_strcasecmp("abort", opt)) {
153 tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
155 } else if (!av_strcasecmp("ignore", opt)) {
156 tee_slave->on_fail = ON_SLAVE_FAILURE_IGNORE;
159 /* Set failure behaviour to abort, so invalid option error will not be ignored */
160 tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
161 return AVERROR(EINVAL);
164 static int close_slave(TeeSlave *tee_slave)
166 AVFormatContext *avf;
170 avf = tee_slave->avf;
174 if (tee_slave->header_written)
175 ret = av_write_trailer(avf);
177 if (tee_slave->bsfs) {
178 for (i = 0; i < avf->nb_streams; ++i) {
179 AVBitStreamFilterContext *bsf_next, *bsf = tee_slave->bsfs[i];
181 bsf_next = bsf->next;
182 av_bitstream_filter_close(bsf);
187 av_freep(&tee_slave->stream_map);
188 av_freep(&tee_slave->bsfs);
190 ff_format_io_close(avf, &avf->pb);
191 avformat_free_context(avf);
192 tee_slave->avf = NULL;
196 static void close_slaves(AVFormatContext *avf)
198 TeeContext *tee = avf->priv_data;
201 for (i = 0; i < tee->nb_slaves; i++) {
202 close_slave(&tee->slaves[i]);
204 av_freep(&tee->slaves);
207 static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
210 AVDictionary *options = NULL;
211 AVDictionaryEntry *entry;
213 char *format = NULL, *select = NULL, *on_fail = NULL;
214 AVFormatContext *avf2 = NULL;
218 char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
220 if ((ret = parse_slave_options(avf, slave, &options, &filename)) < 0)
223 #define STEAL_OPTION(option, field) do { \
224 if ((entry = av_dict_get(options, option, NULL, 0))) { \
225 field = entry->value; \
226 entry->value = NULL; /* prevent it from being freed */ \
227 av_dict_set(&options, option, NULL, 0); \
231 STEAL_OPTION("f", format);
232 STEAL_OPTION("select", select);
233 STEAL_OPTION("onfail", on_fail);
235 ret = parse_slave_failure_policy_option(on_fail, tee_slave);
237 av_log(avf, AV_LOG_ERROR,
238 "Invalid onfail option value, valid options are 'abort' and 'ignore'\n");
242 ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);
245 tee_slave->avf = avf2;
246 av_dict_copy(&avf2->metadata, avf->metadata, 0);
247 avf2->opaque = avf->opaque;
248 avf2->io_open = avf->io_open;
249 avf2->io_close = avf->io_close;
251 tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
252 if (!tee_slave->stream_map) {
253 ret = AVERROR(ENOMEM);
258 for (i = 0; i < avf->nb_streams; i++) {
259 st = avf->streams[i];
261 tmp_select = av_strdup(select); // av_strtok is destructive so we regenerate it in each loop
263 ret = AVERROR(ENOMEM);
267 first_subselect = tmp_select;
268 next_subselect = NULL;
269 while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
270 first_subselect = NULL;
272 ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
274 av_log(avf, AV_LOG_ERROR,
275 "Invalid stream specifier '%s' for output '%s'\n",
280 fullret = 1; // match
284 av_freep(&tmp_select);
286 if (fullret == 0) { /* no match */
287 tee_slave->stream_map[i] = -1;
291 tee_slave->stream_map[i] = stream_count++;
293 if (!(st2 = avformat_new_stream(avf2, NULL))) {
294 ret = AVERROR(ENOMEM);
298 st2->r_frame_rate = st->r_frame_rate;
299 st2->time_base = st->time_base;
300 st2->start_time = st->start_time;
301 st2->duration = st->duration;
302 st2->nb_frames = st->nb_frames;
303 st2->disposition = st->disposition;
304 st2->sample_aspect_ratio = st->sample_aspect_ratio;
305 st2->avg_frame_rate = st->avg_frame_rate;
306 av_dict_copy(&st2->metadata, st->metadata, 0);
307 if ((ret = avcodec_parameters_copy(st2->codecpar, st->codecpar)) < 0)
311 if (!(avf2->oformat->flags & AVFMT_NOFILE)) {
312 if ((ret = avf2->io_open(avf2, &avf2->pb, filename, AVIO_FLAG_WRITE, NULL)) < 0) {
313 av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n",
314 slave, av_err2str(ret));
319 if ((ret = avformat_write_header(avf2, &options)) < 0) {
320 av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
321 slave, av_err2str(ret));
324 tee_slave->header_written = 1;
326 tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
327 if (!tee_slave->bsfs) {
328 ret = AVERROR(ENOMEM);
333 while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
334 const char *spec = entry->key + strlen("bsfs");
336 if (strspn(spec, slave_bsfs_spec_sep) != 1) {
337 av_log(avf, AV_LOG_ERROR,
338 "Specifier separator in '%s' is '%c', but only characters '%s' "
339 "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
340 ret = AVERROR(EINVAL);
343 spec++; /* consume separator */
346 for (i = 0; i < avf2->nb_streams; i++) {
347 ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
349 av_log(avf, AV_LOG_ERROR,
350 "Invalid stream specifier '%s' in bsfs option '%s' for slave "
351 "output '%s'\n", spec, entry->key, filename);
356 av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
357 "output '%s'\n", spec, entry->value, i, filename);
358 if (tee_slave->bsfs[i]) {
359 av_log(avf, AV_LOG_WARNING,
360 "Duplicate bsfs specification associated to stream %d of slave "
361 "output '%s', filters will be ignored\n", i, filename);
364 ret = parse_bsfs(avf, entry->value, &tee_slave->bsfs[i]);
366 av_log(avf, AV_LOG_ERROR,
367 "Error parsing bitstream filter sequence '%s' associated to "
368 "stream %d of slave output '%s'\n", entry->value, i, filename);
374 av_dict_set(&options, entry->key, NULL, 0);
379 while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
380 av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
381 ret = AVERROR_OPTION_NOT_FOUND;
389 av_dict_free(&options);
390 av_freep(&tmp_select);
394 static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
397 av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
398 slave->avf->filename, slave->avf->oformat->name);
399 for (i = 0; i < slave->avf->nb_streams; i++) {
400 AVStream *st = slave->avf->streams[i];
401 AVBitStreamFilterContext *bsf = slave->bsfs[i];
403 av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
404 i, avcodec_get_name(st->codecpar->codec_id),
405 av_get_media_type_string(st->codecpar->codec_type));
407 av_log(log_ctx, log_level, " bsfs:");
409 av_log(log_ctx, log_level, "%s%s",
410 bsf->filter->name, bsf->next ? "," : "");
414 av_log(log_ctx, log_level, "\n");
418 static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
420 TeeContext *tee = avf->priv_data;
421 TeeSlave *tee_slave = &tee->slaves[slave_idx];
425 close_slave(tee_slave);
427 if (!tee->nb_alive) {
428 av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
430 } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
431 av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
434 av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
435 slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
440 static int tee_write_header(AVFormatContext *avf)
442 TeeContext *tee = avf->priv_data;
443 unsigned nb_slaves = 0, i;
444 const char *filename = avf->filename;
445 char **slaves = NULL;
449 char *slave = av_get_token(&filename, slave_delim);
451 ret = AVERROR(ENOMEM);
454 ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
459 if (strspn(filename, slave_delim))
463 if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
464 ret = AVERROR(ENOMEM);
467 tee->nb_slaves = tee->nb_alive = nb_slaves;
469 for (i = 0; i < nb_slaves; i++) {
470 if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
471 ret = tee_process_slave_failure(avf, i, ret);
475 log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
477 av_freep(&slaves[i]);
480 for (i = 0; i < avf->nb_streams; i++) {
482 for (j = 0; j < tee->nb_slaves; j++)
483 if (tee->slaves[j].avf)
484 mapped += tee->slaves[j].stream_map[i] >= 0;
486 av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
487 "to any slave.\n", i);
493 for (i = 0; i < nb_slaves; i++)
494 av_freep(&slaves[i]);
500 static int tee_write_trailer(AVFormatContext *avf)
502 TeeContext *tee = avf->priv_data;
503 int ret_all = 0, ret;
506 for (i = 0; i < tee->nb_slaves; i++) {
507 if ((ret = close_slave(&tee->slaves[i])) < 0) {
508 ret = tee_process_slave_failure(avf, i, ret);
509 if (!ret_all && ret < 0)
513 av_freep(&tee->slaves);
517 static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
519 TeeContext *tee = avf->priv_data;
520 AVFormatContext *avf2;
522 int ret_all = 0, ret;
527 for (i = 0; i < tee->nb_slaves; i++) {
528 if (!(avf2 = tee->slaves[i].avf))
531 s = pkt->stream_index;
532 s2 = tee->slaves[i].stream_map[s];
536 memset(&pkt2, 0, sizeof(AVPacket));
537 if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
542 tb = avf ->streams[s ]->time_base;
543 tb2 = avf2->streams[s2]->time_base;
544 pkt2.pts = av_rescale_q(pkt->pts, tb, tb2);
545 pkt2.dts = av_rescale_q(pkt->dts, tb, tb2);
546 pkt2.duration = av_rescale_q(pkt->duration, tb, tb2);
547 pkt2.stream_index = s2;
549 if ((ret = av_apply_bitstream_filters(avf2->streams[s2]->codec, &pkt2,
550 tee->slaves[i].bsfs[s2])) < 0 ||
551 (ret = av_interleaved_write_frame(avf2, &pkt2)) < 0) {
552 ret = tee_process_slave_failure(avf, i, ret);
553 if (!ret_all && ret < 0)
560 AVOutputFormat ff_tee_muxer = {
562 .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
563 .priv_data_size = sizeof(TeeContext),
564 .write_header = tee_write_header,
565 .write_trailer = tee_write_trailer,
566 .write_packet = tee_write_packet,
567 .priv_class = &tee_muxer_class,
568 .flags = AVFMT_NOFILE,