concatdec.c 25.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (c) 2012 Nicolas George
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

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 28
#include "avformat.h"
#include "internal.h"
29
#include "url.h"
30

31 32 33 34 35
typedef enum ConcatMatchMode {
    MATCH_ONE_TO_ONE,
    MATCH_EXACT_ID,
} ConcatMatchMode;

36
typedef struct ConcatStream {
37
    AVBitStreamFilterContext *bsf;
38
    AVCodecContext *avctx;
39 40 41
    int out_stream_index;
} ConcatStream;

42 43 44
typedef struct {
    char *url;
    int64_t start_time;
45 46
    int64_t file_start_time;
    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 54 55
} ConcatFile;

typedef struct {
56
    AVClass *class;
57 58 59 60
    ConcatFile *files;
    ConcatFile *cur_file;
    unsigned nb_files;
    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 68 69 70
} ConcatContext;

static int concat_probe(AVProbeData *probe)
{
71 72
    return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
           0 : AVPROBE_SCORE_MAX;
73 74 75 76 77 78 79 80 81 82 83 84 85
}

static char *get_keyword(uint8_t **cursor)
{
    char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
    *cursor += strcspn(*cursor, SPACE_CHARS);
    if (**cursor) {
        *((*cursor)++) = 0;
        *cursor += strspn(*cursor, SPACE_CHARS);
    }
    return ret;
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
static int safe_filename(const char *f)
{
    const char *start = f;

    for (; *f; f++) {
        /* A-Za-z0-9_- */
        if (!((unsigned)((*f | 32) - 'a') < 26 ||
              (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
            if (f == start)
                return 0;
            else if (*f == '/')
                start = f + 1;
            else if (*f != '.')
                return 0;
        }
    }
    return 1;
}

105 106 107 108 109 110 111
#define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)

static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
                    unsigned *nb_files_alloc)
{
    ConcatContext *cat = avf->priv_data;
    ConcatFile *file;
112
    char *url = NULL;
113 114
    const char *proto;
    size_t url_len, proto_len;
115
    int ret;
116

117 118
    if (cat->safe > 0 && !safe_filename(filename)) {
        av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
119
        FAIL(AVERROR(EPERM));
120
    }
121 122 123 124 125 126 127 128

    proto = avio_find_protocol_name(filename);
    proto_len = proto ? strlen(proto) : 0;
    if (!memcmp(filename, proto, proto_len) &&
        (filename[proto_len] == ':' || filename[proto_len] == ',')) {
        url = filename;
        filename = NULL;
    } else {
129 130 131 132 133
        url_len = strlen(avf->filename) + strlen(filename) + 16;
        if (!(url = av_malloc(url_len)))
            FAIL(AVERROR(ENOMEM));
        ff_make_absolute_url(url, url_len, avf->filename, filename);
        av_freep(&filename);
134
    }
135 136

    if (cat->nb_files >= *nb_files_alloc) {
137
        size_t n = FFMAX(*nb_files_alloc * 2, 16);
138 139 140
        ConcatFile *new_files;
        if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
            !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
141
            FAIL(AVERROR(ENOMEM));
142
        cat->files = new_files;
143 144 145 146 147 148 149 150 151 152
        *nb_files_alloc = n;
    }

    file = &cat->files[cat->nb_files++];
    memset(file, 0, sizeof(*file));
    *rfile = file;

    file->url        = url;
    file->start_time = AV_NOPTS_VALUE;
    file->duration   = AV_NOPTS_VALUE;
153
    file->inpoint    = AV_NOPTS_VALUE;
154
    file->outpoint   = AV_NOPTS_VALUE;
155 156

    return 0;
157 158 159 160 161

fail:
    av_free(url);
    av_free(filename);
    return ret;
162 163
}

164 165 166 167
static int copy_stream_props(AVStream *st, AVStream *source_st)
{
    int ret;

168 169 170 171 172 173 174 175
    if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
        if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
            if (st->codecpar->extradata) {
                av_freep(&st->codecpar->extradata);
                st->codecpar->extradata_size = 0;
            }
            ret = ff_alloc_extradata(st->codecpar,
                                     source_st->codecpar->extradata_size);
176 177 178
            if (ret < 0)
                return ret;
        }
179 180
        memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
               source_st->codecpar->extradata_size);
181
        return 0;
182
    }
183
    if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
184 185 186 187 188
        return ret;
    st->r_frame_rate        = source_st->r_frame_rate;
    st->avg_frame_rate      = source_st->avg_frame_rate;
    st->time_base           = source_st->time_base;
    st->sample_aspect_ratio = source_st->sample_aspect_ratio;
189 190

    av_dict_copy(&st->metadata, source_st->metadata, 0);
191 192 193
    return 0;
}

194 195 196 197 198 199
static int detect_stream_specific(AVFormatContext *avf, int idx)
{
    ConcatContext *cat = avf->priv_data;
    AVStream *st = cat->avf->streams[idx];
    ConcatStream *cs = &cat->cur_file->streams[idx];
    AVBitStreamFilterContext *bsf;
200
    int ret;
201

202 203
    if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
        (st->codecpar->extradata_size < 4 || AV_RB32(st->codecpar->extradata) != 1)) {
204 205 206 207 208 209 210 211
        av_log(cat->avf, AV_LOG_INFO,
               "Auto-inserting h264_mp4toannexb bitstream filter\n");
        if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) {
            av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
                   "required for H.264 streams\n");
            return AVERROR_BSF_NOT_FOUND;
        }
        cs->bsf = bsf;
212 213 214 215 216

        cs->avctx = avcodec_alloc_context3(NULL);
        if (!cs->avctx)
            return AVERROR(ENOMEM);

217 218 219 220 221 222
        /* This really should be part of the bsf work.
           Note: input bitstream filtering will not work with bsf that
           create extradata from the first packet. */
        av_freep(&st->codecpar->extradata);
        st->codecpar->extradata_size = 0;

223 224 225 226 227 228
        ret = avcodec_parameters_to_context(cs->avctx, st->codecpar);
        if (ret < 0) {
            avcodec_free_context(&cs->avctx);
            return ret;
        }

229 230 231 232
    }
    return 0;
}

233
static int match_streams_one_to_one(AVFormatContext *avf)
234 235 236
{
    ConcatContext *cat = avf->priv_data;
    AVStream *st;
237
    int i, ret;
238

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
        if (i < avf->nb_streams) {
            st = avf->streams[i];
        } else {
            if (!(st = avformat_new_stream(avf, NULL)))
                return AVERROR(ENOMEM);
        }
        if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
            return ret;
        cat->cur_file->streams[i].out_stream_index = i;
    }
    return 0;
}

static int match_streams_exact_id(AVFormatContext *avf)
{
    ConcatContext *cat = avf->priv_data;
    AVStream *st;
    int i, j, ret;
258

259
    for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
260 261 262 263 264 265
        st = cat->avf->streams[i];
        for (j = 0; j < avf->nb_streams; j++) {
            if (avf->streams[j]->id == st->id) {
                av_log(avf, AV_LOG_VERBOSE,
                       "Match slave stream #%d with stream #%d id 0x%x\n",
                       i, j, st->id);
266 267 268
                if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
                    return ret;
                cat->cur_file->streams[i].out_stream_index = j;
269 270 271
            }
        }
    }
272 273
    return 0;
}
274

275 276 277 278 279 280 281 282 283 284 285 286 287
static int match_streams(AVFormatContext *avf)
{
    ConcatContext *cat = avf->priv_data;
    ConcatStream *map;
    int i, ret;

    if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
        return 0;
    map = av_realloc(cat->cur_file->streams,
                     cat->avf->nb_streams * sizeof(*map));
    if (!map)
        return AVERROR(ENOMEM);
    cat->cur_file->streams = map;
288 289
    memset(map + cat->cur_file->nb_streams, 0,
           (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

    for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
        map[i].out_stream_index = -1;
    switch (cat->stream_match_mode) {
    case MATCH_ONE_TO_ONE:
        ret = match_streams_one_to_one(avf);
        break;
    case MATCH_EXACT_ID:
        ret = match_streams_exact_id(avf);
        break;
    default:
        ret = AVERROR_BUG;
    }
    if (ret < 0)
        return ret;
305 306 307
    for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
        if ((ret = detect_stream_specific(avf, i)) < 0)
            return ret;
308
    cat->cur_file->nb_streams = cat->avf->nb_streams;
309 310 311
    return 0;
}

312 313 314 315 316 317
static int open_file(AVFormatContext *avf, unsigned fileno)
{
    ConcatContext *cat = avf->priv_data;
    ConcatFile *file = &cat->files[fileno];
    int ret;

318 319
    if (cat->avf)
        avformat_close_input(&cat->avf);
320 321 322 323 324

    cat->avf = avformat_alloc_context();
    if (!cat->avf)
        return AVERROR(ENOMEM);

325
    cat->avf->flags |= avf->flags;
326
    cat->avf->interrupt_callback = avf->interrupt_callback;
327

328
    if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
329
        return ret;
330

331 332 333
    if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
        (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
        av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
334
        avformat_close_input(&cat->avf);
335 336 337 338 339 340 341
        return ret;
    }
    cat->cur_file = file;
    if (file->start_time == AV_NOPTS_VALUE)
        file->start_time = !fileno ? 0 :
                           cat->files[fileno - 1].start_time +
                           cat->files[fileno - 1].duration;
342
    file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
343
    file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
344 345
    if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
        file->duration = file->outpoint - file->file_inpoint;
346 347 348 349 350 351 352

    if (cat->segment_time_metadata) {
        av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
        if (file->duration != AV_NOPTS_VALUE)
            av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
    }

353 354
    if ((ret = match_streams(avf)) < 0)
        return ret;
355 356 357 358
    if (file->inpoint != AV_NOPTS_VALUE) {
       if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
           return ret;
    }
359 360 361 362 363 364
    return 0;
}

static int concat_read_close(AVFormatContext *avf)
{
    ConcatContext *cat = avf->priv_data;
365
    unsigned i, j;
366

367
    for (i = 0; i < cat->nb_files; i++) {
368
        av_freep(&cat->files[i].url);
369
        for (j = 0; j < cat->files[i].nb_streams; j++) {
370 371 372 373 374
            if (cat->files[i].streams[j].avctx)
                avcodec_free_context(&cat->files[i].streams[j].avctx);
            if (cat->files[i].streams[j].bsf)
                av_bitstream_filter_close(cat->files[i].streams[j].bsf);
        }
375
        av_freep(&cat->files[i].streams);
376
        av_dict_free(&cat->files[i].metadata);
377
    }
378 379
    if (cat->avf)
        avformat_close_input(&cat->avf);
380 381 382 383 384 385 386 387 388 389 390 391
    av_freep(&cat->files);
    return 0;
}

static int concat_read_header(AVFormatContext *avf)
{
    ConcatContext *cat = avf->priv_data;
    uint8_t buf[4096];
    uint8_t *cursor, *keyword;
    int ret, line = 0, i;
    unsigned nb_files_alloc = 0;
    ConcatFile *file = NULL;
392
    int64_t time = 0;
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

    while (1) {
        if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
            break;
        line++;
        cursor = buf;
        keyword = get_keyword(&cursor);
        if (!*keyword || *keyword == '#')
            continue;

        if (!strcmp(keyword, "file")) {
            char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
            if (!filename) {
                av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
                FAIL(AVERROR_INVALIDDATA);
            }
            if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
410
                goto fail;
411
        } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
412 413 414
            char *dur_str = get_keyword(&cursor);
            int64_t dur;
            if (!file) {
415 416
                av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
                       line, keyword);
417 418 419
                FAIL(AVERROR_INVALIDDATA);
            }
            if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
420 421
                av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
                       line, keyword, dur_str);
422
                goto fail;
423
            }
424 425 426 427
            if (!strcmp(keyword, "duration"))
                file->duration = dur;
            else if (!strcmp(keyword, "inpoint"))
                file->inpoint = dur;
428 429
            else if (!strcmp(keyword, "outpoint"))
                file->outpoint = dur;
430 431
        } else if (!strcmp(keyword, "file_packet_metadata")) {
            char *metadata;
432 433 434 435 436
            if (!file) {
                av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
                       line, keyword);
                FAIL(AVERROR_INVALIDDATA);
            }
437 438 439 440 441
            metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
            if (!metadata) {
                av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
                FAIL(AVERROR_INVALIDDATA);
            }
442 443 444 445 446 447
            if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
                av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
                av_freep(&metadata);
                FAIL(AVERROR_INVALIDDATA);
            }
            av_freep(&metadata);
448 449 450 451 452 453 454 455 456 457 458
        } else if (!strcmp(keyword, "stream")) {
            if (!avformat_new_stream(avf, NULL))
                FAIL(AVERROR(ENOMEM));
        } else if (!strcmp(keyword, "exact_stream_id")) {
            if (!avf->nb_streams) {
                av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
                       line);
                FAIL(AVERROR_INVALIDDATA);
            }
            avf->streams[avf->nb_streams - 1]->id =
                strtol(get_keyword(&cursor), NULL, 0);
459 460 461 462 463 464 465 466 467
        } else if (!strcmp(keyword, "ffconcat")) {
            char *ver_kw  = get_keyword(&cursor);
            char *ver_val = get_keyword(&cursor);
            if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
                av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
                FAIL(AVERROR_INVALIDDATA);
            }
            if (cat->safe < 0)
                cat->safe = 1;
468 469 470 471 472 473 474
        } else {
            av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
                   line, keyword);
            FAIL(AVERROR_INVALIDDATA);
        }
    }
    if (ret < 0)
475
        goto fail;
476 477
    if (!cat->nb_files)
        FAIL(AVERROR_INVALIDDATA);
478

479 480 481 482 483
    for (i = 0; i < cat->nb_files; i++) {
        if (cat->files[i].start_time == AV_NOPTS_VALUE)
            cat->files[i].start_time = time;
        else
            time = cat->files[i].start_time;
484 485 486 487 488
        if (cat->files[i].duration == AV_NOPTS_VALUE) {
            if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
                break;
            cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
        }
489 490
        time += cat->files[i].duration;
    }
491
    if (i == cat->nb_files) {
492
        avf->duration = time;
493 494
        cat->seekable = 1;
    }
495

496 497
    cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
                                               MATCH_ONE_TO_ONE;
498
    if ((ret = open_file(avf, 0)) < 0)
499
        goto fail;
500 501 502 503 504 505 506 507 508 509 510 511
    return 0;

fail:
    concat_read_close(avf);
    return ret;
}

static int open_next_file(AVFormatContext *avf)
{
    ConcatContext *cat = avf->priv_data;
    unsigned fileno = cat->cur_file - cat->files;

512 513
    if (cat->cur_file->duration == AV_NOPTS_VALUE)
        cat->cur_file->duration = cat->avf->duration - (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
514

515 516
    if (++fileno >= cat->nb_files) {
        cat->eof = 1;
517
        return AVERROR_EOF;
518
    }
519 520 521
    return open_file(avf, fileno);
}

522 523 524 525 526 527 528 529 530 531
static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
{
    AVStream *st = avf->streams[cs->out_stream_index];
    AVBitStreamFilterContext *bsf;
    AVPacket pkt2;
    int ret;

    av_assert0(cs->out_stream_index >= 0);
    for (bsf = cs->bsf; bsf; bsf = bsf->next) {
        pkt2 = *pkt;
532 533

        ret = av_bitstream_filter_filter(bsf, cs->avctx, NULL,
534 535 536 537 538 539 540
                                         &pkt2.data, &pkt2.size,
                                         pkt->data, pkt->size,
                                         !!(pkt->flags & AV_PKT_FLAG_KEY));
        if (ret < 0) {
            av_packet_unref(pkt);
            return ret;
        }
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

        if (cs->avctx->extradata_size > st->codecpar->extradata_size) {
            int eret;
            if (st->codecpar->extradata)
                av_freep(&st->codecpar->extradata);

            eret = ff_alloc_extradata(st->codecpar, cs->avctx->extradata_size);
            if (eret < 0) {
                av_packet_unref(pkt);
                return AVERROR(ENOMEM);
            }
            st->codecpar->extradata_size = cs->avctx->extradata_size;
            memcpy(st->codecpar->extradata, cs->avctx->extradata, cs->avctx->extradata_size);
        }

556 557 558 559 560 561 562 563 564
        av_assert0(pkt2.buf);
        if (ret == 0 && pkt2.data != pkt->data) {
            if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
                av_free(pkt2.data);
                return ret;
            }
            ret = 1;
        }
        if (ret > 0) {
565
            av_packet_unref(pkt);
566 567 568 569 570 571 572 573 574 575 576 577
            pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
                                        av_buffer_default_free, NULL, 0);
            if (!pkt2.buf) {
                av_free(pkt2.data);
                return AVERROR(ENOMEM);
            }
        }
        *pkt = pkt2;
    }
    return 0;
}

578 579 580 581 582 583 584 585 586 587
/* Returns true if the packet dts is greater or equal to the specified outpoint. */
static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
{
    if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
        return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
                             cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
    }
    return 0;
}

588 589 590 591
static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
{
    ConcatContext *cat = avf->priv_data;
    int ret;
592
    int64_t delta;
593
    ConcatStream *cs;
594
    AVStream *st;
595

596 597 598
    if (cat->eof)
        return AVERROR_EOF;

599 600 601
    if (!cat->avf)
        return AVERROR(EIO);

602
    while (1) {
603
        ret = av_read_frame(cat->avf, pkt);
604
        if (ret == AVERROR_EOF) {
605 606 607 608 609 610
            if ((ret = open_next_file(avf)) < 0)
                return ret;
            continue;
        }
        if (ret < 0)
            return ret;
611 612 613 614
        if ((ret = match_streams(avf)) < 0) {
            av_packet_unref(pkt);
            return ret;
        }
615 616 617 618 619 620
        if (packet_after_outpoint(cat, pkt)) {
            av_packet_unref(pkt);
            if ((ret = open_next_file(avf)) < 0)
                return ret;
            continue;
        }
621 622 623 624 625 626
        cs = &cat->cur_file->streams[pkt->stream_index];
        if (cs->out_stream_index < 0) {
            av_packet_unref(pkt);
            continue;
        }
        pkt->stream_index = cs->out_stream_index;
627
        break;
628
    }
629 630
    if ((ret = filter_packet(avf, cs, pkt)))
        return ret;
631

632 633 634 635 636 637
    st = cat->avf->streams[pkt->stream_index];
    av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
           (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
           av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
           av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));

638
    delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
639 640 641 642 643 644
                         AV_TIME_BASE_Q,
                         cat->avf->streams[pkt->stream_index]->time_base);
    if (pkt->pts != AV_NOPTS_VALUE)
        pkt->pts += delta;
    if (pkt->dts != AV_NOPTS_VALUE)
        pkt->dts += delta;
645 646 647
    av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
           av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
           av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
648 649 650 651 652 653 654 655 656 657 658 659 660
    if (cat->cur_file->metadata) {
        uint8_t* metadata;
        int metadata_len;
        char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
        if (!packed_metadata)
            return AVERROR(ENOMEM);
        if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
            av_freep(&packed_metadata);
            return AVERROR(ENOMEM);
        }
        memcpy(metadata, packed_metadata, metadata_len);
        av_freep(&packed_metadata);
    }
661 662 663
    return ret;
}

664 665 666 667 668 669 670 671 672 673 674 675 676 677
static void rescale_interval(AVRational tb_in, AVRational tb_out,
                             int64_t *min_ts, int64_t *ts, int64_t *max_ts)
{
    *ts     = av_rescale_q    (*    ts, tb_in, tb_out);
    *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
                               AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);
    *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
                               AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
}

static int try_seek(AVFormatContext *avf, int stream,
                    int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
{
    ConcatContext *cat = avf->priv_data;
678
    int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
679 680 681 682 683 684 685 686 687 688 689 690 691 692

    ts -= t0;
    min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
    max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
    if (stream >= 0) {
        if (stream >= cat->avf->nb_streams)
            return AVERROR(EIO);
        rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
                         &min_ts, &ts, &max_ts);
    }
    return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
}

static int real_seek(AVFormatContext *avf, int stream,
693
                     int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
{
    ConcatContext *cat = avf->priv_data;
    int ret, left, right;

    if (stream >= 0) {
        if (stream >= avf->nb_streams)
            return AVERROR(EINVAL);
        rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
                         &min_ts, &ts, &max_ts);
    }

    left  = 0;
    right = cat->nb_files;
    while (right - left > 1) {
        int mid = (left + right) / 2;
        if (ts < cat->files[mid].start_time)
            right = mid;
        else
            left  = mid;
    }

715 716 717 718 719 720
    if (cat->cur_file != &cat->files[left]) {
        if ((ret = open_file(avf, left)) < 0)
            return ret;
    } else {
        cat->avf = cur_avf;
    }
721 722

    ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
723
    if (ret < 0 &&
724 725
        left < cat->nb_files - 1 &&
        cat->files[left + 1].start_time < max_ts) {
726 727
        if (cat->cur_file == &cat->files[left])
            cat->avf = NULL;
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
        if ((ret = open_file(avf, left + 1)) < 0)
            return ret;
        ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
    }
    return ret;
}

static int concat_seek(AVFormatContext *avf, int stream,
                       int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
{
    ConcatContext *cat = avf->priv_data;
    ConcatFile *cur_file_saved = cat->cur_file;
    AVFormatContext *cur_avf_saved = cat->avf;
    int ret;

    if (!cat->seekable)
        return AVERROR(ESPIPE); /* XXX: can we use it? */
    if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
        return AVERROR(ENOSYS);
    cat->avf = NULL;
748 749 750 751 752
    if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags, cur_avf_saved)) < 0) {
        if (cat->cur_file != cur_file_saved) {
            if (cat->avf)
                avformat_close_input(&cat->avf);
        }
753 754 755
        cat->avf      = cur_avf_saved;
        cat->cur_file = cur_file_saved;
    } else {
756 757 758
        if (cat->cur_file != cur_file_saved) {
            avformat_close_input(&cur_avf_saved);
        }
759
        cat->eof = 0;
760 761 762 763
    }
    return ret;
}

764 765 766 767 768
#define OFFSET(x) offsetof(ConcatContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM

static const AVOption options[] = {
    { "safe", "enable safe mode",
769
      OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
770
    { "auto_convert", "automatically convert bitstream format",
771
      OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
772 773
    { "segment_time_metadata", "output file segment start time and duration as packet metadata",
      OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
774 775 776 777 778 779 780 781 782 783 784
    { NULL }
};

static const AVClass concat_class = {
    .class_name = "concat demuxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};


785 786 787 788 789 790 791 792
AVInputFormat ff_concat_demuxer = {
    .name           = "concat",
    .long_name      = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
    .priv_data_size = sizeof(ConcatContext),
    .read_probe     = concat_probe,
    .read_header    = concat_read_header,
    .read_packet    = concat_read_packet,
    .read_close     = concat_read_close,
793
    .read_seek2     = concat_seek,
794
    .priv_class     = &concat_class,
795
};