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