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