]> git.sesse.net Git - ffmpeg/blob - libavformat/concatdec.c
avformat/concatdec: factorize the duration calculating function
[ffmpeg] / libavformat / concatdec.c
1 /*
2  * Copyright (c) 2012 Nicolas George
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License
8  * as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/avassert.h"
22 #include "libavutil/avstring.h"
23 #include "libavutil/bprint.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/parseutils.h"
27 #include "libavutil/timestamp.h"
28 #include "avformat.h"
29 #include "internal.h"
30 #include "url.h"
31
32 typedef enum ConcatMatchMode {
33     MATCH_ONE_TO_ONE,
34     MATCH_EXACT_ID,
35 } ConcatMatchMode;
36
37 typedef struct ConcatStream {
38     AVBSFContext *bsf;
39     int out_stream_index;
40 } ConcatStream;
41
42 typedef struct {
43     char *url;
44     int64_t start_time;
45     int64_t file_start_time;
46     int64_t file_inpoint;
47     int64_t duration;
48     int64_t user_duration;
49     int64_t next_dts;
50     ConcatStream *streams;
51     int64_t inpoint;
52     int64_t outpoint;
53     AVDictionary *metadata;
54     int nb_streams;
55 } ConcatFile;
56
57 typedef struct {
58     AVClass *class;
59     ConcatFile *files;
60     ConcatFile *cur_file;
61     unsigned nb_files;
62     AVFormatContext *avf;
63     int safe;
64     int seekable;
65     int eof;
66     ConcatMatchMode stream_match_mode;
67     unsigned auto_convert;
68     int segment_time_metadata;
69 } ConcatContext;
70
71 static int concat_probe(AVProbeData *probe)
72 {
73     return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
74            0 : AVPROBE_SCORE_MAX;
75 }
76
77 static char *get_keyword(uint8_t **cursor)
78 {
79     char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
80     *cursor += strcspn(*cursor, SPACE_CHARS);
81     if (**cursor) {
82         *((*cursor)++) = 0;
83         *cursor += strspn(*cursor, SPACE_CHARS);
84     }
85     return ret;
86 }
87
88 static int safe_filename(const char *f)
89 {
90     const char *start = f;
91
92     for (; *f; f++) {
93         /* A-Za-z0-9_- */
94         if (!((unsigned)((*f | 32) - 'a') < 26 ||
95               (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
96             if (f == start)
97                 return 0;
98             else if (*f == '/')
99                 start = f + 1;
100             else if (*f != '.')
101                 return 0;
102         }
103     }
104     return 1;
105 }
106
107 #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
108
109 static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
110                     unsigned *nb_files_alloc)
111 {
112     ConcatContext *cat = avf->priv_data;
113     ConcatFile *file;
114     char *url = NULL;
115     const char *proto;
116     size_t url_len, proto_len;
117     int ret;
118
119     if (cat->safe > 0 && !safe_filename(filename)) {
120         av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
121         FAIL(AVERROR(EPERM));
122     }
123
124     proto = avio_find_protocol_name(filename);
125     proto_len = proto ? strlen(proto) : 0;
126     if (proto && !memcmp(filename, proto, proto_len) &&
127         (filename[proto_len] == ':' || filename[proto_len] == ',')) {
128         url = filename;
129         filename = NULL;
130     } else {
131         url_len = strlen(avf->url) + strlen(filename) + 16;
132         if (!(url = av_malloc(url_len)))
133             FAIL(AVERROR(ENOMEM));
134         ff_make_absolute_url(url, url_len, avf->url, filename);
135         av_freep(&filename);
136     }
137
138     if (cat->nb_files >= *nb_files_alloc) {
139         size_t n = FFMAX(*nb_files_alloc * 2, 16);
140         ConcatFile *new_files;
141         if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
142             !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
143             FAIL(AVERROR(ENOMEM));
144         cat->files = new_files;
145         *nb_files_alloc = n;
146     }
147
148     file = &cat->files[cat->nb_files++];
149     memset(file, 0, sizeof(*file));
150     *rfile = file;
151
152     file->url        = url;
153     file->start_time = AV_NOPTS_VALUE;
154     file->duration   = AV_NOPTS_VALUE;
155     file->next_dts   = AV_NOPTS_VALUE;
156     file->inpoint    = AV_NOPTS_VALUE;
157     file->outpoint   = AV_NOPTS_VALUE;
158     file->user_duration = AV_NOPTS_VALUE;
159
160     return 0;
161
162 fail:
163     av_free(url);
164     av_free(filename);
165     return ret;
166 }
167
168 static int copy_stream_props(AVStream *st, AVStream *source_st)
169 {
170     int ret;
171
172     if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
173         if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
174             if (st->codecpar->extradata) {
175                 av_freep(&st->codecpar->extradata);
176                 st->codecpar->extradata_size = 0;
177             }
178             ret = ff_alloc_extradata(st->codecpar,
179                                      source_st->codecpar->extradata_size);
180             if (ret < 0)
181                 return ret;
182         }
183         memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
184                source_st->codecpar->extradata_size);
185         return 0;
186     }
187     if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
188         return ret;
189     st->r_frame_rate        = source_st->r_frame_rate;
190     st->avg_frame_rate      = source_st->avg_frame_rate;
191     st->sample_aspect_ratio = source_st->sample_aspect_ratio;
192     avpriv_set_pts_info(st, 64, source_st->time_base.num, source_st->time_base.den);
193
194     av_dict_copy(&st->metadata, source_st->metadata, 0);
195     return 0;
196 }
197
198 static int detect_stream_specific(AVFormatContext *avf, int idx)
199 {
200     ConcatContext *cat = avf->priv_data;
201     AVStream *st = cat->avf->streams[idx];
202     ConcatStream *cs = &cat->cur_file->streams[idx];
203     const AVBitStreamFilter *filter;
204     AVBSFContext *bsf;
205     int ret;
206
207     if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264) {
208         if (!st->codecpar->extradata_size                                                ||
209             (st->codecpar->extradata_size >= 3 && AV_RB24(st->codecpar->extradata) == 1) ||
210             (st->codecpar->extradata_size >= 4 && AV_RB32(st->codecpar->extradata) == 1))
211             return 0;
212         av_log(cat->avf, AV_LOG_INFO,
213                "Auto-inserting h264_mp4toannexb bitstream filter\n");
214         filter = av_bsf_get_by_name("h264_mp4toannexb");
215         if (!filter) {
216             av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
217                    "required for H.264 streams\n");
218             return AVERROR_BSF_NOT_FOUND;
219         }
220         ret = av_bsf_alloc(filter, &bsf);
221         if (ret < 0)
222             return ret;
223         cs->bsf = bsf;
224
225         ret = avcodec_parameters_copy(bsf->par_in, st->codecpar);
226         if (ret < 0)
227            return ret;
228
229         ret = av_bsf_init(bsf);
230         if (ret < 0)
231             return ret;
232
233         ret = avcodec_parameters_copy(st->codecpar, bsf->par_out);
234         if (ret < 0)
235             return ret;
236     }
237     return 0;
238 }
239
240 static int match_streams_one_to_one(AVFormatContext *avf)
241 {
242     ConcatContext *cat = avf->priv_data;
243     AVStream *st;
244     int i, ret;
245
246     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
247         if (i < avf->nb_streams) {
248             st = avf->streams[i];
249         } else {
250             if (!(st = avformat_new_stream(avf, NULL)))
251                 return AVERROR(ENOMEM);
252         }
253         if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
254             return ret;
255         cat->cur_file->streams[i].out_stream_index = i;
256     }
257     return 0;
258 }
259
260 static int match_streams_exact_id(AVFormatContext *avf)
261 {
262     ConcatContext *cat = avf->priv_data;
263     AVStream *st;
264     int i, j, ret;
265
266     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
267         st = cat->avf->streams[i];
268         for (j = 0; j < avf->nb_streams; j++) {
269             if (avf->streams[j]->id == st->id) {
270                 av_log(avf, AV_LOG_VERBOSE,
271                        "Match slave stream #%d with stream #%d id 0x%x\n",
272                        i, j, st->id);
273                 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
274                     return ret;
275                 cat->cur_file->streams[i].out_stream_index = j;
276             }
277         }
278     }
279     return 0;
280 }
281
282 static int match_streams(AVFormatContext *avf)
283 {
284     ConcatContext *cat = avf->priv_data;
285     ConcatStream *map;
286     int i, ret;
287
288     if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
289         return 0;
290     map = av_realloc(cat->cur_file->streams,
291                      cat->avf->nb_streams * sizeof(*map));
292     if (!map)
293         return AVERROR(ENOMEM);
294     cat->cur_file->streams = map;
295     memset(map + cat->cur_file->nb_streams, 0,
296            (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
297
298     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
299         map[i].out_stream_index = -1;
300         if ((ret = detect_stream_specific(avf, i)) < 0)
301             return ret;
302     }
303     switch (cat->stream_match_mode) {
304     case MATCH_ONE_TO_ONE:
305         ret = match_streams_one_to_one(avf);
306         break;
307     case MATCH_EXACT_ID:
308         ret = match_streams_exact_id(avf);
309         break;
310     default:
311         ret = AVERROR_BUG;
312     }
313     if (ret < 0)
314         return ret;
315     cat->cur_file->nb_streams = cat->avf->nb_streams;
316     return 0;
317 }
318
319 static int64_t get_best_effort_duration(ConcatFile *file, AVFormatContext *avf)
320 {
321     if (file->user_duration != AV_NOPTS_VALUE)
322         return file->user_duration;
323     if (file->outpoint != AV_NOPTS_VALUE)
324         return file->outpoint - file->file_inpoint;
325     if (avf->duration > 0)
326         return avf->duration - (file->file_inpoint - file->file_start_time);
327     if (file->next_dts != AV_NOPTS_VALUE)
328         return file->next_dts - (file->file_inpoint - file->file_start_time);
329     return AV_NOPTS_VALUE;
330 }
331
332 static int open_file(AVFormatContext *avf, unsigned fileno)
333 {
334     ConcatContext *cat = avf->priv_data;
335     ConcatFile *file = &cat->files[fileno];
336     int ret;
337
338     if (cat->avf)
339         avformat_close_input(&cat->avf);
340
341     cat->avf = avformat_alloc_context();
342     if (!cat->avf)
343         return AVERROR(ENOMEM);
344
345     cat->avf->flags |= avf->flags & ~AVFMT_FLAG_CUSTOM_IO;
346     cat->avf->interrupt_callback = avf->interrupt_callback;
347
348     if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
349         return ret;
350
351     if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
352         (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
353         av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
354         avformat_close_input(&cat->avf);
355         return ret;
356     }
357     cat->cur_file = file;
358     if (file->start_time == AV_NOPTS_VALUE)
359         file->start_time = !fileno ? 0 :
360                            cat->files[fileno - 1].start_time +
361                            cat->files[fileno - 1].duration;
362     file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
363     file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
364     if (file->duration == AV_NOPTS_VALUE)
365         file->duration = get_best_effort_duration(file, cat->avf);
366
367     if (cat->segment_time_metadata) {
368         av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
369         if (file->duration != AV_NOPTS_VALUE)
370             av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
371     }
372
373     if ((ret = match_streams(avf)) < 0)
374         return ret;
375     if (file->inpoint != AV_NOPTS_VALUE) {
376        if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
377            return ret;
378     }
379     return 0;
380 }
381
382 static int concat_read_close(AVFormatContext *avf)
383 {
384     ConcatContext *cat = avf->priv_data;
385     unsigned i, j;
386
387     for (i = 0; i < cat->nb_files; i++) {
388         av_freep(&cat->files[i].url);
389         for (j = 0; j < cat->files[i].nb_streams; j++) {
390             if (cat->files[i].streams[j].bsf)
391                 av_bsf_free(&cat->files[i].streams[j].bsf);
392         }
393         av_freep(&cat->files[i].streams);
394         av_dict_free(&cat->files[i].metadata);
395     }
396     if (cat->avf)
397         avformat_close_input(&cat->avf);
398     av_freep(&cat->files);
399     return 0;
400 }
401
402 static int concat_read_header(AVFormatContext *avf)
403 {
404     ConcatContext *cat = avf->priv_data;
405     AVBPrint bp;
406     uint8_t *cursor, *keyword;
407     int line = 0, i;
408     unsigned nb_files_alloc = 0;
409     ConcatFile *file = NULL;
410     int64_t ret, time = 0;
411
412     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
413
414     while ((ret = ff_read_line_to_bprint_overwrite(avf->pb, &bp)) >= 0) {
415         line++;
416         cursor = bp.str;
417         keyword = get_keyword(&cursor);
418         if (!*keyword || *keyword == '#')
419             continue;
420
421         if (!strcmp(keyword, "file")) {
422             char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
423             if (!filename) {
424                 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
425                 FAIL(AVERROR_INVALIDDATA);
426             }
427             if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
428                 goto fail;
429         } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
430             char *dur_str = get_keyword(&cursor);
431             int64_t dur;
432             if (!file) {
433                 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
434                        line, keyword);
435                 FAIL(AVERROR_INVALIDDATA);
436             }
437             if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
438                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
439                        line, keyword, dur_str);
440                 goto fail;
441             }
442             if (!strcmp(keyword, "duration"))
443                 file->user_duration = dur;
444             else if (!strcmp(keyword, "inpoint"))
445                 file->inpoint = dur;
446             else if (!strcmp(keyword, "outpoint"))
447                 file->outpoint = dur;
448         } else if (!strcmp(keyword, "file_packet_metadata")) {
449             char *metadata;
450             if (!file) {
451                 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
452                        line, keyword);
453                 FAIL(AVERROR_INVALIDDATA);
454             }
455             metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
456             if (!metadata) {
457                 av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
458                 FAIL(AVERROR_INVALIDDATA);
459             }
460             if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
461                 av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
462                 av_freep(&metadata);
463                 FAIL(AVERROR_INVALIDDATA);
464             }
465             av_freep(&metadata);
466         } else if (!strcmp(keyword, "stream")) {
467             if (!avformat_new_stream(avf, NULL))
468                 FAIL(AVERROR(ENOMEM));
469         } else if (!strcmp(keyword, "exact_stream_id")) {
470             if (!avf->nb_streams) {
471                 av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
472                        line);
473                 FAIL(AVERROR_INVALIDDATA);
474             }
475             avf->streams[avf->nb_streams - 1]->id =
476                 strtol(get_keyword(&cursor), NULL, 0);
477         } else if (!strcmp(keyword, "ffconcat")) {
478             char *ver_kw  = get_keyword(&cursor);
479             char *ver_val = get_keyword(&cursor);
480             if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
481                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
482                 FAIL(AVERROR_INVALIDDATA);
483             }
484             if (cat->safe < 0)
485                 cat->safe = 1;
486         } else {
487             av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
488                    line, keyword);
489             FAIL(AVERROR_INVALIDDATA);
490         }
491     }
492     if (ret != AVERROR_EOF && ret < 0)
493         goto fail;
494     if (!cat->nb_files)
495         FAIL(AVERROR_INVALIDDATA);
496
497     for (i = 0; i < cat->nb_files; i++) {
498         if (cat->files[i].start_time == AV_NOPTS_VALUE)
499             cat->files[i].start_time = time;
500         else
501             time = cat->files[i].start_time;
502         if (cat->files[i].user_duration == AV_NOPTS_VALUE) {
503             if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
504                 break;
505             cat->files[i].user_duration = cat->files[i].outpoint - cat->files[i].inpoint;
506         }
507         time += cat->files[i].user_duration;
508     }
509     if (i == cat->nb_files) {
510         avf->duration = time;
511         cat->seekable = 1;
512     }
513
514     cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
515                                                MATCH_ONE_TO_ONE;
516     if ((ret = open_file(avf, 0)) < 0)
517         goto fail;
518     av_bprint_finalize(&bp, NULL);
519     return 0;
520
521 fail:
522     av_bprint_finalize(&bp, NULL);
523     concat_read_close(avf);
524     return ret;
525 }
526
527 static int open_next_file(AVFormatContext *avf)
528 {
529     ConcatContext *cat = avf->priv_data;
530     unsigned fileno = cat->cur_file - cat->files;
531
532     if (cat->cur_file->duration == AV_NOPTS_VALUE)
533         cat->cur_file->duration = get_best_effort_duration(cat->cur_file, cat->avf);
534
535     if (++fileno >= cat->nb_files) {
536         cat->eof = 1;
537         return AVERROR_EOF;
538     }
539     return open_file(avf, fileno);
540 }
541
542 static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
543 {
544     int ret;
545
546     if (cs->bsf) {
547         ret = av_bsf_send_packet(cs->bsf, pkt);
548         if (ret < 0) {
549             av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
550                    "failed to send input packet\n");
551             av_packet_unref(pkt);
552             return ret;
553         }
554
555         while (!ret)
556             ret = av_bsf_receive_packet(cs->bsf, pkt);
557
558         if (ret < 0 && (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)) {
559             av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
560                    "failed to receive output packet\n");
561             return ret;
562         }
563     }
564     return 0;
565 }
566
567 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
568 static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
569 {
570     if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
571         return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
572                              cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
573     }
574     return 0;
575 }
576
577 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
578 {
579     ConcatContext *cat = avf->priv_data;
580     int ret;
581     int64_t delta;
582     ConcatStream *cs;
583     AVStream *st;
584
585     if (cat->eof)
586         return AVERROR_EOF;
587
588     if (!cat->avf)
589         return AVERROR(EIO);
590
591     while (1) {
592         ret = av_read_frame(cat->avf, pkt);
593         if (ret == AVERROR_EOF) {
594             if ((ret = open_next_file(avf)) < 0)
595                 return ret;
596             continue;
597         }
598         if (ret < 0)
599             return ret;
600         if ((ret = match_streams(avf)) < 0) {
601             av_packet_unref(pkt);
602             return ret;
603         }
604         if (packet_after_outpoint(cat, pkt)) {
605             av_packet_unref(pkt);
606             if ((ret = open_next_file(avf)) < 0)
607                 return ret;
608             continue;
609         }
610         cs = &cat->cur_file->streams[pkt->stream_index];
611         if (cs->out_stream_index < 0) {
612             av_packet_unref(pkt);
613             continue;
614         }
615         break;
616     }
617     if ((ret = filter_packet(avf, cs, pkt)))
618         return ret;
619
620     st = cat->avf->streams[pkt->stream_index];
621     av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
622            (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
623            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
624            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
625
626     delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
627                          AV_TIME_BASE_Q,
628                          cat->avf->streams[pkt->stream_index]->time_base);
629     if (pkt->pts != AV_NOPTS_VALUE)
630         pkt->pts += delta;
631     if (pkt->dts != AV_NOPTS_VALUE)
632         pkt->dts += delta;
633     av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
634            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
635            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
636     if (cat->cur_file->metadata) {
637         uint8_t* metadata;
638         int metadata_len;
639         char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
640         if (!packed_metadata)
641             return AVERROR(ENOMEM);
642         if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
643             av_freep(&packed_metadata);
644             return AVERROR(ENOMEM);
645         }
646         memcpy(metadata, packed_metadata, metadata_len);
647         av_freep(&packed_metadata);
648     }
649
650     if (cat->cur_file->duration == AV_NOPTS_VALUE && st->cur_dts != AV_NOPTS_VALUE) {
651         int64_t next_dts = av_rescale_q(st->cur_dts, st->time_base, AV_TIME_BASE_Q);
652         if (cat->cur_file->next_dts == AV_NOPTS_VALUE || next_dts > cat->cur_file->next_dts) {
653             cat->cur_file->next_dts = next_dts;
654         }
655     }
656
657     pkt->stream_index = cs->out_stream_index;
658     return ret;
659 }
660
661 static void rescale_interval(AVRational tb_in, AVRational tb_out,
662                              int64_t *min_ts, int64_t *ts, int64_t *max_ts)
663 {
664     *ts     = av_rescale_q    (*    ts, tb_in, tb_out);
665     *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
666                                AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
667     *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
668                                AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
669 }
670
671 static int try_seek(AVFormatContext *avf, int stream,
672                     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
673 {
674     ConcatContext *cat = avf->priv_data;
675     int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
676
677     ts -= t0;
678     min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
679     max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
680     if (stream >= 0) {
681         if (stream >= cat->avf->nb_streams)
682             return AVERROR(EIO);
683         rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
684                          &min_ts, &ts, &max_ts);
685     }
686     return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
687 }
688
689 static int real_seek(AVFormatContext *avf, int stream,
690                      int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
691 {
692     ConcatContext *cat = avf->priv_data;
693     int ret, left, right;
694
695     if (stream >= 0) {
696         if (stream >= avf->nb_streams)
697             return AVERROR(EINVAL);
698         rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
699                          &min_ts, &ts, &max_ts);
700     }
701
702     left  = 0;
703     right = cat->nb_files;
704
705     /* Always support seek to start */
706     if (ts <= 0)
707         right = 1;
708     else if (!cat->seekable)
709         return AVERROR(ESPIPE); /* XXX: can we use it? */
710
711     while (right - left > 1) {
712         int mid = (left + right) / 2;
713         if (ts < cat->files[mid].start_time)
714             right = mid;
715         else
716             left  = mid;
717     }
718
719     if (cat->cur_file != &cat->files[left]) {
720         if ((ret = open_file(avf, left)) < 0)
721             return ret;
722     } else {
723         cat->avf = cur_avf;
724     }
725
726     ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
727     if (ret < 0 &&
728         left < cat->nb_files - 1 &&
729         cat->files[left + 1].start_time < max_ts) {
730         if (cat->cur_file == &cat->files[left])
731             cat->avf = NULL;
732         if ((ret = open_file(avf, left + 1)) < 0)
733             return ret;
734         ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
735     }
736     return ret;
737 }
738
739 static int concat_seek(AVFormatContext *avf, int stream,
740                        int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
741 {
742     ConcatContext *cat = avf->priv_data;
743     ConcatFile *cur_file_saved = cat->cur_file;
744     AVFormatContext *cur_avf_saved = cat->avf;
745     int ret;
746
747     if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
748         return AVERROR(ENOSYS);
749     cat->avf = NULL;
750     if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags, cur_avf_saved)) < 0) {
751         if (cat->cur_file != cur_file_saved) {
752             if (cat->avf)
753                 avformat_close_input(&cat->avf);
754         }
755         cat->avf      = cur_avf_saved;
756         cat->cur_file = cur_file_saved;
757     } else {
758         if (cat->cur_file != cur_file_saved) {
759             avformat_close_input(&cur_avf_saved);
760         }
761         cat->eof = 0;
762     }
763     return ret;
764 }
765
766 #define OFFSET(x) offsetof(ConcatContext, x)
767 #define DEC AV_OPT_FLAG_DECODING_PARAM
768
769 static const AVOption options[] = {
770     { "safe", "enable safe mode",
771       OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
772     { "auto_convert", "automatically convert bitstream format",
773       OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
774     { "segment_time_metadata", "output file segment start time and duration as packet metadata",
775       OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
776     { NULL }
777 };
778
779 static const AVClass concat_class = {
780     .class_name = "concat demuxer",
781     .item_name  = av_default_item_name,
782     .option     = options,
783     .version    = LIBAVUTIL_VERSION_INT,
784 };
785
786
787 AVInputFormat ff_concat_demuxer = {
788     .name           = "concat",
789     .long_name      = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
790     .priv_data_size = sizeof(ConcatContext),
791     .read_probe     = concat_probe,
792     .read_header    = concat_read_header,
793     .read_packet    = concat_read_packet,
794     .read_close     = concat_read_close,
795     .read_seek2     = concat_seek,
796     .priv_class     = &concat_class,
797 };