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