]> git.sesse.net Git - ffmpeg/blob - libavformat/tee.c
avformat: add av_stream_get_codec_timebase()
[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 "internal.h"
27 #include "avformat.h"
28 #include "avio_internal.h"
29 #include "tee_common.h"
30
31 typedef enum {
32     ON_SLAVE_FAILURE_ABORT  = 1,
33     ON_SLAVE_FAILURE_IGNORE = 2
34 } SlaveFailurePolicy;
35
36 #define DEFAULT_SLAVE_FAILURE_POLICY ON_SLAVE_FAILURE_ABORT
37
38 typedef struct {
39     AVFormatContext *avf;
40     AVBSFContext **bsfs; ///< bitstream filters per stream
41
42     SlaveFailurePolicy on_fail;
43
44     /** map from input to output streams indexes,
45      * disabled output streams are set to -1 */
46     int *stream_map;
47     int header_written;
48 } TeeSlave;
49
50 typedef struct TeeContext {
51     const AVClass *class;
52     unsigned nb_slaves;
53     unsigned nb_alive;
54     TeeSlave *slaves;
55 } TeeContext;
56
57 static const char *const slave_delim     = "|";
58 static const char *const slave_bsfs_spec_sep = "/";
59 static const char *const slave_select_sep = ",";
60
61 static const AVClass tee_muxer_class = {
62     .class_name = "Tee muxer",
63     .item_name  = av_default_item_name,
64     .version    = LIBAVUTIL_VERSION_INT,
65 };
66
67 static inline int parse_slave_failure_policy_option(const char *opt, TeeSlave *tee_slave)
68 {
69     if (!opt) {
70         tee_slave->on_fail = DEFAULT_SLAVE_FAILURE_POLICY;
71         return 0;
72     } else if (!av_strcasecmp("abort", opt)) {
73         tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
74         return 0;
75     } else if (!av_strcasecmp("ignore", opt)) {
76         tee_slave->on_fail = ON_SLAVE_FAILURE_IGNORE;
77         return 0;
78     }
79     /* Set failure behaviour to abort, so invalid option error will not be ignored */
80     tee_slave->on_fail = ON_SLAVE_FAILURE_ABORT;
81     return AVERROR(EINVAL);
82 }
83
84 static int close_slave(TeeSlave *tee_slave)
85 {
86     AVFormatContext *avf;
87     unsigned i;
88     int ret = 0;
89
90     avf = tee_slave->avf;
91     if (!avf)
92         return 0;
93
94     if (tee_slave->header_written)
95         ret = av_write_trailer(avf);
96
97     if (tee_slave->bsfs) {
98         for (i = 0; i < avf->nb_streams; ++i)
99             av_bsf_free(&tee_slave->bsfs[i]);
100     }
101     av_freep(&tee_slave->stream_map);
102     av_freep(&tee_slave->bsfs);
103
104     ff_format_io_close(avf, &avf->pb);
105     avformat_free_context(avf);
106     tee_slave->avf = NULL;
107     return ret;
108 }
109
110 static void close_slaves(AVFormatContext *avf)
111 {
112     TeeContext *tee = avf->priv_data;
113     unsigned i;
114
115     for (i = 0; i < tee->nb_slaves; i++) {
116         close_slave(&tee->slaves[i]);
117     }
118     av_freep(&tee->slaves);
119 }
120
121 static int open_slave(AVFormatContext *avf, char *slave, TeeSlave *tee_slave)
122 {
123     int i, ret;
124     AVDictionary *options = NULL;
125     AVDictionaryEntry *entry;
126     char *filename;
127     char *format = NULL, *select = NULL, *on_fail = NULL;
128     AVFormatContext *avf2 = NULL;
129     AVStream *st, *st2;
130     int stream_count;
131     int fullret;
132     char *subselect = NULL, *next_subselect = NULL, *first_subselect = NULL, *tmp_select = NULL;
133
134     if ((ret = ff_tee_parse_slave_options(avf, slave, &options, &filename)) < 0)
135         return ret;
136
137 #define STEAL_OPTION(option, field) do {                                \
138         if ((entry = av_dict_get(options, option, NULL, 0))) {          \
139             field = entry->value;                                       \
140             entry->value = NULL; /* prevent it from being freed */      \
141             av_dict_set(&options, option, NULL, 0);                     \
142         }                                                               \
143     } while (0)
144
145     STEAL_OPTION("f", format);
146     STEAL_OPTION("select", select);
147     STEAL_OPTION("onfail", on_fail);
148
149     ret = parse_slave_failure_policy_option(on_fail, tee_slave);
150     if (ret < 0) {
151         av_log(avf, AV_LOG_ERROR,
152                "Invalid onfail option value, valid options are 'abort' and 'ignore'\n");
153         goto end;
154     }
155
156     ret = avformat_alloc_output_context2(&avf2, NULL, format, filename);
157     if (ret < 0)
158         goto end;
159     tee_slave->avf = avf2;
160     av_dict_copy(&avf2->metadata, avf->metadata, 0);
161     avf2->opaque   = avf->opaque;
162     avf2->io_open  = avf->io_open;
163     avf2->io_close = avf->io_close;
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             tmp_select = av_strdup(select);  // av_strtok is destructive so we regenerate it in each loop
176             if (!tmp_select) {
177                 ret = AVERROR(ENOMEM);
178                 goto end;
179             }
180             fullret = 0;
181             first_subselect = tmp_select;
182             next_subselect = NULL;
183             while (subselect = av_strtok(first_subselect, slave_select_sep, &next_subselect)) {
184                 first_subselect = NULL;
185
186                 ret = avformat_match_stream_specifier(avf, avf->streams[i], subselect);
187                 if (ret < 0) {
188                     av_log(avf, AV_LOG_ERROR,
189                            "Invalid stream specifier '%s' for output '%s'\n",
190                            subselect, slave);
191                     goto end;
192                 }
193                 if (ret != 0) {
194                     fullret = 1; // match
195                     break;
196                 }
197             }
198             av_freep(&tmp_select);
199
200             if (fullret == 0) { /* no match */
201                 tee_slave->stream_map[i] = -1;
202                 continue;
203             }
204         }
205         tee_slave->stream_map[i] = stream_count++;
206
207         if (!(st2 = avformat_new_stream(avf2, NULL))) {
208             ret = AVERROR(ENOMEM);
209             goto end;
210         }
211
212         ret = ff_stream_encode_params_copy(st2, st);
213         if (ret < 0)
214             goto end;
215     }
216
217     ret = ff_format_output_open(avf2, filename, NULL);
218     if (ret < 0) {
219         av_log(avf, AV_LOG_ERROR, "Slave '%s': error opening: %s\n", slave,
220                av_err2str(ret));
221         goto end;
222     }
223
224     if ((ret = avformat_write_header(avf2, &options)) < 0) {
225         av_log(avf, AV_LOG_ERROR, "Slave '%s': error writing header: %s\n",
226                slave, av_err2str(ret));
227         goto end;
228     }
229     tee_slave->header_written = 1;
230
231     tee_slave->bsfs = av_calloc(avf2->nb_streams, sizeof(*tee_slave->bsfs));
232     if (!tee_slave->bsfs) {
233         ret = AVERROR(ENOMEM);
234         goto end;
235     }
236
237     entry = NULL;
238     while (entry = av_dict_get(options, "bsfs", NULL, AV_DICT_IGNORE_SUFFIX)) {
239         const char *spec = entry->key + strlen("bsfs");
240         if (*spec) {
241             if (strspn(spec, slave_bsfs_spec_sep) != 1) {
242                 av_log(avf, AV_LOG_ERROR,
243                        "Specifier separator in '%s' is '%c', but only characters '%s' "
244                        "are allowed\n", entry->key, *spec, slave_bsfs_spec_sep);
245                 ret = AVERROR(EINVAL);
246                 goto end;
247             }
248             spec++; /* consume separator */
249         }
250
251         for (i = 0; i < avf2->nb_streams; i++) {
252             ret = avformat_match_stream_specifier(avf2, avf2->streams[i], spec);
253             if (ret < 0) {
254                 av_log(avf, AV_LOG_ERROR,
255                        "Invalid stream specifier '%s' in bsfs option '%s' for slave "
256                        "output '%s'\n", spec, entry->key, filename);
257                 goto end;
258             }
259
260             if (ret > 0) {
261                 av_log(avf, AV_LOG_DEBUG, "spec:%s bsfs:%s matches stream %d of slave "
262                        "output '%s'\n", spec, entry->value, i, filename);
263                 if (tee_slave->bsfs[i]) {
264                     av_log(avf, AV_LOG_WARNING,
265                            "Duplicate bsfs specification associated to stream %d of slave "
266                            "output '%s', filters will be ignored\n", i, filename);
267                     continue;
268                 }
269                 ret = av_bsf_list_parse_str(entry->value, &tee_slave->bsfs[i]);
270                 if (ret < 0) {
271                     av_log(avf, AV_LOG_ERROR,
272                            "Error parsing bitstream filter sequence '%s' associated to "
273                            "stream %d of slave output '%s'\n", entry->value, i, filename);
274                     goto end;
275                 }
276             }
277         }
278
279         av_dict_set(&options, entry->key, NULL, 0);
280     }
281
282     for (i = 0; i < avf->nb_streams; i++){
283         int target_stream = tee_slave->stream_map[i];
284         if (target_stream < 0)
285             continue;
286
287         if (!tee_slave->bsfs[target_stream]) {
288             /* Add pass-through bitstream filter */
289             ret = av_bsf_get_null_filter(&tee_slave->bsfs[target_stream]);
290             if (ret < 0) {
291                 av_log(avf, AV_LOG_ERROR,
292                        "Failed to create pass-through bitstream filter: %s\n",
293                        av_err2str(ret));
294                 goto end;
295             }
296         }
297
298         tee_slave->bsfs[target_stream]->time_base_in = avf->streams[i]->time_base;
299         ret = avcodec_parameters_copy(tee_slave->bsfs[target_stream]->par_in,
300                                       avf->streams[i]->codecpar);
301         if (ret < 0)
302             goto end;
303
304         ret = av_bsf_init(tee_slave->bsfs[target_stream]);
305         if (ret < 0) {
306             av_log(avf, AV_LOG_ERROR,
307             "Failed to initialize bitstream filter(s): %s\n",
308             av_err2str(ret));
309             goto end;
310         }
311     }
312
313     if (options) {
314         entry = NULL;
315         while ((entry = av_dict_get(options, "", entry, AV_DICT_IGNORE_SUFFIX)))
316             av_log(avf2, AV_LOG_ERROR, "Unknown option '%s'\n", entry->key);
317         ret = AVERROR_OPTION_NOT_FOUND;
318         goto end;
319     }
320
321 end:
322     av_free(format);
323     av_free(select);
324     av_free(on_fail);
325     av_dict_free(&options);
326     av_freep(&tmp_select);
327     return ret;
328 }
329
330 static void log_slave(TeeSlave *slave, void *log_ctx, int log_level)
331 {
332     int i;
333     av_log(log_ctx, log_level, "filename:'%s' format:%s\n",
334            slave->avf->filename, slave->avf->oformat->name);
335     for (i = 0; i < slave->avf->nb_streams; i++) {
336         AVStream *st = slave->avf->streams[i];
337         AVBSFContext *bsf = slave->bsfs[i];
338         const char *bsf_name;
339
340         av_log(log_ctx, log_level, "    stream:%d codec:%s type:%s",
341                i, avcodec_get_name(st->codecpar->codec_id),
342                av_get_media_type_string(st->codecpar->codec_type));
343
344         bsf_name = bsf->filter->priv_class ?
345                    bsf->filter->priv_class->item_name(bsf) : bsf->filter->name;
346         av_log(log_ctx, log_level, " bsfs: %s\n", bsf_name);
347     }
348 }
349
350 static int tee_process_slave_failure(AVFormatContext *avf, unsigned slave_idx, int err_n)
351 {
352     TeeContext *tee = avf->priv_data;
353     TeeSlave *tee_slave = &tee->slaves[slave_idx];
354
355     tee->nb_alive--;
356
357     close_slave(tee_slave);
358
359     if (!tee->nb_alive) {
360         av_log(avf, AV_LOG_ERROR, "All tee outputs failed.\n");
361         return err_n;
362     } else if (tee_slave->on_fail == ON_SLAVE_FAILURE_ABORT) {
363         av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed, aborting.\n", slave_idx);
364         return err_n;
365     } else {
366         av_log(avf, AV_LOG_ERROR, "Slave muxer #%u failed: %s, continuing with %u/%u slaves.\n",
367                slave_idx, av_err2str(err_n), tee->nb_alive, tee->nb_slaves);
368         return 0;
369     }
370 }
371
372 static int tee_write_header(AVFormatContext *avf)
373 {
374     TeeContext *tee = avf->priv_data;
375     unsigned nb_slaves = 0, i;
376     const char *filename = avf->filename;
377     char **slaves = NULL;
378     int ret;
379
380     while (*filename) {
381         char *slave = av_get_token(&filename, slave_delim);
382         if (!slave) {
383             ret = AVERROR(ENOMEM);
384             goto fail;
385         }
386         ret = av_dynarray_add_nofree(&slaves, &nb_slaves, slave);
387         if (ret < 0) {
388             av_free(slave);
389             goto fail;
390         }
391         if (strspn(filename, slave_delim))
392             filename++;
393     }
394
395     if (!(tee->slaves = av_mallocz_array(nb_slaves, sizeof(*tee->slaves)))) {
396         ret = AVERROR(ENOMEM);
397         goto fail;
398     }
399     tee->nb_slaves = tee->nb_alive = nb_slaves;
400
401     for (i = 0; i < nb_slaves; i++) {
402         if ((ret = open_slave(avf, slaves[i], &tee->slaves[i])) < 0) {
403             ret = tee_process_slave_failure(avf, i, ret);
404             if (ret < 0)
405                 goto fail;
406         } else {
407             log_slave(&tee->slaves[i], avf, AV_LOG_VERBOSE);
408         }
409         av_freep(&slaves[i]);
410     }
411
412     for (i = 0; i < avf->nb_streams; i++) {
413         int j, mapped = 0;
414         for (j = 0; j < tee->nb_slaves; j++)
415             if (tee->slaves[j].avf)
416                 mapped += tee->slaves[j].stream_map[i] >= 0;
417         if (!mapped)
418             av_log(avf, AV_LOG_WARNING, "Input stream #%d is not mapped "
419                    "to any slave.\n", i);
420     }
421     av_free(slaves);
422     return 0;
423
424 fail:
425     for (i = 0; i < nb_slaves; i++)
426         av_freep(&slaves[i]);
427     close_slaves(avf);
428     av_free(slaves);
429     return ret;
430 }
431
432 static int tee_write_trailer(AVFormatContext *avf)
433 {
434     TeeContext *tee = avf->priv_data;
435     int ret_all = 0, ret;
436     unsigned i;
437
438     for (i = 0; i < tee->nb_slaves; i++) {
439         if ((ret = close_slave(&tee->slaves[i])) < 0) {
440             ret = tee_process_slave_failure(avf, i, ret);
441             if (!ret_all && ret < 0)
442                 ret_all = ret;
443         }
444     }
445     av_freep(&tee->slaves);
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     AVBSFContext *bsfs;
454     AVPacket pkt2;
455     int ret_all = 0, ret;
456     unsigned i, s;
457     int s2;
458
459     for (i = 0; i < tee->nb_slaves; i++) {
460         if (!(avf2 = tee->slaves[i].avf))
461             continue;
462
463         /* Flush slave if pkt is NULL*/
464         if (!pkt) {
465             ret = av_interleaved_write_frame(avf2, NULL);
466             if (ret < 0) {
467                 ret = tee_process_slave_failure(avf, i, ret);
468                 if (!ret_all && ret < 0)
469                     ret_all = ret;
470             }
471             continue;
472         }
473
474         s = pkt->stream_index;
475         s2 = tee->slaves[i].stream_map[s];
476         if (s2 < 0)
477             continue;
478
479         memset(&pkt2, 0, sizeof(AVPacket));
480         if ((ret = av_packet_ref(&pkt2, pkt)) < 0)
481             if (!ret_all) {
482                 ret_all = ret;
483                 continue;
484             }
485         bsfs = tee->slaves[i].bsfs[s2];
486         pkt2.stream_index = s2;
487
488         ret = av_bsf_send_packet(bsfs, &pkt2);
489         if (ret < 0) {
490             av_log(avf, AV_LOG_ERROR, "Error while sending packet to bitstream filter: %s\n",
491                    av_err2str(ret));
492             ret = tee_process_slave_failure(avf, i, ret);
493             if (!ret_all && ret < 0)
494                 ret_all = ret;
495         }
496
497         while(1) {
498             ret = av_bsf_receive_packet(bsfs, &pkt2);
499             if (ret == AVERROR(EAGAIN)) {
500                 ret = 0;
501                 break;
502             } else if (ret < 0) {
503                 break;
504             }
505
506             av_packet_rescale_ts(&pkt2, bsfs->time_base_out,
507                                  avf2->streams[s2]->time_base);
508             ret = av_interleaved_write_frame(avf2, &pkt2);
509             if (ret < 0)
510                 break;
511         };
512
513         if (ret < 0) {
514             ret = tee_process_slave_failure(avf, i, ret);
515             if (!ret_all && ret < 0)
516                 ret_all = ret;
517         }
518     }
519     return ret_all;
520 }
521
522 AVOutputFormat ff_tee_muxer = {
523     .name              = "tee",
524     .long_name         = NULL_IF_CONFIG_SMALL("Multiple muxer tee"),
525     .priv_data_size    = sizeof(TeeContext),
526     .write_header      = tee_write_header,
527     .write_trailer     = tee_write_trailer,
528     .write_packet      = tee_write_packet,
529     .priv_class        = &tee_muxer_class,
530     .flags             = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
531 };