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