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