6ed31ac2935eeeff15d8fe045bd5da172fffda8a
[ffmpeg.git] / tools / ismindex.c
1 /*
2  * Copyright (c) 2012 Martin Storsjo
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /*
22  * To create a simple file for smooth streaming:
23  * avconv <normal input/transcoding options> -movflags frag_keyframe foo.ismv
24  * ismindex -n foo foo.ismv
25  * This step creates foo.ism and foo.ismc that is required by IIS for
26  * serving it.
27  *
28  * With -ismf, it also creates foo.ismf, which maps fragment names to
29  * start-end offsets in the ismv, for use in your own streaming server.
30  *
31  * By adding -path-prefix path/, the produced foo.ism will refer to the
32  * files foo.ismv as "path/foo.ismv" - the prefix for the generated ismc
33  * file can be set with the -ismc-prefix option similarly.
34  *
35  * To pre-split files for serving as static files by a web server without
36  * any extra server support, create the ismv file as above, and split it:
37  * ismindex -split foo.ismv
38  * This step creates a file Manifest and directories QualityLevel(...),
39  * that can be read directly by a smooth streaming player.
40  *
41  * The -output dir option can be used to request that output files
42  * (both .ism/.ismc, or Manifest/QualityLevels* when splitting)
43  * should be written to this directory instead of in the current directory.
44  * (The directory itself isn't created if it doesn't already exist.)
45  */
46
47 #include <stdio.h>
48 #include <string.h>
49
50 #include "libavformat/avformat.h"
51 #include "libavformat/os_support.h"
52 #include "libavutil/intreadwrite.h"
53 #include "libavutil/mathematics.h"
54
55 static int usage(const char *argv0, int ret)
56 {
57     fprintf(stderr, "%s [-split] [-ismf] [-n basename] [-path-prefix prefix] "
58                     "[-ismc-prefix prefix] [-output dir] file1 [file2] ...\n", argv0);
59     return ret;
60 }
61
62 struct MoofOffset {
63     int64_t time;
64     int64_t offset;
65     int64_t duration;
66 };
67
68 struct Track {
69     const char *name;
70     int64_t duration;
71     int bitrate;
72     int track_id;
73     int is_audio, is_video;
74     int width, height;
75     int chunks;
76     int sample_rate, channels;
77     uint8_t *codec_private;
78     int codec_private_size;
79     struct MoofOffset *offsets;
80     int timescale;
81     const char *fourcc;
82     int blocksize;
83     int tag;
84 };
85
86 struct Tracks {
87     int nb_tracks;
88     int64_t duration;
89     struct Track **tracks;
90     int video_track, audio_track;
91     int nb_video_tracks, nb_audio_tracks;
92 };
93
94 static int expect_tag(int32_t got_tag, int32_t expected_tag) {
95     if (got_tag != expected_tag) {
96         char got_tag_str[4], expected_tag_str[4];
97         AV_WB32(got_tag_str, got_tag);
98         AV_WB32(expected_tag_str, expected_tag);
99         fprintf(stderr, "wanted tag %.4s, got %.4s\n", expected_tag_str,
100                 got_tag_str);
101         return -1;
102     }
103     return 0;
104 }
105
106 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
107 {
108     int32_t size, tag;
109
110     size = avio_rb32(in);
111     tag  = avio_rb32(in);
112     avio_wb32(out, size);
113     avio_wb32(out, tag);
114     if (expect_tag(tag, tag_name) != 0)
115         return -1;
116     size -= 8;
117     while (size > 0) {
118         char buf[1024];
119         int len = FFMIN(sizeof(buf), size);
120         int got;
121         if ((got = avio_read(in, buf, len)) != len) {
122             fprintf(stderr, "short read, wanted %d, got %d\n", len, got);
123             break;
124         }
125         avio_write(out, buf, len);
126         size -= len;
127     }
128     return 0;
129 }
130
131 static int skip_tag(AVIOContext *in, int32_t tag_name)
132 {
133     int64_t pos = avio_tell(in);
134     int32_t size, tag;
135
136     size = avio_rb32(in);
137     tag  = avio_rb32(in);
138     if (expect_tag(tag, tag_name) != 0)
139         return -1;
140     avio_seek(in, pos + size, SEEK_SET);
141     return 0;
142 }
143
144 static int write_fragment(const char *filename, AVIOContext *in)
145 {
146     AVIOContext *out = NULL;
147     int ret;
148
149     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0) {
150         char errbuf[100];
151         av_strerror(ret, errbuf, sizeof(errbuf));
152         fprintf(stderr, "Unable to open %s: %s\n", filename, errbuf);
153         return ret;
154     }
155     ret = copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
156     if (!ret)
157         ret = copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
158
159     avio_flush(out);
160     avio_close(out);
161
162     return ret;
163 }
164
165 static int skip_fragment(AVIOContext *in)
166 {
167     int ret;
168     ret = skip_tag(in, MKBETAG('m', 'o', 'o', 'f'));
169     if (!ret)
170         ret = skip_tag(in, MKBETAG('m', 'd', 'a', 't'));
171     return ret;
172 }
173
174 static int write_fragments(struct Tracks *tracks, int start_index,
175                            AVIOContext *in, const char *basename,
176                            int split, int ismf, const char* output_prefix)
177 {
178     char dirname[2048], filename[2048], idxname[2048];
179     int i, j, ret = 0, fragment_ret;
180     FILE* out = NULL;
181
182     if (ismf) {
183         snprintf(idxname, sizeof(idxname), "%s%s.ismf", output_prefix, basename);
184         out = fopen(idxname, "w");
185         if (!out) {
186             ret = AVERROR(errno);
187             perror(idxname);
188             goto fail;
189         }
190     }
191     for (i = start_index; i < tracks->nb_tracks; i++) {
192         struct Track *track = tracks->tracks[i];
193         const char *type    = track->is_video ? "video" : "audio";
194         snprintf(dirname, sizeof(dirname), "%sQualityLevels(%d)", output_prefix, track->bitrate);
195         if (split) {
196             if (mkdir(dirname, 0777) == -1 && errno != EEXIST) {
197                 ret = AVERROR(errno);
198                 perror(dirname);
199                 goto fail;
200             }
201         }
202         for (j = 0; j < track->chunks; j++) {
203             snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
204                      dirname, type, track->offsets[j].time);
205             avio_seek(in, track->offsets[j].offset, SEEK_SET);
206             if (ismf)
207                 fprintf(out, "%s %"PRId64, filename, avio_tell(in));
208             if (split)
209                 fragment_ret = write_fragment(filename, in);
210             else
211                 fragment_ret = skip_fragment(in);
212             if (ismf)
213                 fprintf(out, " %"PRId64"\n", avio_tell(in));
214             if (fragment_ret != 0) {
215                 fprintf(stderr, "failed fragment %d in track %d (%s)\n", j,
216                         track->track_id, track->name);
217                 ret = fragment_ret;
218             }
219         }
220     }
221 fail:
222     if (out)
223         fclose(out);
224     return ret;
225 }
226
227 static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
228 {
229     int ret = AVERROR_EOF, track_id;
230     int version, fieldlength, i, j;
231     int64_t pos   = avio_tell(f);
232     uint32_t size = avio_rb32(f);
233     struct Track *track = NULL;
234
235     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
236         goto fail;
237     version = avio_r8(f);
238     avio_rb24(f);
239     track_id = avio_rb32(f); /* track id */
240     for (i = start_index; i < tracks->nb_tracks && !track; i++)
241         if (tracks->tracks[i]->track_id == track_id)
242             track = tracks->tracks[i];
243     if (!track) {
244         /* Ok, continue parsing the next atom */
245         ret = 0;
246         goto fail;
247     }
248     fieldlength = avio_rb32(f);
249     track->chunks  = avio_rb32(f);
250     track->offsets = av_mallocz(sizeof(*track->offsets) * track->chunks);
251     if (!track->offsets) {
252         ret = AVERROR(ENOMEM);
253         goto fail;
254     }
255     // The duration here is always the difference between consecutive
256     // start times and doesn't even try to read the actual duration of the
257     // media fragments. This is what other smooth streaming tools tend to
258     // do too, but cannot express missing fragments, and the start times
259     // may not match the stream metadata we get from libavformat. Correct
260     // calculation would require parsing the tfxd atom (if present, it's
261     // not mandatory) or parsing the full moof atoms separately.
262     for (i = 0; i < track->chunks; i++) {
263         if (version == 1) {
264             track->offsets[i].time   = avio_rb64(f);
265             track->offsets[i].offset = avio_rb64(f);
266         } else {
267             track->offsets[i].time   = avio_rb32(f);
268             track->offsets[i].offset = avio_rb32(f);
269         }
270         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
271             avio_r8(f);
272         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
273             avio_r8(f);
274         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
275             avio_r8(f);
276         if (i > 0)
277             track->offsets[i - 1].duration = track->offsets[i].time -
278                                              track->offsets[i - 1].time;
279     }
280     if (track->chunks > 0) {
281         track->offsets[track->chunks - 1].duration = track->offsets[0].time +
282                                                      track->duration -
283                                                      track->offsets[track->chunks - 1].time;
284         if (track->offsets[track->chunks - 1].duration <= 0) {
285             fprintf(stderr, "Calculated last chunk duration for track %d "
286                     "was non-positive (%"PRId64"), probably due to missing "
287                     "fragments ", track->track_id,
288                     track->offsets[track->chunks - 1].duration);
289             if (track->chunks > 1) {
290                 track->offsets[track->chunks - 1].duration =
291                     track->offsets[track->chunks - 2].duration;
292             } else {
293                 track->offsets[track->chunks - 1].duration = 1;
294             }
295             fprintf(stderr, "corrected to %"PRId64"\n",
296                     track->offsets[track->chunks - 1].duration);
297             track->duration = track->offsets[track->chunks - 1].time +
298                               track->offsets[track->chunks - 1].duration -
299                               track->offsets[0].time;
300             fprintf(stderr, "Track duration corrected to %"PRId64"\n",
301                     track->duration);
302         }
303     }
304     ret = 0;
305
306 fail:
307     avio_seek(f, pos + size, SEEK_SET);
308     return ret;
309 }
310
311 static int read_mfra(struct Tracks *tracks, int start_index,
312                      const char *file, int split, int ismf,
313                      const char *basename, const char* output_prefix)
314 {
315     int err = 0;
316     const char* err_str = "";
317     AVIOContext *f = NULL;
318     int32_t mfra_size;
319
320     if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
321         goto fail;
322     avio_seek(f, avio_size(f) - 4, SEEK_SET);
323     mfra_size = avio_rb32(f);
324     avio_seek(f, -mfra_size, SEEK_CUR);
325     if (avio_rb32(f) != mfra_size) {
326         err = AVERROR_INVALIDDATA;
327         err_str = "mfra size mismatch";
328         goto fail;
329     }
330     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
331         err = AVERROR_INVALIDDATA;
332         err_str = "mfra tag mismatch";
333         goto fail;
334     }
335     while (!read_tfra(tracks, start_index, f)) {
336         /* Empty */
337     }
338
339     if (split || ismf)
340         err = write_fragments(tracks, start_index, f, basename, split, ismf,
341                               output_prefix);
342     err_str = "error in write_fragments";
343
344 fail:
345     if (f)
346         avio_close(f);
347     if (err)
348         fprintf(stderr, "Unable to read the MFRA atom in %s (%s)\n", file, err_str);
349     return err;
350 }
351
352 static int get_private_data(struct Track *track, AVCodecContext *codec)
353 {
354     track->codec_private_size = codec->extradata_size;
355     track->codec_private      = av_mallocz(codec->extradata_size);
356     if (!track->codec_private)
357         return AVERROR(ENOMEM);
358     memcpy(track->codec_private, codec->extradata, codec->extradata_size);
359     return 0;
360 }
361
362 static int get_video_private_data(struct Track *track, AVCodecContext *codec)
363 {
364     AVIOContext *io = NULL;
365     uint16_t sps_size, pps_size;
366     int err;
367
368     if (codec->codec_id == AV_CODEC_ID_VC1)
369         return get_private_data(track, codec);
370
371     if ((err = avio_open_dyn_buf(&io)) < 0)
372         goto fail;
373     err = AVERROR(EINVAL);
374     if (codec->extradata_size < 11 || codec->extradata[0] != 1)
375         goto fail;
376     sps_size = AV_RB16(&codec->extradata[6]);
377     if (11 + sps_size > codec->extradata_size)
378         goto fail;
379     avio_wb32(io, 0x00000001);
380     avio_write(io, &codec->extradata[8], sps_size);
381     pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
382     if (11 + sps_size + pps_size > codec->extradata_size)
383         goto fail;
384     avio_wb32(io, 0x00000001);
385     avio_write(io, &codec->extradata[11 + sps_size], pps_size);
386     err = 0;
387
388 fail:
389     track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
390     return err;
391 }
392
393 static int handle_file(struct Tracks *tracks, const char *file, int split,
394                        int ismf, const char *basename,
395                        const char* output_prefix)
396 {
397     AVFormatContext *ctx = NULL;
398     int err = 0, i, orig_tracks = tracks->nb_tracks;
399     char errbuf[50], *ptr;
400     struct Track *track;
401
402     err = avformat_open_input(&ctx, file, NULL, NULL);
403     if (err < 0) {
404         av_strerror(err, errbuf, sizeof(errbuf));
405         fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
406         return 1;
407     }
408
409     err = avformat_find_stream_info(ctx, NULL);
410     if (err < 0) {
411         av_strerror(err, errbuf, sizeof(errbuf));
412         fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
413         goto fail;
414     }
415
416     if (ctx->nb_streams < 1) {
417         fprintf(stderr, "No streams found in %s\n", file);
418         goto fail;
419     }
420
421     for (i = 0; i < ctx->nb_streams; i++) {
422         struct Track **temp;
423         AVStream *st = ctx->streams[i];
424
425         if (st->codec->bit_rate == 0) {
426             fprintf(stderr, "Skipping track %d in %s as it has zero bitrate\n",
427                     st->id, file);
428             continue;
429         }
430
431         track = av_mallocz(sizeof(*track));
432         if (!track) {
433             err = AVERROR(ENOMEM);
434             goto fail;
435         }
436         temp = av_realloc(tracks->tracks,
437                           sizeof(*tracks->tracks) * (tracks->nb_tracks + 1));
438         if (!temp) {
439             av_free(track);
440             err = AVERROR(ENOMEM);
441             goto fail;
442         }
443         tracks->tracks = temp;
444         tracks->tracks[tracks->nb_tracks] = track;
445
446         track->name = file;
447         if ((ptr = strrchr(file, '/')))
448             track->name = ptr + 1;
449
450         track->bitrate   = st->codec->bit_rate;
451         track->track_id  = st->id;
452         track->timescale = st->time_base.den;
453         track->duration  = st->duration;
454         track->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
455         track->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
456
457         if (!track->is_audio && !track->is_video) {
458             fprintf(stderr,
459                     "Track %d in %s is neither video nor audio, skipping\n",
460                     track->track_id, file);
461             av_freep(&tracks->tracks[tracks->nb_tracks]);
462             continue;
463         }
464
465         tracks->duration = FFMAX(tracks->duration,
466                                  av_rescale_rnd(track->duration, AV_TIME_BASE,
467                                                 track->timescale, AV_ROUND_UP));
468
469         if (track->is_audio) {
470             if (tracks->audio_track < 0)
471                 tracks->audio_track = tracks->nb_tracks;
472             tracks->nb_audio_tracks++;
473             track->channels    = st->codec->channels;
474             track->sample_rate = st->codec->sample_rate;
475             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
476                 track->fourcc    = "AACL";
477                 track->tag       = 255;
478                 track->blocksize = 4;
479             } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
480                 track->fourcc    = "WMAP";
481                 track->tag       = st->codec->codec_tag;
482                 track->blocksize = st->codec->block_align;
483             }
484             get_private_data(track, st->codec);
485         }
486         if (track->is_video) {
487             if (tracks->video_track < 0)
488                 tracks->video_track = tracks->nb_tracks;
489             tracks->nb_video_tracks++;
490             track->width  = st->codec->width;
491             track->height = st->codec->height;
492             if (st->codec->codec_id == AV_CODEC_ID_H264)
493                 track->fourcc = "H264";
494             else if (st->codec->codec_id == AV_CODEC_ID_VC1)
495                 track->fourcc = "WVC1";
496             get_video_private_data(track, st->codec);
497         }
498
499         tracks->nb_tracks++;
500     }
501
502     avformat_close_input(&ctx);
503
504     err = read_mfra(tracks, orig_tracks, file, split, ismf, basename,
505                     output_prefix);
506
507 fail:
508     if (ctx)
509         avformat_close_input(&ctx);
510     return err;
511 }
512
513 static void output_server_manifest(struct Tracks *tracks, const char *basename,
514                                    const char *output_prefix,
515                                    const char *path_prefix,
516                                    const char *ismc_prefix)
517 {
518     char filename[1000];
519     FILE *out;
520     int i;
521
522     snprintf(filename, sizeof(filename), "%s%s.ism", output_prefix, basename);
523     out = fopen(filename, "w");
524     if (!out) {
525         perror(filename);
526         return;
527     }
528     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
529     fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
530     fprintf(out, "\t<head>\n");
531     fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
532                  "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
533     fprintf(out, "\t</head>\n");
534     fprintf(out, "\t<body>\n");
535     fprintf(out, "\t\t<switch>\n");
536     for (i = 0; i < tracks->nb_tracks; i++) {
537         struct Track *track = tracks->tracks[i];
538         const char *type    = track->is_video ? "video" : "audio";
539         fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
540                 type, path_prefix, track->name, track->bitrate);
541         fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
542                      "valueType=\"data\" />\n", track->track_id);
543         fprintf(out, "\t\t\t</%s>\n", type);
544     }
545     fprintf(out, "\t\t</switch>\n");
546     fprintf(out, "\t</body>\n");
547     fprintf(out, "</smil>\n");
548     fclose(out);
549 }
550
551 static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
552                                const char *type)
553 {
554     int i, j;
555     int64_t pos = 0;
556     struct Track *track = tracks->tracks[main];
557     int should_print_time_mismatch = 1;
558
559     for (i = 0; i < track->chunks; i++) {
560         for (j = main + 1; j < tracks->nb_tracks; j++) {
561             if (tracks->tracks[j]->is_audio == track->is_audio) {
562                 if (track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration) {
563                     fprintf(stderr, "Mismatched duration of %s chunk %d in %s (%d) and %s (%d)\n",
564                             type, i, track->name, main, tracks->tracks[j]->name, j);
565                     should_print_time_mismatch = 1;
566                 }
567                 if (track->offsets[i].time != tracks->tracks[j]->offsets[i].time) {
568                     if (should_print_time_mismatch)
569                         fprintf(stderr, "Mismatched (start) time of %s chunk %d in %s (%d) and %s (%d)\n",
570                                 type, i, track->name, main, tracks->tracks[j]->name, j);
571                     should_print_time_mismatch = 0;
572                 }
573             }
574         }
575         fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" ",
576                 i, track->offsets[i].duration);
577         if (pos != track->offsets[i].time) {
578             // With the current logic for calculation of durations from
579             // chunk start times, this branch can only be hit on the first
580             // chunk - but that's still useful and this will keep working
581             // if the duration calculation is improved.
582             fprintf(out, "t=\"%"PRId64"\" ", track->offsets[i].time);
583             pos = track->offsets[i].time;
584         }
585         pos += track->offsets[i].duration;
586         fprintf(out, "/>\n");
587     }
588 }
589
590 static void output_client_manifest(struct Tracks *tracks, const char *basename,
591                                    const char *output_prefix, int split)
592 {
593     char filename[1000];
594     FILE *out;
595     int i, j;
596
597     if (split)
598         snprintf(filename, sizeof(filename), "%sManifest", output_prefix);
599     else
600         snprintf(filename, sizeof(filename), "%s%s.ismc", output_prefix, basename);
601     out = fopen(filename, "w");
602     if (!out) {
603         perror(filename);
604         return;
605     }
606     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
607     fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
608                  "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
609     if (tracks->video_track >= 0) {
610         struct Track *track = tracks->tracks[tracks->video_track];
611         struct Track *first_track = track;
612         int index = 0;
613         fprintf(out,
614                 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
615                 "Chunks=\"%d\" "
616                 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
617                 tracks->nb_video_tracks, track->chunks);
618         for (i = 0; i < tracks->nb_tracks; i++) {
619             track = tracks->tracks[i];
620             if (!track->is_video)
621                 continue;
622             fprintf(out,
623                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
624                     "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
625                     "CodecPrivateData=\"",
626                     index, track->bitrate, track->fourcc, track->width, track->height);
627             for (j = 0; j < track->codec_private_size; j++)
628                 fprintf(out, "%02X", track->codec_private[j]);
629             fprintf(out, "\" />\n");
630             index++;
631             if (track->chunks != first_track->chunks)
632                 fprintf(stderr, "Mismatched number of video chunks in %s (id: %d, chunks %d) and %s (id: %d, chunks %d)\n",
633                         track->name, track->track_id, track->chunks, first_track->name, first_track->track_id, first_track->chunks);
634         }
635         print_track_chunks(out, tracks, tracks->video_track, "video");
636         fprintf(out, "\t</StreamIndex>\n");
637     }
638     if (tracks->audio_track >= 0) {
639         struct Track *track = tracks->tracks[tracks->audio_track];
640         struct Track *first_track = track;
641         int index = 0;
642         fprintf(out,
643                 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
644                 "Chunks=\"%d\" "
645                 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
646                 tracks->nb_audio_tracks, track->chunks);
647         for (i = 0; i < tracks->nb_tracks; i++) {
648             track = tracks->tracks[i];
649             if (!track->is_audio)
650                 continue;
651             fprintf(out,
652                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
653                     "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
654                     "BitsPerSample=\"16\" PacketSize=\"%d\" "
655                     "AudioTag=\"%d\" CodecPrivateData=\"",
656                     index, track->bitrate, track->fourcc, track->sample_rate,
657                     track->channels, track->blocksize, track->tag);
658             for (j = 0; j < track->codec_private_size; j++)
659                 fprintf(out, "%02X", track->codec_private[j]);
660             fprintf(out, "\" />\n");
661             index++;
662             if (track->chunks != first_track->chunks)
663                 fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
664                         track->name, first_track->name);
665         }
666         print_track_chunks(out, tracks, tracks->audio_track, "audio");
667         fprintf(out, "\t</StreamIndex>\n");
668     }
669     fprintf(out, "</SmoothStreamingMedia>\n");
670     fclose(out);
671 }
672
673 static void clean_tracks(struct Tracks *tracks)
674 {
675     int i;
676     for (i = 0; i < tracks->nb_tracks; i++) {
677         av_freep(&tracks->tracks[i]->codec_private);
678         av_freep(&tracks->tracks[i]->offsets);
679         av_freep(&tracks->tracks[i]);
680     }
681     av_freep(&tracks->tracks);
682     tracks->nb_tracks = 0;
683 }
684
685 int main(int argc, char **argv)
686 {
687     const char *basename = NULL;
688     const char *path_prefix = "", *ismc_prefix = "";
689     const char *output_prefix = "";
690     char output_prefix_buf[2048];
691     int split = 0, ismf = 0, i;
692     struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
693
694     av_register_all();
695
696     for (i = 1; i < argc; i++) {
697         if (!strcmp(argv[i], "-n")) {
698             basename = argv[i + 1];
699             i++;
700         } else if (!strcmp(argv[i], "-path-prefix")) {
701             path_prefix = argv[i + 1];
702             i++;
703         } else if (!strcmp(argv[i], "-ismc-prefix")) {
704             ismc_prefix = argv[i + 1];
705             i++;
706         } else if (!strcmp(argv[i], "-output")) {
707             output_prefix = argv[i + 1];
708             i++;
709             if (output_prefix[strlen(output_prefix) - 1] != '/') {
710                 snprintf(output_prefix_buf, sizeof(output_prefix_buf),
711                          "%s/", output_prefix);
712                 output_prefix = output_prefix_buf;
713             }
714         } else if (!strcmp(argv[i], "-split")) {
715             split = 1;
716         } else if (!strcmp(argv[i], "-ismf")) {
717             ismf = 1;
718         } else if (argv[i][0] == '-') {
719             return usage(argv[0], 1);
720         } else {
721             if (!basename)
722                 ismf = 0;
723             if (handle_file(&tracks, argv[i], split, ismf,
724                             basename, output_prefix))
725                 return 1;
726         }
727     }
728     if (!tracks.nb_tracks || (!basename && !split))
729         return usage(argv[0], 1);
730
731     if (!split)
732         output_server_manifest(&tracks, basename, output_prefix,
733                                path_prefix, ismc_prefix);
734     output_client_manifest(&tracks, basename, output_prefix, split);
735
736     clean_tracks(&tracks);
737
738     return 0;
739 }