ismindex.c 18.8 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 31
 * 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.
 *
32 33 34 35 36 37 38 39 40
 * 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.
 */

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

42
#include "libavformat/avformat.h"
43
#include "libavformat/os_support.h"
44 45 46 47 48
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"

static int usage(const char *argv0, int ret)
{
49 50
    fprintf(stderr, "%s [-split] [-n basename] [-path-prefix prefix] "
                    "[-ismc-prefix prefix] file1 [file2] ...\n", argv0);
51 52 53 54 55 56
    return ret;
}

struct MoofOffset {
    int64_t time;
    int64_t offset;
57
    int64_t duration;
58 59
};

60
struct Track {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    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;
};

78 79
struct Tracks {
    int nb_tracks;
80
    int64_t duration;
81 82 83
    struct Track **tracks;
    int video_track, audio_track;
    int nb_video_tracks, nb_audio_tracks;
84 85 86 87 88 89 90
};

static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
{
    int32_t size, tag;

    size = avio_rb32(in);
91
    tag  = avio_rb32(in);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    avio_wb32(out, size);
    avio_wb32(out, tag);
    if (tag != tag_name)
        return -1;
    size -= 8;
    while (size > 0) {
        char buf[1024];
        int len = FFMIN(sizeof(buf), size);
        if (avio_read(in, buf, len) != len)
            break;
        avio_write(out, buf, len);
        size -= len;
    }
    return 0;
}

static int write_fragment(const char *filename, AVIOContext *in)
{
    AVIOContext *out = NULL;
    int ret;

    if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
        return ret;
    copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
    copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));

    avio_flush(out);
    avio_close(out);

    return ret;
}

124
static int write_fragments(struct Tracks *tracks, int start_index,
125 126 127 128 129
                           AVIOContext *in)
{
    char dirname[100], filename[500];
    int i, j;

130 131 132 133
    for (i = start_index; i < tracks->nb_tracks; i++) {
        struct Track *track = tracks->tracks[i];
        const char *type    = track->is_video ? "video" : "audio";
        snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", track->bitrate);
134
        mkdir(dirname, 0777);
135
        for (j = 0; j < track->chunks; j++) {
136
            snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
137 138
                     dirname, type, track->offsets[j].time);
            avio_seek(in, track->offsets[j].offset, SEEK_SET);
139 140 141 142 143 144
            write_fragment(filename, in);
        }
    }
    return 0;
}

145
static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
146 147 148
{
    int ret = AVERROR_EOF, track_id;
    int version, fieldlength, i, j;
149
    int64_t pos   = avio_tell(f);
150
    uint32_t size = avio_rb32(f);
151
    struct Track *track = NULL;
152 153 154 155 156 157

    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 */
158 159 160 161
    for (i = start_index; i < tracks->nb_tracks && !track; i++)
        if (tracks->tracks[i]->track_id == track_id)
            track = tracks->tracks[i];
    if (!track) {
162 163 164 165 166
        /* Ok, continue parsing the next atom */
        ret = 0;
        goto fail;
    }
    fieldlength = avio_rb32(f);
167 168 169
    track->chunks  = avio_rb32(f);
    track->offsets = av_mallocz(sizeof(*track->offsets) * track->chunks);
    if (!track->offsets) {
170 171 172
        ret = AVERROR(ENOMEM);
        goto fail;
    }
173
    for (i = 0; i < track->chunks; i++) {
174
        if (version == 1) {
175 176
            track->offsets[i].time   = avio_rb64(f);
            track->offsets[i].offset = avio_rb64(f);
177
        } else {
178 179
            track->offsets[i].time   = avio_rb32(f);
            track->offsets[i].offset = avio_rb32(f);
180 181 182 183 184 185 186 187
        }
        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)
188 189
            track->offsets[i - 1].duration = track->offsets[i].time -
                                             track->offsets[i - 1].time;
190
    }
191 192 193
    if (track->chunks > 0)
        track->offsets[track->chunks - 1].duration = track->duration -
                                                     track->offsets[track->chunks - 1].time;
194
    ret = 0;
195

196 197 198 199 200
fail:
    avio_seek(f, pos + size, SEEK_SET);
    return ret;
}

201
static int read_mfra(struct Tracks *tracks, int start_index,
202 203 204 205 206 207 208 209 210 211 212
                     const char *file, int split)
{
    int err = 0;
    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);
213 214
    if (avio_rb32(f) != mfra_size) {
        err = AVERROR_INVALIDDATA;
215
        goto fail;
216 217 218
    }
    if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
        err = AVERROR_INVALIDDATA;
219
        goto fail;
220
    }
221
    while (!read_tfra(tracks, start_index, f)) {
222 223 224 225
        /* Empty */
    }

    if (split)
226
        write_fragments(tracks, start_index, f);
227 228 229 230

fail:
    if (f)
        avio_close(f);
231 232
    if (err)
        fprintf(stderr, "Unable to read the MFRA atom in %s\n", file);
233 234 235
    return err;
}

236
static int get_private_data(struct Track *track, AVCodecContext *codec)
237
{
238 239 240
    track->codec_private_size = codec->extradata_size;
    track->codec_private      = av_mallocz(codec->extradata_size);
    if (!track->codec_private)
241
        return AVERROR(ENOMEM);
242
    memcpy(track->codec_private, codec->extradata, codec->extradata_size);
243 244 245
    return 0;
}

246
static int get_video_private_data(struct Track *track, AVCodecContext *codec)
247 248 249 250 251
{
    AVIOContext *io = NULL;
    uint16_t sps_size, pps_size;
    int err = AVERROR(EINVAL);

252
    if (codec->codec_id == AV_CODEC_ID_VC1)
253
        return get_private_data(track, codec);
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    avio_open_dyn_buf(&io);
    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;
269

270
fail:
271
    track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
272 273 274
    return err;
}

275
static int handle_file(struct Tracks *tracks, const char *file, int split)
276 277
{
    AVFormatContext *ctx = NULL;
278
    int err = 0, i, orig_tracks = tracks->nb_tracks;
279
    char errbuf[50], *ptr;
280
    struct Track *track;
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

    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++) {
302
        struct Track **temp;
303
        AVStream *st = ctx->streams[i];
304
        track = av_mallocz(sizeof(*track));
305 306 307 308 309 310 311 312 313 314 315 316
        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;
317
        tracks->tracks[tracks->nb_tracks] = track;
318

319
        track->name = file;
320
        if ((ptr = strrchr(file, '/')) != NULL)
321
            track->name = ptr + 1;
322

323 324 325
        track->bitrate   = st->codec->bit_rate;
        track->track_id  = st->id;
        track->timescale = st->time_base.den;
326
        track->duration  = st->duration;
327 328
        track->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
        track->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
329

330
        if (!track->is_audio && !track->is_video) {
331 332
            fprintf(stderr,
                    "Track %d in %s is neither video nor audio, skipping\n",
333 334
                    track->track_id, file);
            av_freep(&tracks->tracks[tracks->nb_tracks]);
335 336 337
            continue;
        }

338 339 340 341
        tracks->duration = FFMAX(tracks->duration,
                                 av_rescale_rnd(track->duration, AV_TIME_BASE,
                                                track->timescale, AV_ROUND_UP));

342 343 344 345 346 347
        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;
348
            if (st->codec->codec_id == AV_CODEC_ID_AAC) {
349 350 351
                track->fourcc    = "AACL";
                track->tag       = 255;
                track->blocksize = 4;
352
            } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
353 354 355
                track->fourcc    = "WMAP";
                track->tag       = st->codec->codec_tag;
                track->blocksize = st->codec->block_align;
356
            }
357
            get_private_data(track, st->codec);
358
        }
359 360 361 362 363 364
        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;
365
            if (st->codec->codec_id == AV_CODEC_ID_H264)
366
                track->fourcc = "H264";
367
            else if (st->codec->codec_id == AV_CODEC_ID_VC1)
368 369
                track->fourcc = "WVC1";
            get_video_private_data(track, st->codec);
370 371
        }

372
        tracks->nb_tracks++;
373 374 375 376
    }

    avformat_close_input(&ctx);

377
    err = read_mfra(tracks, orig_tracks, file, split);
378 379 380 381 382 383 384

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

385
static void output_server_manifest(struct Tracks *tracks,
386 387
                                   const char *basename, const char *path_prefix,
                                   const char *ismc_prefix)
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
{
    char filename[1000];
    FILE *out;
    int i;

    snprintf(filename, sizeof(filename), "%s.ism", basename);
    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\" "
403
                 "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
404 405 406
    fprintf(out, "\t</head>\n");
    fprintf(out, "\t<body>\n");
    fprintf(out, "\t\t<switch>\n");
407 408 409
    for (i = 0; i < tracks->nb_tracks; i++) {
        struct Track *track = tracks->tracks[i];
        const char *type    = track->is_video ? "video" : "audio";
410 411
        fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
                type, path_prefix, track->name, track->bitrate);
412
        fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
413
                     "valueType=\"data\" />\n", track->track_id);
414 415 416 417 418 419 420 421
        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);
}

422 423 424 425 426 427 428 429 430 431 432 433
static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
                               const char *type)
{
    int i, j;
    struct Track *track = tracks->tracks[main];
    for (i = 0; i < track->chunks; i++) {
        for (j = main + 1; j < tracks->nb_tracks; j++) {
            if (tracks->tracks[j]->is_audio == track->is_audio &&
                track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration)
                fprintf(stderr, "Mismatched duration of %s chunk %d in %s and %s\n",
                        type, i, track->name, tracks->tracks[j]->name);
        }
434
        fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" />\n",
435 436 437 438
                i, track->offsets[i].duration);
    }
}

439
static void output_client_manifest(struct Tracks *tracks,
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                                   const char *basename, int split)
{
    char filename[1000];
    FILE *out;
    int i, j;

    if (split)
        snprintf(filename, sizeof(filename), "Manifest");
    else
        snprintf(filename, sizeof(filename), "%s.ismc", basename);
    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\" "
457 458 459 460
                 "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
    if (tracks->video_track >= 0) {
        struct Track *track = tracks->tracks[tracks->video_track];
        struct Track *first_track = track;
461
        int index = 0;
462 463 464 465
        fprintf(out,
                "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
                "Chunks=\"%d\" "
                "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
466 467 468 469
                tracks->nb_video_tracks, track->chunks);
        for (i = 0; i < tracks->nb_tracks; i++) {
            track = tracks->tracks[i];
            if (!track->is_video)
470
                continue;
471 472 473 474
            fprintf(out,
                    "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
                    "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
                    "CodecPrivateData=\"",
475 476 477
                    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]);
478 479
            fprintf(out, "\" />\n");
            index++;
480
            if (track->chunks != first_track->chunks)
481
                fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
482
                        track->name, first_track->name);
483
        }
484
        print_track_chunks(out, tracks, tracks->video_track, "video");
485 486
        fprintf(out, "\t</StreamIndex>\n");
    }
487 488 489
    if (tracks->audio_track >= 0) {
        struct Track *track = tracks->tracks[tracks->audio_track];
        struct Track *first_track = track;
490
        int index = 0;
491 492 493 494
        fprintf(out,
                "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
                "Chunks=\"%d\" "
                "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
495 496 497 498
                tracks->nb_audio_tracks, track->chunks);
        for (i = 0; i < tracks->nb_tracks; i++) {
            track = tracks->tracks[i];
            if (!track->is_audio)
499
                continue;
500 501 502 503 504
            fprintf(out,
                    "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
                    "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
                    "BitsPerSample=\"16\" PacketSize=\"%d\" "
                    "AudioTag=\"%d\" CodecPrivateData=\"",
505 506 507 508
                    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]);
509 510
            fprintf(out, "\" />\n");
            index++;
511
            if (track->chunks != first_track->chunks)
512
                fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
513
                        track->name, first_track->name);
514
        }
515
        print_track_chunks(out, tracks, tracks->audio_track, "audio");
516 517 518 519 520 521
        fprintf(out, "\t</StreamIndex>\n");
    }
    fprintf(out, "</SmoothStreamingMedia>\n");
    fclose(out);
}

522
static void clean_tracks(struct Tracks *tracks)
523 524
{
    int i;
525 526 527 528
    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]);
529
    }
530 531
    av_freep(&tracks->tracks);
    tracks->nb_tracks = 0;
532 533 534 535 536
}

int main(int argc, char **argv)
{
    const char *basename = NULL;
537
    const char *path_prefix = "", *ismc_prefix = "";
538
    int split = 0, i;
539
    struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
540 541 542 543 544 545 546

    av_register_all();

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-n")) {
            basename = argv[i + 1];
            i++;
547 548 549 550 551 552
        } 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++;
553 554 555 556 557
        } else if (!strcmp(argv[i], "-split")) {
            split = 1;
        } else if (argv[i][0] == '-') {
            return usage(argv[0], 1);
        } else {
558
            if (handle_file(&tracks, argv[i], split))
559
                return 1;
560 561
        }
    }
562
    if (!tracks.nb_tracks || (!basename && !split))
563 564 565
        return usage(argv[0], 1);

    if (!split)
566
        output_server_manifest(&tracks, basename, path_prefix, ismc_prefix);
567
    output_client_manifest(&tracks, basename, split);
568

569
    clean_tracks(&tracks);
570 571 572

    return 0;
}