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