]> git.sesse.net Git - ffmpeg/blob - libavformat/concatdec.c
lavf/concatdec: remove unrelated change during codecpar merge.
[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         (st->codecpar->extradata_size < 4 || AV_RB32(st->codecpar->extradata) != 1)) {
204         av_log(cat->avf, AV_LOG_INFO,
205                "Auto-inserting h264_mp4toannexb bitstream filter\n");
206         if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) {
207             av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
208                    "required for H.264 streams\n");
209             return AVERROR_BSF_NOT_FOUND;
210         }
211         cs->bsf = bsf;
212
213         cs->avctx = avcodec_alloc_context3(NULL);
214         if (!cs->avctx)
215             return AVERROR(ENOMEM);
216
217         ret = avcodec_parameters_to_context(cs->avctx, st->codecpar);
218         if (ret < 0) {
219             avcodec_free_context(&cs->avctx);
220             return ret;
221         }
222
223     }
224     return 0;
225 }
226
227 static int match_streams_one_to_one(AVFormatContext *avf)
228 {
229     ConcatContext *cat = avf->priv_data;
230     AVStream *st;
231     int i, ret;
232
233     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
234         if (i < avf->nb_streams) {
235             st = avf->streams[i];
236         } else {
237             if (!(st = avformat_new_stream(avf, NULL)))
238                 return AVERROR(ENOMEM);
239         }
240         if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
241             return ret;
242         cat->cur_file->streams[i].out_stream_index = i;
243     }
244     return 0;
245 }
246
247 static int match_streams_exact_id(AVFormatContext *avf)
248 {
249     ConcatContext *cat = avf->priv_data;
250     AVStream *st;
251     int i, j, ret;
252
253     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
254         st = cat->avf->streams[i];
255         for (j = 0; j < avf->nb_streams; j++) {
256             if (avf->streams[j]->id == st->id) {
257                 av_log(avf, AV_LOG_VERBOSE,
258                        "Match slave stream #%d with stream #%d id 0x%x\n",
259                        i, j, st->id);
260                 if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
261                     return ret;
262                 cat->cur_file->streams[i].out_stream_index = j;
263             }
264         }
265     }
266     return 0;
267 }
268
269 static int match_streams(AVFormatContext *avf)
270 {
271     ConcatContext *cat = avf->priv_data;
272     ConcatStream *map;
273     int i, ret;
274
275     if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
276         return 0;
277     map = av_realloc(cat->cur_file->streams,
278                      cat->avf->nb_streams * sizeof(*map));
279     if (!map)
280         return AVERROR(ENOMEM);
281     cat->cur_file->streams = map;
282     memset(map + cat->cur_file->nb_streams, 0,
283            (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
284
285     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
286         map[i].out_stream_index = -1;
287     switch (cat->stream_match_mode) {
288     case MATCH_ONE_TO_ONE:
289         ret = match_streams_one_to_one(avf);
290         break;
291     case MATCH_EXACT_ID:
292         ret = match_streams_exact_id(avf);
293         break;
294     default:
295         ret = AVERROR_BUG;
296     }
297     if (ret < 0)
298         return ret;
299     for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
300         if ((ret = detect_stream_specific(avf, i)) < 0)
301             return ret;
302     cat->cur_file->nb_streams = cat->avf->nb_streams;
303     return 0;
304 }
305
306 static int open_file(AVFormatContext *avf, unsigned fileno)
307 {
308     ConcatContext *cat = avf->priv_data;
309     ConcatFile *file = &cat->files[fileno];
310     int ret;
311
312     if (cat->avf)
313         avformat_close_input(&cat->avf);
314
315     cat->avf = avformat_alloc_context();
316     if (!cat->avf)
317         return AVERROR(ENOMEM);
318
319     cat->avf->interrupt_callback = avf->interrupt_callback;
320
321     if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
322         return ret;
323
324     if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
325         (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
326         av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
327         avformat_close_input(&cat->avf);
328         return ret;
329     }
330     cat->cur_file = file;
331     if (file->start_time == AV_NOPTS_VALUE)
332         file->start_time = !fileno ? 0 :
333                            cat->files[fileno - 1].start_time +
334                            cat->files[fileno - 1].duration;
335     file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
336     file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
337     if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
338         file->duration = file->outpoint - file->file_inpoint;
339
340     if (cat->segment_time_metadata) {
341         av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
342         if (file->duration != AV_NOPTS_VALUE)
343             av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
344     }
345
346     if ((ret = match_streams(avf)) < 0)
347         return ret;
348     if (file->inpoint != AV_NOPTS_VALUE) {
349        if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
350            return ret;
351     }
352     return 0;
353 }
354
355 static int concat_read_close(AVFormatContext *avf)
356 {
357     ConcatContext *cat = avf->priv_data;
358     unsigned i, j;
359
360     for (i = 0; i < cat->nb_files; i++) {
361         av_freep(&cat->files[i].url);
362         for (j = 0; j < cat->files[i].nb_streams; j++) {
363             if (cat->files[i].streams[j].avctx)
364                 avcodec_free_context(&cat->files[i].streams[j].avctx);
365             if (cat->files[i].streams[j].bsf)
366                 av_bitstream_filter_close(cat->files[i].streams[j].bsf);
367         }
368         av_freep(&cat->files[i].streams);
369         av_dict_free(&cat->files[i].metadata);
370     }
371     if (cat->avf)
372         avformat_close_input(&cat->avf);
373     av_freep(&cat->files);
374     return 0;
375 }
376
377 static int concat_read_header(AVFormatContext *avf)
378 {
379     ConcatContext *cat = avf->priv_data;
380     uint8_t buf[4096];
381     uint8_t *cursor, *keyword;
382     int ret, line = 0, i;
383     unsigned nb_files_alloc = 0;
384     ConcatFile *file = NULL;
385     int64_t time = 0;
386
387     while (1) {
388         if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
389             break;
390         line++;
391         cursor = buf;
392         keyword = get_keyword(&cursor);
393         if (!*keyword || *keyword == '#')
394             continue;
395
396         if (!strcmp(keyword, "file")) {
397             char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
398             if (!filename) {
399                 av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
400                 FAIL(AVERROR_INVALIDDATA);
401             }
402             if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
403                 goto fail;
404         } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
405             char *dur_str = get_keyword(&cursor);
406             int64_t dur;
407             if (!file) {
408                 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
409                        line, keyword);
410                 FAIL(AVERROR_INVALIDDATA);
411             }
412             if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
413                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
414                        line, keyword, dur_str);
415                 goto fail;
416             }
417             if (!strcmp(keyword, "duration"))
418                 file->duration = dur;
419             else if (!strcmp(keyword, "inpoint"))
420                 file->inpoint = dur;
421             else if (!strcmp(keyword, "outpoint"))
422                 file->outpoint = dur;
423         } else if (!strcmp(keyword, "file_packet_metadata")) {
424             char *metadata;
425             if (!file) {
426                 av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
427                        line, keyword);
428                 FAIL(AVERROR_INVALIDDATA);
429             }
430             metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
431             if (!metadata) {
432                 av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
433                 FAIL(AVERROR_INVALIDDATA);
434             }
435             if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
436                 av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
437                 av_freep(&metadata);
438                 FAIL(AVERROR_INVALIDDATA);
439             }
440             av_freep(&metadata);
441         } else if (!strcmp(keyword, "stream")) {
442             if (!avformat_new_stream(avf, NULL))
443                 FAIL(AVERROR(ENOMEM));
444         } else if (!strcmp(keyword, "exact_stream_id")) {
445             if (!avf->nb_streams) {
446                 av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
447                        line);
448                 FAIL(AVERROR_INVALIDDATA);
449             }
450             avf->streams[avf->nb_streams - 1]->id =
451                 strtol(get_keyword(&cursor), NULL, 0);
452         } else if (!strcmp(keyword, "ffconcat")) {
453             char *ver_kw  = get_keyword(&cursor);
454             char *ver_val = get_keyword(&cursor);
455             if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
456                 av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
457                 FAIL(AVERROR_INVALIDDATA);
458             }
459             if (cat->safe < 0)
460                 cat->safe = 1;
461         } else {
462             av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
463                    line, keyword);
464             FAIL(AVERROR_INVALIDDATA);
465         }
466     }
467     if (ret < 0)
468         goto fail;
469     if (!cat->nb_files)
470         FAIL(AVERROR_INVALIDDATA);
471
472     for (i = 0; i < cat->nb_files; i++) {
473         if (cat->files[i].start_time == AV_NOPTS_VALUE)
474             cat->files[i].start_time = time;
475         else
476             time = cat->files[i].start_time;
477         if (cat->files[i].duration == AV_NOPTS_VALUE) {
478             if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
479                 break;
480             cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
481         }
482         time += cat->files[i].duration;
483     }
484     if (i == cat->nb_files) {
485         avf->duration = time;
486         cat->seekable = 1;
487     }
488
489     cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
490                                                MATCH_ONE_TO_ONE;
491     if ((ret = open_file(avf, 0)) < 0)
492         goto fail;
493     return 0;
494
495 fail:
496     concat_read_close(avf);
497     return ret;
498 }
499
500 static int open_next_file(AVFormatContext *avf)
501 {
502     ConcatContext *cat = avf->priv_data;
503     unsigned fileno = cat->cur_file - cat->files;
504
505     if (cat->cur_file->duration == AV_NOPTS_VALUE)
506         cat->cur_file->duration = cat->avf->duration - (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
507
508     if (++fileno >= cat->nb_files) {
509         cat->eof = 1;
510         return AVERROR_EOF;
511     }
512     return open_file(avf, fileno);
513 }
514
515 static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
516 {
517     AVStream *st = avf->streams[cs->out_stream_index];
518     AVBitStreamFilterContext *bsf;
519     AVPacket pkt2;
520     int ret;
521
522     av_assert0(cs->out_stream_index >= 0);
523     for (bsf = cs->bsf; bsf; bsf = bsf->next) {
524         pkt2 = *pkt;
525
526         ret = av_bitstream_filter_filter(bsf, cs->avctx, NULL,
527                                          &pkt2.data, &pkt2.size,
528                                          pkt->data, pkt->size,
529                                          !!(pkt->flags & AV_PKT_FLAG_KEY));
530         if (ret < 0) {
531             av_packet_unref(pkt);
532             return ret;
533         }
534
535         if (cs->avctx->extradata_size > st->codecpar->extradata_size) {
536             int eret;
537             if (st->codecpar->extradata)
538                 av_freep(&st->codecpar->extradata);
539
540             eret = ff_alloc_extradata(st->codecpar, cs->avctx->extradata_size);
541             if (eret < 0) {
542                 av_packet_unref(pkt);
543                 return AVERROR(ENOMEM);
544             }
545             st->codecpar->extradata_size = cs->avctx->extradata_size;
546             memcpy(st->codecpar->extradata, cs->avctx->extradata, cs->avctx->extradata_size);
547         }
548
549         av_assert0(pkt2.buf);
550         if (ret == 0 && pkt2.data != pkt->data) {
551             if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
552                 av_free(pkt2.data);
553                 return ret;
554             }
555             ret = 1;
556         }
557         if (ret > 0) {
558             av_packet_unref(pkt);
559             pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
560                                         av_buffer_default_free, NULL, 0);
561             if (!pkt2.buf) {
562                 av_free(pkt2.data);
563                 return AVERROR(ENOMEM);
564             }
565         }
566         *pkt = pkt2;
567     }
568     return 0;
569 }
570
571 /* Returns true if the packet dts is greater or equal to the specified outpoint. */
572 static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
573 {
574     if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
575         return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
576                              cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
577     }
578     return 0;
579 }
580
581 static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
582 {
583     ConcatContext *cat = avf->priv_data;
584     int ret;
585     int64_t delta;
586     ConcatStream *cs;
587     AVStream *st;
588
589     if (cat->eof)
590         return AVERROR_EOF;
591
592     if (!cat->avf)
593         return AVERROR(EIO);
594
595     while (1) {
596         ret = av_read_frame(cat->avf, pkt);
597         if (ret == AVERROR_EOF) {
598             if ((ret = open_next_file(avf)) < 0)
599                 return ret;
600             continue;
601         }
602         if (ret < 0)
603             return ret;
604         if ((ret = match_streams(avf)) < 0) {
605             av_packet_unref(pkt);
606             return ret;
607         }
608         if (packet_after_outpoint(cat, pkt)) {
609             av_packet_unref(pkt);
610             if ((ret = open_next_file(avf)) < 0)
611                 return ret;
612             continue;
613         }
614         cs = &cat->cur_file->streams[pkt->stream_index];
615         if (cs->out_stream_index < 0) {
616             av_packet_unref(pkt);
617             continue;
618         }
619         pkt->stream_index = cs->out_stream_index;
620         break;
621     }
622     if ((ret = filter_packet(avf, cs, pkt)))
623         return ret;
624
625     st = cat->avf->streams[pkt->stream_index];
626     av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
627            (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
628            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
629            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
630
631     delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
632                          AV_TIME_BASE_Q,
633                          cat->avf->streams[pkt->stream_index]->time_base);
634     if (pkt->pts != AV_NOPTS_VALUE)
635         pkt->pts += delta;
636     if (pkt->dts != AV_NOPTS_VALUE)
637         pkt->dts += delta;
638     av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
639            av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
640            av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
641     if (cat->cur_file->metadata) {
642         uint8_t* metadata;
643         int metadata_len;
644         char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
645         if (!packed_metadata)
646             return AVERROR(ENOMEM);
647         if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
648             av_freep(&packed_metadata);
649             return AVERROR(ENOMEM);
650         }
651         memcpy(metadata, packed_metadata, metadata_len);
652         av_freep(&packed_metadata);
653     }
654     return ret;
655 }
656
657 static void rescale_interval(AVRational tb_in, AVRational tb_out,
658                              int64_t *min_ts, int64_t *ts, int64_t *max_ts)
659 {
660     *ts     = av_rescale_q    (*    ts, tb_in, tb_out);
661     *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
662                                AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
663     *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
664                                AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
665 }
666
667 static int try_seek(AVFormatContext *avf, int stream,
668                     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
669 {
670     ConcatContext *cat = avf->priv_data;
671     int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
672
673     ts -= t0;
674     min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
675     max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
676     if (stream >= 0) {
677         if (stream >= cat->avf->nb_streams)
678             return AVERROR(EIO);
679         rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
680                          &min_ts, &ts, &max_ts);
681     }
682     return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
683 }
684
685 static int real_seek(AVFormatContext *avf, int stream,
686                      int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
687 {
688     ConcatContext *cat = avf->priv_data;
689     int ret, left, right;
690
691     if (stream >= 0) {
692         if (stream >= avf->nb_streams)
693             return AVERROR(EINVAL);
694         rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
695                          &min_ts, &ts, &max_ts);
696     }
697
698     left  = 0;
699     right = cat->nb_files;
700     while (right - left > 1) {
701         int mid = (left + right) / 2;
702         if (ts < cat->files[mid].start_time)
703             right = mid;
704         else
705             left  = mid;
706     }
707
708     if ((ret = open_file(avf, left)) < 0)
709         return ret;
710
711     ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
712     if (ret < 0 &&
713         left < cat->nb_files - 1 &&
714         cat->files[left + 1].start_time < max_ts) {
715         if ((ret = open_file(avf, left + 1)) < 0)
716             return ret;
717         ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
718     }
719     return ret;
720 }
721
722 static int concat_seek(AVFormatContext *avf, int stream,
723                        int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
724 {
725     ConcatContext *cat = avf->priv_data;
726     ConcatFile *cur_file_saved = cat->cur_file;
727     AVFormatContext *cur_avf_saved = cat->avf;
728     int ret;
729
730     if (!cat->seekable)
731         return AVERROR(ESPIPE); /* XXX: can we use it? */
732     if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
733         return AVERROR(ENOSYS);
734     cat->avf = NULL;
735     if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
736         if (cat->avf)
737             avformat_close_input(&cat->avf);
738         cat->avf      = cur_avf_saved;
739         cat->cur_file = cur_file_saved;
740     } else {
741         avformat_close_input(&cur_avf_saved);
742         cat->eof = 0;
743     }
744     return ret;
745 }
746
747 #define OFFSET(x) offsetof(ConcatContext, x)
748 #define DEC AV_OPT_FLAG_DECODING_PARAM
749
750 static const AVOption options[] = {
751     { "safe", "enable safe mode",
752       OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
753     { "auto_convert", "automatically convert bitstream format",
754       OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
755     { "segment_time_metadata", "output file segment start time and duration as packet metadata",
756       OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
757     { NULL }
758 };
759
760 static const AVClass concat_class = {
761     .class_name = "concat demuxer",
762     .item_name  = av_default_item_name,
763     .option     = options,
764     .version    = LIBAVUTIL_VERSION_INT,
765 };
766
767
768 AVInputFormat ff_concat_demuxer = {
769     .name           = "concat",
770     .long_name      = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
771     .priv_data_size = sizeof(ConcatContext),
772     .read_probe     = concat_probe,
773     .read_header    = concat_read_header,
774     .read_packet    = concat_read_packet,
775     .read_close     = concat_read_close,
776     .read_seek2     = concat_seek,
777     .priv_class     = &concat_class,
778 };