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"
29 #include "tee_common.h"
32 ON_SLAVE_FAILURE_ABORT = 1,
33 ON_SLAVE_FAILURE_IGNORE = 2
36 #define DEFAULT_SLAVE_FAILURE_POLICY ON_SLAVE_FAILURE_ABORT
40 AVBSFContext **bsfs; ///< bitstream filters per stream
42 SlaveFailurePolicy on_fail;
44 AVDictionary *fifo_options;
46 /** map from input to output streams indexes,
47 * disabled output streams are set to -1 */
52 typedef struct TeeContext {
58 AVDictionary *fifo_options;
59 char *fifo_options_str;
62 static const char *const slave_delim = "|";
63 static const char *const slave_bsfs_spec_sep = "/";
64 static const char *const slave_select_sep = ",";
66 #define OFFSET(x) offsetof(TeeContext, x)
67 static const AVOption options[] = {
68 {"use_fifo", "Use fifo pseudo-muxer to separate actual muxers from encoder",
69 OFFSET(use_fifo), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
70 {"fifo_options", "fifo pseudo-muxer options", OFFSET(fifo_options_str),
71 AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM},
75 static const AVClass tee_muxer_class = {
76 .class_name = "Tee muxer",
77 .item_name = av_default_item_name,
79 .version = LIBAVUTIL_VERSION_INT,
82 static inline int parse_slave_failure_policy_option(const char *opt, TeeSlave *tee_slave)
85 tee_slave->on_fail = DEFAULT_SLAVE_FAILURE_POLICY;
87 } else if (!av_strcasecmp("abort", opt)) {
88 tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
90 } else if (!av_strcasecmp("ignore", opt)) {
91 tee_slave->on_fail = ON_SLAVE_FAILURE_IGNORE;
94 /* Set failure behaviour to abort, so invalid option error will not be ignored */
95 tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
96 return AVERROR(EINVAL);
99 static int parse_slave_fifo_options(const char *use_fifo,
100 const char *fifo_options, TeeSlave *tee_slave)
105 /*TODO - change this to use proper function for parsing boolean
106 * options when there is one */
107 if (av_match_name(use_fifo, "true,y,yes,enable,enabled,on,1")) {
108 tee_slave->use_fifo = 1;
109 } else if (av_match_name(use_fifo, "false,n,no,disable,disabled,off,0")) {
110 tee_slave->use_fifo = 0;
112 return AVERROR(EINVAL);
117 ret = av_dict_parse_string(&tee_slave->fifo_options, fifo_options, "=", ":", 0);
122 static int close_slave(TeeSlave *tee_slave)
124 AVFormatContext *avf;
128 avf = tee_slave->avf;
132 if (tee_slave->header_written)
133 ret = av_write_trailer(avf);
135 if (tee_slave->bsfs) {
136 for (i = 0; i < avf->nb_streams; ++i)
137 av_bsf_free(&tee_slave->bsfs[i]);
139 av_freep(&tee_slave->stream_map);
140 av_freep(&tee_slave->bsfs);
142 ff_format_io_close(avf, &avf->pb);
143 avformat_free_context(avf);
144 tee_slave->avf = NULL;
148 static void close_slaves(AVFormatContext *avf)
150 TeeContext *tee = avf->priv_data;
153 for (i = 0; i < tee->nb_slaves; i++) {
154 close_slave(&tee->slaves[i]);
156 av_freep(&tee->slaves);
159 static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
162 AVDictionary *options = NULL;
163 AVDictionaryEntry *entry;
165 char *format = NULL, *select = NULL, *on_fail = NULL;
166 char *use_fifo = NULL, *fifo_options_str = NULL;
167 AVFormatContext *avf2 = NULL;
171 char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
173 if ((ret = ff_tee_parse_slave_options(avf, slave, &options, &filename)) < 0)
176 #define STEAL_OPTION(option, field) do { \
177 if ((entry = av_dict_get(options, option, NULL, 0))) { \
178 field = entry->value; \
179 entry->value = NULL; /* prevent it from being freed */ \
180 av_dict_set(&options, option, NULL, 0); \
184 STEAL_OPTION("f", format);
185 STEAL_OPTION("select", select);
186 STEAL_OPTION("onfail", on_fail);
187 STEAL_OPTION("use_fifo", use_fifo);
188 STEAL_OPTION("fifo_options", fifo_options_str);
190 ret = parse_slave_failure_policy_option(on_fail, tee_slave);
192 av_log(avf, AV_LOG_ERROR,
193 "Invalid onfail option value, valid options are 'abort' and 'ignore'\n");
197 ret = parse_slave_fifo_options(use_fifo, fifo_options_str, tee_slave);
199 av_log(avf, AV_LOG_ERROR, "Error parsing fifo options: %s\n", av_err2str(ret));
203 if (tee_slave->use_fifo) {
206 char *format_options_str = NULL;
207 ret = av_dict_get_string(options, &format_options_str, '=', ':');
211 ret = av_dict_set(&tee_slave->fifo_options, "format_opts", format_options_str,
212 AV_DICT_DONT_STRDUP_VAL);
218 ret = av_dict_set(&tee_slave->fifo_options, "fifo_format", format,
219 AV_DICT_DONT_STRDUP_VAL);
225 av_dict_free(&options);
226 options = tee_slave->fifo_options;
228 ret = avformat_alloc_output_context2(&avf2, NULL,
229 tee_slave->use_fifo ? "fifo" :format, filename);
232 tee_slave->avf = avf2;
233 av_dict_copy(&avf2->metadata, avf->metadata, 0);
234 avf2->opaque = avf->opaque;
235 avf2->io_open = avf->io_open;
236 avf2->io_close = avf->io_close;
237 avf2->interrupt_callback = avf->interrupt_callback;
238 avf2->flags = avf->flags;
240 tee_slave->stream_map = av_calloc(avf->nb_streams, sizeof(*tee_slave->stream_map));
241 if (!tee_slave->stream_map) {
242 ret = AVERROR(ENOMEM);
247 for (i = 0; i < avf->nb_streams; i++) {
248 st = avf->streams[i];
250 tmp_select = av_strdup(select); // av_strtok is destructive so we regenerate it in each loop
252 ret = AVERROR(ENOMEM);
256 first_subselect = tmp_select;
257 next_subselect = NULL;
258 while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
259 first_subselect = NULL;
261 ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
263 av_log(avf, AV_LOG_ERROR,
264 "Invalid stream specifier '%s' for output '%s'\n",
269 fullret = 1; // match
273 av_freep(&tmp_select);
275 if (fullret == 0) { /* no match */
276 tee_slave->stream_map[i] = -1;
280 tee_slave->stream_map[i] = stream_count++;
282 if (!(st2 = avformat_new_stream(avf2, NULL))) {
283 ret = AVERROR(ENOMEM);
287 ret = ff_stream_encode_params_copy(st2, st);
292 ret = ff_format_output_open(avf2, filename, NULL);
294 av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n", slave,
299 if ((ret = avformat_write_header(avf2, &options)) < 0) {
300 av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
301 slave, av_err2str(ret));
304 tee_slave->header_written = 1;
306 tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
307 if (!tee_slave->bsfs) {
308 ret = AVERROR(ENOMEM);
313 while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
314 const char *spec = entry->key + strlen("bsfs");
316 if (strspn(spec, slave_bsfs_spec_sep) != 1) {
317 av_log(avf, AV_LOG_ERROR,
318 "Specifier separator in '%s' is '%c', but only characters '%s' "
319 "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
320 ret = AVERROR(EINVAL);
323 spec++; /* consume separator */
326 for (i = 0; i < avf2->nb_streams; i++) {
327 ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
329 av_log(avf, AV_LOG_ERROR,
330 "Invalid stream specifier '%s' in bsfs option '%s' for slave "
331 "output '%s'\n", spec, entry->key, filename);
336 av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
337 "output '%s'\n", spec, entry->value, i, filename);
338 if (tee_slave->bsfs[i]) {
339 av_log(avf, AV_LOG_WARNING,
340 "Duplicate bsfs specification associated to stream %d of slave "
341 "output '%s', filters will be ignored\n", i, filename);
344 ret = av_bsf_list_parse_str(entry->value, &tee_slave->bsfs[i]);
346 av_log(avf, AV_LOG_ERROR,
347 "Error parsing bitstream filter sequence '%s' associated to "
348 "stream %d of slave output '%s'\n", entry->value, i, filename);
354 av_dict_set(&options, entry->key, NULL, 0);
357 for (i = 0; i < avf->nb_streams; i++){
358 int target_stream = tee_slave->stream_map[i];
359 if (target_stream < 0)
362 if (!tee_slave->bsfs[target_stream]) {
363 /* Add pass-through bitstream filter */
364 ret = av_bsf_get_null_filter(&tee_slave->bsfs[target_stream]);
366 av_log(avf, AV_LOG_ERROR,
367 "Failed to create pass-through bitstream filter: %s\n",
373 tee_slave->bsfs[target_stream]->time_base_in = avf->streams[i]->time_base;
374 ret = avcodec_parameters_copy(tee_slave->bsfs[target_stream]->par_in,
375 avf->streams[i]->codecpar);
379 ret = av_bsf_init(tee_slave->bsfs[target_stream]);
381 av_log(avf, AV_LOG_ERROR,
382 "Failed to initialize bitstream filter(s): %s\n",
390 while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
391 av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
392 ret = AVERROR_OPTION_NOT_FOUND;
400 av_dict_free(&options);
401 av_freep(&tmp_select);
405 static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
408 av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
409 slave->avf->filename, slave->avf->oformat->name);
410 for (i = 0; i < slave->avf->nb_streams; i++) {
411 AVStream *st = slave->avf->streams[i];
412 AVBSFContext *bsf = slave->bsfs[i];
413 const char *bsf_name;
415 av_log(log_ctx, log_level, " stream:%d codec:%s type:%s",
416 i, avcodec_get_name(st->codecpar->codec_id),
417 av_get_media_type_string(st->codecpar->codec_type));
419 bsf_name = bsf->filter->priv_class ?
420 bsf->filter->priv_class->item_name(bsf) : bsf->filter->name;
421 av_log(log_ctx, log_level, " bsfs: %s\n", bsf_name);
425 static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
427 TeeContext *tee = avf->priv_data;
428 TeeSlave *tee_slave = &tee->slaves[slave_idx];
432 close_slave(tee_slave);
434 if (!tee->nb_alive) {
435 av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
437 } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
438 av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
441 av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
442 slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
447 static int tee_write_header(AVFormatContext *avf)
449 TeeContext *tee = avf->priv_data;
450 unsigned nb_slaves = 0, i;
451 const char *filename = avf->filename;
452 char **slaves = NULL;
456 char *slave = av_get_token(&filename, slave_delim);
458 ret = AVERROR(ENOMEM);
461 ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
466 if (strspn(filename, slave_delim))
470 if (tee->fifo_options_str) {
471 ret = av_dict_parse_string(&tee->fifo_options, tee->fifo_options_str, "=", ":", 0);
476 if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
477 ret = AVERROR(ENOMEM);
480 tee->nb_slaves = tee->nb_alive = nb_slaves;
482 for (i = 0; i < nb_slaves; i++) {
484 tee->slaves[i].use_fifo = tee->use_fifo;
485 ret = av_dict_copy(&tee->slaves[i].fifo_options, tee->fifo_options, 0);
489 if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
490 ret = tee_process_slave_failure(avf, i, ret);
494 log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
496 av_freep(&slaves[i]);
499 for (i = 0; i < avf->nb_streams; i++) {
501 for (j = 0; j < tee->nb_slaves; j++)
502 if (tee->slaves[j].avf)
503 mapped += tee->slaves[j].stream_map[i] >= 0;
505 av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
506 "to any slave.\n", i);
512 for (i = 0; i < nb_slaves; i++)
513 av_freep(&slaves[i]);
519 static int tee_write_trailer(AVFormatContext *avf)
521 TeeContext *tee = avf->priv_data;
522 int ret_all = 0, ret;
525 for (i = 0; i < tee->nb_slaves; i++) {
526 if ((ret = close_slave(&tee->slaves[i])) < 0) {
527 ret = tee_process_slave_failure(avf, i, ret);
528 if (!ret_all && ret < 0)
532 av_freep(&tee->slaves);
536 static int tee_write_packet(AVFormatContext *avf, AVPacket *pkt)
538 TeeContext *tee = avf->priv_data;
539 AVFormatContext *avf2;
542 int ret_all = 0, ret;
546 for (i = 0; i < tee->nb_slaves; i++) {
547 if (!(avf2 = tee->slaves[i].avf))
550 /* Flush slave if pkt is NULL*/
552 ret = av_interleaved_write_frame(avf2, NULL);
554 ret = tee_process_slave_failure(avf, i, ret);
555 if (!ret_all && ret < 0)
561 s = pkt->stream_index;
562 s2 = tee->slaves[i].stream_map[s];
566 memset(&pkt2, 0, sizeof(AVPacket));
567 if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
572 bsfs = tee->slaves[i].bsfs[s2];
573 pkt2.stream_index = s2;
575 ret = av_bsf_send_packet(bsfs, &pkt2);
577 av_log(avf, AV_LOG_ERROR, "Error while sending packet to bitstream filter: %s\n",
579 ret = tee_process_slave_failure(avf, i, ret);
580 if (!ret_all && ret < 0)
585 ret = av_bsf_receive_packet(bsfs, &pkt2);
586 if (ret == AVERROR(EAGAIN)) {
589 } else if (ret < 0) {
593 av_packet_rescale_ts(&pkt2, bsfs->time_base_out,
594 avf2->streams[s2]->time_base);
595 ret = av_interleaved_write_frame(avf2, &pkt2);
601 ret = tee_process_slave_failure(avf, i, ret);
602 if (!ret_all && ret < 0)
609 AVOutputFormat ff_tee_muxer = {
611 .long_name = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
612 .priv_data_size = sizeof(TeeContext),
613 .write_header = tee_write_header,
614 .write_trailer = tee_write_trailer,
615 .write_packet = tee_write_packet,
616 .priv_class = &tee_muxer_class,
617 .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,