ismindex.c 28.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * Copyright (c) 2012 Martin Storsjo
 *
 * This file is part of Libav.
 *
 * Libav 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.
 *
 * Libav 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 Libav; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/*
 * To create a simple file for smooth streaming:
 * avconv <normal input/transcoding options> -movflags frag_keyframe foo.ismv
 * ismindex -n foo foo.ismv
 * This step creates foo.ism and foo.ismc that is required by IIS for
 * serving it.
 *
28 29 30
 * With -ismf, it also creates foo.ismf, which maps fragment names to
 * start-end offsets in the ismv, for use in your own streaming server.
 *
31 32 33 34
 * By adding -path-prefix path/, the produced foo.ism will refer to the
 * files foo.ismv as "path/foo.ismv" - the prefix for the generated ismc
 * file can be set with the -ismc-prefix option similarly.
 *
35 36 37 38 39
 * To pre-split files for serving as static files by a web server without
 * any extra server support, create the ismv file as above, and split it:
 * ismindex -split foo.ismv
 * This step creates a file Manifest and directories QualityLevel(...),
 * that can be read directly by a smooth streaming player.
40 41 42 43 44
 *
 * The -output dir option can be used to request that output files
 * (both .ism/.ismc, or Manifest/QualityLevels* when splitting)
 * should be written to this directory instead of in the current directory.
 * (The directory itself isn't created if it doesn't already exist.)
45 46 47 48
 */

#include <stdio.h>
#include <string.h>
49

50
#include "libavformat/avformat.h"
51
#include "libavformat/isom.h"
52
#include "libavformat/os_support.h"
53 54 55 56 57
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"

static int usage(const char *argv0, int ret)
{
58
    fprintf(stderr, "%s [-split] [-ismf] [-n basename] [-path-prefix prefix] "
59
                    "[-ismc-prefix prefix] [-output dir] file1 [file2] ...\n", argv0);
60 61 62 63 64 65
    return ret;
}

struct MoofOffset {
    int64_t time;
    int64_t offset;
66
    int64_t duration;
67 68
};

69
struct Track {
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    const char *name;
    int64_t duration;
    int bitrate;
    int track_id;
    int is_audio, is_video;
    int width, height;
    int chunks;
    int sample_rate, channels;
    uint8_t *codec_private;
    int codec_private_size;
    struct MoofOffset *offsets;
    int timescale;
    const char *fourcc;
    int blocksize;
    int tag;
};

87 88
struct Tracks {
    int nb_tracks;
89
    int64_t duration;
90 91 92
    struct Track **tracks;
    int video_track, audio_track;
    int nb_video_tracks, nb_audio_tracks;
93 94
};

95 96 97 98 99 100 101 102 103 104 105 106
static int expect_tag(int32_t got_tag, int32_t expected_tag) {
    if (got_tag != expected_tag) {
        char got_tag_str[4], expected_tag_str[4];
        AV_WB32(got_tag_str, got_tag);
        AV_WB32(expected_tag_str, expected_tag);
        fprintf(stderr, "wanted tag %.4s, got %.4s\n", expected_tag_str,
                got_tag_str);
        return -1;
    }
    return 0;
}

107 108 109 110 111
static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
{
    int32_t size, tag;

    size = avio_rb32(in);
112
    tag  = avio_rb32(in);
113 114
    avio_wb32(out, size);
    avio_wb32(out, tag);
115
    if (expect_tag(tag, tag_name) != 0)
116 117 118 119 120
        return -1;
    size -= 8;
    while (size > 0) {
        char buf[1024];
        int len = FFMIN(sizeof(buf), size);
121 122 123
        int got;
        if ((got = avio_read(in, buf, len)) != len) {
            fprintf(stderr, "short read, wanted %d, got %d\n", len, got);
124
            break;
125
        }
126 127 128 129 130 131
        avio_write(out, buf, len);
        size -= len;
    }
    return 0;
}

132 133 134 135 136 137 138 139 140 141 142 143 144
static int skip_tag(AVIOContext *in, int32_t tag_name)
{
    int64_t pos = avio_tell(in);
    int32_t size, tag;

    size = avio_rb32(in);
    tag  = avio_rb32(in);
    if (expect_tag(tag, tag_name) != 0)
        return -1;
    avio_seek(in, pos + size, SEEK_SET);
    return 0;
}

145 146 147 148 149
static int write_fragment(const char *filename, AVIOContext *in)
{
    AVIOContext *out = NULL;
    int ret;

150 151 152 153
    if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0) {
        char errbuf[100];
        av_strerror(ret, errbuf, sizeof(errbuf));
        fprintf(stderr, "Unable to open %s: %s\n", filename, errbuf);
154
        return ret;
155 156 157 158
    }
    ret = copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
    if (!ret)
        ret = copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
159 160 161 162 163 164 165

    avio_flush(out);
    avio_close(out);

    return ret;
}

166
static int skip_fragment(AVIOContext *in)
167
{
168 169 170 171 172 173
    int ret;
    ret = skip_tag(in, MKBETAG('m', 'o', 'o', 'f'));
    if (!ret)
        ret = skip_tag(in, MKBETAG('m', 'd', 'a', 't'));
    return ret;
}
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
static int write_fragments(struct Tracks *tracks, int start_index,
                           AVIOContext *in, const char *basename,
                           int split, int ismf, const char* output_prefix)
{
    char dirname[2048], filename[2048], idxname[2048];
    int i, j, ret = 0, fragment_ret;
    FILE* out = NULL;

    if (ismf) {
        snprintf(idxname, sizeof(idxname), "%s%s.ismf", output_prefix, basename);
        out = fopen(idxname, "w");
        if (!out) {
            ret = AVERROR(errno);
            perror(idxname);
            goto fail;
        }
    }
192 193 194
    for (i = start_index; i < tracks->nb_tracks; i++) {
        struct Track *track = tracks->tracks[i];
        const char *type    = track->is_video ? "video" : "audio";
195
        snprintf(dirname, sizeof(dirname), "%sQualityLevels(%d)", output_prefix, track->bitrate);
196 197 198 199 200 201 202
        if (split) {
            if (mkdir(dirname, 0777) == -1 && errno != EEXIST) {
                ret = AVERROR(errno);
                perror(dirname);
                goto fail;
            }
        }
203
        for (j = 0; j < track->chunks; j++) {
204
            snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
205 206
                     dirname, type, track->offsets[j].time);
            avio_seek(in, track->offsets[j].offset, SEEK_SET);
207 208 209 210 211 212 213 214 215 216 217 218 219
            if (ismf)
                fprintf(out, "%s %"PRId64, filename, avio_tell(in));
            if (split)
                fragment_ret = write_fragment(filename, in);
            else
                fragment_ret = skip_fragment(in);
            if (ismf)
                fprintf(out, " %"PRId64"\n", avio_tell(in));
            if (fragment_ret != 0) {
                fprintf(stderr, "failed fragment %d in track %d (%s)\n", j,
                        track->track_id, track->name);
                ret = fragment_ret;
            }
220 221
        }
    }
222 223 224 225
fail:
    if (out)
        fclose(out);
    return ret;
226 227
}

228 229
static int64_t read_trun_duration(AVIOContext *in, int default_duration,
                                  int64_t end)
230 231 232 233 234 235 236
{
    int64_t ret = 0;
    int64_t pos;
    int flags, i;
    int entries;
    avio_r8(in); /* version */
    flags = avio_rb24(in);
237
    if (default_duration <= 0 && !(flags & MOV_TRUN_SAMPLE_DURATION)) {
238 239 240 241 242 243 244 245 246 247
        fprintf(stderr, "No sample duration in trun flags\n");
        return -1;
    }
    entries = avio_rb32(in);

    if (flags & MOV_TRUN_DATA_OFFSET)        avio_rb32(in);
    if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_rb32(in);

    pos = avio_tell(in);
    for (i = 0; i < entries && pos < end; i++) {
248
        int sample_duration = default_duration;
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(in);
        if (flags & MOV_TRUN_SAMPLE_SIZE)     avio_rb32(in);
        if (flags & MOV_TRUN_SAMPLE_FLAGS)    avio_rb32(in);
        if (flags & MOV_TRUN_SAMPLE_CTS)      avio_rb32(in);
        if (sample_duration < 0) {
            fprintf(stderr, "Negative sample duration %d\n", sample_duration);
            return -1;
        }
        ret += sample_duration;
        pos = avio_tell(in);
    }

    return ret;
}

static int64_t read_moof_duration(AVIOContext *in, int64_t offset)
{
    int64_t ret = -1;
    int32_t moof_size, size, tag;
    int64_t pos = 0;
269
    int default_duration = 0;
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

    avio_seek(in, offset, SEEK_SET);
    moof_size = avio_rb32(in);
    tag  = avio_rb32(in);
    if (expect_tag(tag, MKBETAG('m', 'o', 'o', 'f')) != 0)
        goto fail;
    while (pos < offset + moof_size) {
        pos = avio_tell(in);
        size = avio_rb32(in);
        tag  = avio_rb32(in);
        if (tag == MKBETAG('t', 'r', 'a', 'f')) {
            int64_t traf_pos = pos;
            int64_t traf_size = size;
            while (pos < traf_pos + traf_size) {
                pos = avio_tell(in);
                size = avio_rb32(in);
                tag  = avio_rb32(in);
287 288 289 290 291 292 293 294 295 296 297 298
                if (tag == MKBETAG('t', 'f', 'h', 'd')) {
                    int flags = 0;
                    avio_r8(in); /* version */
                    flags = avio_rb24(in);
                    avio_rb32(in); /* track_id */
                    if (flags & MOV_TFHD_BASE_DATA_OFFSET)
                        avio_rb64(in);
                    if (flags & MOV_TFHD_STSD_ID)
                        avio_rb32(in);
                    if (flags & MOV_TFHD_DEFAULT_DURATION)
                        default_duration = avio_rb32(in);
                }
299
                if (tag == MKBETAG('t', 'r', 'u', 'n')) {
300 301
                    return read_trun_duration(in, default_duration,
                                              pos + size);
302 303 304 305 306 307 308 309 310 311 312 313 314 315
                }
                avio_seek(in, pos + size, SEEK_SET);
            }
            fprintf(stderr, "Couldn't find trun\n");
            goto fail;
        }
        avio_seek(in, pos + size, SEEK_SET);
    }
    fprintf(stderr, "Couldn't find traf\n");

fail:
    return ret;
}

316
static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
317 318 319
{
    int ret = AVERROR_EOF, track_id;
    int version, fieldlength, i, j;
320
    int64_t pos   = avio_tell(f);
321
    uint32_t size = avio_rb32(f);
322
    struct Track *track = NULL;
323 324 325 326 327 328

    if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
        goto fail;
    version = avio_r8(f);
    avio_rb24(f);
    track_id = avio_rb32(f); /* track id */
329 330 331 332
    for (i = start_index; i < tracks->nb_tracks && !track; i++)
        if (tracks->tracks[i]->track_id == track_id)
            track = tracks->tracks[i];
    if (!track) {
333 334 335 336 337
        /* Ok, continue parsing the next atom */
        ret = 0;
        goto fail;
    }
    fieldlength = avio_rb32(f);
338 339 340
    track->chunks  = avio_rb32(f);
    track->offsets = av_mallocz(sizeof(*track->offsets) * track->chunks);
    if (!track->offsets) {
341 342 343
        ret = AVERROR(ENOMEM);
        goto fail;
    }
344
    // The duration here is always the difference between consecutive
345
    // start times.
346
    for (i = 0; i < track->chunks; i++) {
347
        if (version == 1) {
348 349
            track->offsets[i].time   = avio_rb64(f);
            track->offsets[i].offset = avio_rb64(f);
350
        } else {
351 352
            track->offsets[i].time   = avio_rb32(f);
            track->offsets[i].offset = avio_rb32(f);
353 354 355 356 357 358 359 360
        }
        for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
            avio_r8(f);
        for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
            avio_r8(f);
        for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
            avio_r8(f);
        if (i > 0)
361 362
            track->offsets[i - 1].duration = track->offsets[i].time -
                                             track->offsets[i - 1].time;
363
    }
364 365 366
    if (track->chunks > 0) {
        track->offsets[track->chunks - 1].duration = track->offsets[0].time +
                                                     track->duration -
367
                                                     track->offsets[track->chunks - 1].time;
368 369 370 371 372 373 374 375 376 377 378
    }
    // Now try and read the actual durations from the trun sample data.
    for (i = 0; i < track->chunks; i++) {
        int64_t duration = read_moof_duration(f, track->offsets[i].offset);
        if (duration > 0 && abs(duration - track->offsets[i].duration) > 3) {
            // 3 allows for integer duration to drift a few units,
            // e.g., for 1/3 durations
            track->offsets[i].duration = duration;
        }
    }
    if (track->chunks > 0) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        if (track->offsets[track->chunks - 1].duration <= 0) {
            fprintf(stderr, "Calculated last chunk duration for track %d "
                    "was non-positive (%"PRId64"), probably due to missing "
                    "fragments ", track->track_id,
                    track->offsets[track->chunks - 1].duration);
            if (track->chunks > 1) {
                track->offsets[track->chunks - 1].duration =
                    track->offsets[track->chunks - 2].duration;
            } else {
                track->offsets[track->chunks - 1].duration = 1;
            }
            fprintf(stderr, "corrected to %"PRId64"\n",
                    track->offsets[track->chunks - 1].duration);
            track->duration = track->offsets[track->chunks - 1].time +
                              track->offsets[track->chunks - 1].duration -
                              track->offsets[0].time;
            fprintf(stderr, "Track duration corrected to %"PRId64"\n",
                    track->duration);
        }
    }
399
    ret = 0;
400

401 402 403 404 405
fail:
    avio_seek(f, pos + size, SEEK_SET);
    return ret;
}

406
static int read_mfra(struct Tracks *tracks, int start_index,
407 408
                     const char *file, int split, int ismf,
                     const char *basename, const char* output_prefix)
409 410
{
    int err = 0;
411
    const char* err_str = "";
412 413 414 415 416 417 418 419
    AVIOContext *f = NULL;
    int32_t mfra_size;

    if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
        goto fail;
    avio_seek(f, avio_size(f) - 4, SEEK_SET);
    mfra_size = avio_rb32(f);
    avio_seek(f, -mfra_size, SEEK_CUR);
420 421
    if (avio_rb32(f) != mfra_size) {
        err = AVERROR_INVALIDDATA;
422
        err_str = "mfra size mismatch";
423
        goto fail;
424 425 426
    }
    if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
        err = AVERROR_INVALIDDATA;
427
        err_str = "mfra tag mismatch";
428
        goto fail;
429
    }
430
    while (!read_tfra(tracks, start_index, f)) {
431 432 433
        /* Empty */
    }

434 435 436 437
    if (split || ismf)
        err = write_fragments(tracks, start_index, f, basename, split, ismf,
                              output_prefix);
    err_str = "error in write_fragments";
438 439 440 441

fail:
    if (f)
        avio_close(f);
442
    if (err)
443
        fprintf(stderr, "Unable to read the MFRA atom in %s (%s)\n", file, err_str);
444 445 446
    return err;
}

447
static int get_private_data(struct Track *track, AVCodecContext *codec)
448
{
449 450 451
    track->codec_private_size = codec->extradata_size;
    track->codec_private      = av_mallocz(codec->extradata_size);
    if (!track->codec_private)
452
        return AVERROR(ENOMEM);
453
    memcpy(track->codec_private, codec->extradata, codec->extradata_size);
454 455 456
    return 0;
}

457
static int get_video_private_data(struct Track *track, AVCodecContext *codec)
458 459 460
{
    AVIOContext *io = NULL;
    uint16_t sps_size, pps_size;
461
    int err;
462

463
    if (codec->codec_id == AV_CODEC_ID_VC1)
464
        return get_private_data(track, codec);
465

466 467 468
    if ((err = avio_open_dyn_buf(&io)) < 0)
        goto fail;
    err = AVERROR(EINVAL);
469 470 471 472 473 474 475 476 477 478 479 480 481
    if (codec->extradata_size < 11 || codec->extradata[0] != 1)
        goto fail;
    sps_size = AV_RB16(&codec->extradata[6]);
    if (11 + sps_size > codec->extradata_size)
        goto fail;
    avio_wb32(io, 0x00000001);
    avio_write(io, &codec->extradata[8], sps_size);
    pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
    if (11 + sps_size + pps_size > codec->extradata_size)
        goto fail;
    avio_wb32(io, 0x00000001);
    avio_write(io, &codec->extradata[11 + sps_size], pps_size);
    err = 0;
482

483
fail:
484
    track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
485 486 487
    return err;
}

488
static int handle_file(struct Tracks *tracks, const char *file, int split,
489 490
                       int ismf, const char *basename,
                       const char* output_prefix)
491 492
{
    AVFormatContext *ctx = NULL;
493
    int err = 0, i, orig_tracks = tracks->nb_tracks;
494
    char errbuf[50], *ptr;
495
    struct Track *track;
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

    err = avformat_open_input(&ctx, file, NULL, NULL);
    if (err < 0) {
        av_strerror(err, errbuf, sizeof(errbuf));
        fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
        return 1;
    }

    err = avformat_find_stream_info(ctx, NULL);
    if (err < 0) {
        av_strerror(err, errbuf, sizeof(errbuf));
        fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
        goto fail;
    }

    if (ctx->nb_streams < 1) {
        fprintf(stderr, "No streams found in %s\n", file);
        goto fail;
    }

    for (i = 0; i < ctx->nb_streams; i++) {
517
        struct Track **temp;
518
        AVStream *st = ctx->streams[i];
519 520

        if (st->codec->bit_rate == 0) {
521 522
            fprintf(stderr, "Skipping track %d in %s as it has zero bitrate\n",
                    st->id, file);
523 524 525
            continue;
        }

526
        track = av_mallocz(sizeof(*track));
527 528 529 530 531 532 533 534 535 536 537 538
        if (!track) {
            err = AVERROR(ENOMEM);
            goto fail;
        }
        temp = av_realloc(tracks->tracks,
                          sizeof(*tracks->tracks) * (tracks->nb_tracks + 1));
        if (!temp) {
            av_free(track);
            err = AVERROR(ENOMEM);
            goto fail;
        }
        tracks->tracks = temp;
539
        tracks->tracks[tracks->nb_tracks] = track;
540

541
        track->name = file;
542
        if ((ptr = strrchr(file, '/')))
543
            track->name = ptr + 1;
544

545 546 547
        track->bitrate   = st->codec->bit_rate;
        track->track_id  = st->id;
        track->timescale = st->time_base.den;
548
        track->duration  = st->duration;
549 550
        track->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
        track->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
551

552
        if (!track->is_audio && !track->is_video) {
553 554
            fprintf(stderr,
                    "Track %d in %s is neither video nor audio, skipping\n",
555 556
                    track->track_id, file);
            av_freep(&tracks->tracks[tracks->nb_tracks]);
557 558 559
            continue;
        }

560 561 562 563
        tracks->duration = FFMAX(tracks->duration,
                                 av_rescale_rnd(track->duration, AV_TIME_BASE,
                                                track->timescale, AV_ROUND_UP));

564 565 566 567 568 569
        if (track->is_audio) {
            if (tracks->audio_track < 0)
                tracks->audio_track = tracks->nb_tracks;
            tracks->nb_audio_tracks++;
            track->channels    = st->codec->channels;
            track->sample_rate = st->codec->sample_rate;
570
            if (st->codec->codec_id == AV_CODEC_ID_AAC) {
571 572 573
                track->fourcc    = "AACL";
                track->tag       = 255;
                track->blocksize = 4;
574
            } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
575 576 577
                track->fourcc    = "WMAP";
                track->tag       = st->codec->codec_tag;
                track->blocksize = st->codec->block_align;
578
            }
579
            get_private_data(track, st->codec);
580
        }
581 582 583 584 585 586
        if (track->is_video) {
            if (tracks->video_track < 0)
                tracks->video_track = tracks->nb_tracks;
            tracks->nb_video_tracks++;
            track->width  = st->codec->width;
            track->height = st->codec->height;
587
            if (st->codec->codec_id == AV_CODEC_ID_H264)
588
                track->fourcc = "H264";
589
            else if (st->codec->codec_id == AV_CODEC_ID_VC1)
590 591
                track->fourcc = "WVC1";
            get_video_private_data(track, st->codec);
592 593
        }

594
        tracks->nb_tracks++;
595 596 597 598
    }

    avformat_close_input(&ctx);

599 600
    err = read_mfra(tracks, orig_tracks, file, split, ismf, basename,
                    output_prefix);
601 602 603 604 605 606 607

fail:
    if (ctx)
        avformat_close_input(&ctx);
    return err;
}

608 609 610
static void output_server_manifest(struct Tracks *tracks, const char *basename,
                                   const char *output_prefix,
                                   const char *path_prefix,
611
                                   const char *ismc_prefix)
612 613 614 615 616
{
    char filename[1000];
    FILE *out;
    int i;

617
    snprintf(filename, sizeof(filename), "%s%s.ism", output_prefix, basename);
618 619 620 621 622 623 624 625 626
    out = fopen(filename, "w");
    if (!out) {
        perror(filename);
        return;
    }
    fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
    fprintf(out, "\t<head>\n");
    fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
627
                 "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
628 629 630
    fprintf(out, "\t</head>\n");
    fprintf(out, "\t<body>\n");
    fprintf(out, "\t\t<switch>\n");
631 632 633
    for (i = 0; i < tracks->nb_tracks; i++) {
        struct Track *track = tracks->tracks[i];
        const char *type    = track->is_video ? "video" : "audio";
634 635
        fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
                type, path_prefix, track->name, track->bitrate);
636
        fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
637
                     "valueType=\"data\" />\n", track->track_id);
638 639 640 641 642 643 644 645
        fprintf(out, "\t\t\t</%s>\n", type);
    }
    fprintf(out, "\t\t</switch>\n");
    fprintf(out, "\t</body>\n");
    fprintf(out, "</smil>\n");
    fclose(out);
}

646 647 648 649
static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
                               const char *type)
{
    int i, j;
650
    int64_t pos = 0;
651
    struct Track *track = tracks->tracks[main];
652 653
    int should_print_time_mismatch = 1;

654 655
    for (i = 0; i < track->chunks; i++) {
        for (j = main + 1; j < tracks->nb_tracks; j++) {
656 657 658 659 660 661 662 663 664 665 666 667 668
            if (tracks->tracks[j]->is_audio == track->is_audio) {
                if (track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration) {
                    fprintf(stderr, "Mismatched duration of %s chunk %d in %s (%d) and %s (%d)\n",
                            type, i, track->name, main, tracks->tracks[j]->name, j);
                    should_print_time_mismatch = 1;
                }
                if (track->offsets[i].time != tracks->tracks[j]->offsets[i].time) {
                    if (should_print_time_mismatch)
                        fprintf(stderr, "Mismatched (start) time of %s chunk %d in %s (%d) and %s (%d)\n",
                                type, i, track->name, main, tracks->tracks[j]->name, j);
                    should_print_time_mismatch = 0;
                }
            }
669
        }
670
        fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" ",
671
                i, track->offsets[i].duration);
672 673 674 675 676 677
        if (pos != track->offsets[i].time) {
            fprintf(out, "t=\"%"PRId64"\" ", track->offsets[i].time);
            pos = track->offsets[i].time;
        }
        pos += track->offsets[i].duration;
        fprintf(out, "/>\n");
678 679 680
    }
}

681 682
static void output_client_manifest(struct Tracks *tracks, const char *basename,
                                   const char *output_prefix, int split)
683 684 685 686 687 688
{
    char filename[1000];
    FILE *out;
    int i, j;

    if (split)
689
        snprintf(filename, sizeof(filename), "%sManifest", output_prefix);
690
    else
691
        snprintf(filename, sizeof(filename), "%s%s.ismc", output_prefix, basename);
692 693 694 695 696 697 698
    out = fopen(filename, "w");
    if (!out) {
        perror(filename);
        return;
    }
    fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
699 700 701 702
                 "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
    if (tracks->video_track >= 0) {
        struct Track *track = tracks->tracks[tracks->video_track];
        struct Track *first_track = track;
703
        int index = 0;
704 705 706 707
        fprintf(out,
                "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
                "Chunks=\"%d\" "
                "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
708 709 710 711
                tracks->nb_video_tracks, track->chunks);
        for (i = 0; i < tracks->nb_tracks; i++) {
            track = tracks->tracks[i];
            if (!track->is_video)
712
                continue;
713 714 715 716
            fprintf(out,
                    "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
                    "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
                    "CodecPrivateData=\"",
717 718 719
                    index, track->bitrate, track->fourcc, track->width, track->height);
            for (j = 0; j < track->codec_private_size; j++)
                fprintf(out, "%02X", track->codec_private[j]);
720 721
            fprintf(out, "\" />\n");
            index++;
722
            if (track->chunks != first_track->chunks)
723 724
                fprintf(stderr, "Mismatched number of video chunks in %s (id: %d, chunks %d) and %s (id: %d, chunks %d)\n",
                        track->name, track->track_id, track->chunks, first_track->name, first_track->track_id, first_track->chunks);
725
        }
726
        print_track_chunks(out, tracks, tracks->video_track, "video");
727 728
        fprintf(out, "\t</StreamIndex>\n");
    }
729 730 731
    if (tracks->audio_track >= 0) {
        struct Track *track = tracks->tracks[tracks->audio_track];
        struct Track *first_track = track;
732
        int index = 0;
733 734 735 736
        fprintf(out,
                "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
                "Chunks=\"%d\" "
                "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
737 738 739 740
                tracks->nb_audio_tracks, track->chunks);
        for (i = 0; i < tracks->nb_tracks; i++) {
            track = tracks->tracks[i];
            if (!track->is_audio)
741
                continue;
742 743 744 745 746
            fprintf(out,
                    "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
                    "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
                    "BitsPerSample=\"16\" PacketSize=\"%d\" "
                    "AudioTag=\"%d\" CodecPrivateData=\"",
747 748 749 750
                    index, track->bitrate, track->fourcc, track->sample_rate,
                    track->channels, track->blocksize, track->tag);
            for (j = 0; j < track->codec_private_size; j++)
                fprintf(out, "%02X", track->codec_private[j]);
751 752
            fprintf(out, "\" />\n");
            index++;
753
            if (track->chunks != first_track->chunks)
754
                fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
755
                        track->name, first_track->name);
756
        }
757
        print_track_chunks(out, tracks, tracks->audio_track, "audio");
758 759 760 761 762 763
        fprintf(out, "\t</StreamIndex>\n");
    }
    fprintf(out, "</SmoothStreamingMedia>\n");
    fclose(out);
}

764
static void clean_tracks(struct Tracks *tracks)
765 766
{
    int i;
767 768 769 770
    for (i = 0; i < tracks->nb_tracks; i++) {
        av_freep(&tracks->tracks[i]->codec_private);
        av_freep(&tracks->tracks[i]->offsets);
        av_freep(&tracks->tracks[i]);
771
    }
772 773
    av_freep(&tracks->tracks);
    tracks->nb_tracks = 0;
774 775 776 777 778
}

int main(int argc, char **argv)
{
    const char *basename = NULL;
779
    const char *path_prefix = "", *ismc_prefix = "";
780 781
    const char *output_prefix = "";
    char output_prefix_buf[2048];
782
    int split = 0, ismf = 0, i;
783
    struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
784 785 786 787 788 789 790

    av_register_all();

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-n")) {
            basename = argv[i + 1];
            i++;
791 792 793 794 795 796
        } else if (!strcmp(argv[i], "-path-prefix")) {
            path_prefix = argv[i + 1];
            i++;
        } else if (!strcmp(argv[i], "-ismc-prefix")) {
            ismc_prefix = argv[i + 1];
            i++;
797 798 799 800 801 802 803 804
        } else if (!strcmp(argv[i], "-output")) {
            output_prefix = argv[i + 1];
            i++;
            if (output_prefix[strlen(output_prefix) - 1] != '/') {
                snprintf(output_prefix_buf, sizeof(output_prefix_buf),
                         "%s/", output_prefix);
                output_prefix = output_prefix_buf;
            }
805 806
        } else if (!strcmp(argv[i], "-split")) {
            split = 1;
807 808
        } else if (!strcmp(argv[i], "-ismf")) {
            ismf = 1;
809 810 811
        } else if (argv[i][0] == '-') {
            return usage(argv[0], 1);
        } else {
812 813
            if (!basename)
                ismf = 0;
814 815
            if (handle_file(&tracks, argv[i], split, ismf,
                            basename, output_prefix))
816
                return 1;
817 818
        }
    }
819
    if (!tracks.nb_tracks || (!basename && !split))
820 821 822
        return usage(argv[0], 1);

    if (!split)
823 824 825
        output_server_manifest(&tracks, basename, output_prefix,
                               path_prefix, ismc_prefix);
    output_client_manifest(&tracks, basename, output_prefix, split);
826

827
    clean_tracks(&tracks);
828 829 830

    return 0;
}