OSDN Git Service

avcodec/snow: Initialize spatial_decomposition_count to a valid value
[android-x86/external-ffmpeg.git] / tools / ismindex.c
1 /*
2  * Copyright (c) 2012 Martin Storsjo
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
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  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 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 FFmpeg; 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  * ffmpeg <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 "cmdutils.h"
51
52 #include "libavformat/avformat.h"
53 #include "libavformat/isom.h"
54 #include "libavformat/os_support.h"
55 #include "libavutil/intreadwrite.h"
56 #include "libavutil/mathematics.h"
57
58 static int usage(const char *argv0, int ret)
59 {
60     fprintf(stderr, "%s [-split] [-ismf] [-n basename] [-path-prefix prefix] "
61                     "[-ismc-prefix prefix] [-output dir] file1 [file2] ...\n", argv0);
62     return ret;
63 }
64
65 struct MoofOffset {
66     int64_t time;
67     int64_t offset;
68     int64_t duration;
69 };
70
71 struct Track {
72     const char *name;
73     int64_t duration;
74     int bitrate;
75     int track_id;
76     int is_audio, is_video;
77     int width, height;
78     int chunks;
79     int sample_rate, channels;
80     uint8_t *codec_private;
81     int codec_private_size;
82     struct MoofOffset *offsets;
83     int timescale;
84     const char *fourcc;
85     int blocksize;
86     int tag;
87 };
88
89 struct Tracks {
90     int nb_tracks;
91     int64_t duration;
92     struct Track **tracks;
93     int video_track, audio_track;
94     int nb_video_tracks, nb_audio_tracks;
95 };
96
97 static int expect_tag(int32_t got_tag, int32_t expected_tag) {
98     if (got_tag != expected_tag) {
99         char got_tag_str[4], expected_tag_str[4];
100         AV_WB32(got_tag_str, got_tag);
101         AV_WB32(expected_tag_str, expected_tag);
102         fprintf(stderr, "wanted tag %.4s, got %.4s\n", expected_tag_str,
103                 got_tag_str);
104         return -1;
105     }
106     return 0;
107 }
108
109 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
110 {
111     int32_t size, tag;
112
113     size = avio_rb32(in);
114     tag  = avio_rb32(in);
115     avio_wb32(out, size);
116     avio_wb32(out, tag);
117     if (expect_tag(tag, tag_name) != 0)
118         return -1;
119     size -= 8;
120     while (size > 0) {
121         char buf[1024];
122         int len = FFMIN(sizeof(buf), size);
123         int got;
124         if ((got = avio_read(in, buf, len)) != len) {
125             fprintf(stderr, "short read, wanted %d, got %d\n", len, got);
126             break;
127         }
128         avio_write(out, buf, len);
129         size -= len;
130     }
131     return 0;
132 }
133
134 static int skip_tag(AVIOContext *in, int32_t tag_name)
135 {
136     int64_t pos = avio_tell(in);
137     int32_t size, tag;
138
139     size = avio_rb32(in);
140     tag  = avio_rb32(in);
141     if (expect_tag(tag, tag_name) != 0)
142         return -1;
143     avio_seek(in, pos + size, SEEK_SET);
144     return 0;
145 }
146
147 static int write_fragment(const char *filename, AVIOContext *in)
148 {
149     AVIOContext *out = NULL;
150     int ret;
151
152     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0) {
153         char errbuf[100];
154         av_strerror(ret, errbuf, sizeof(errbuf));
155         fprintf(stderr, "Unable to open %s: %s\n", filename, errbuf);
156         return ret;
157     }
158     ret = copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
159     if (!ret)
160         ret = copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
161
162     avio_flush(out);
163     avio_close(out);
164
165     return ret;
166 }
167
168 static int skip_fragment(AVIOContext *in)
169 {
170     int ret;
171     ret = skip_tag(in, MKBETAG('m', 'o', 'o', 'f'));
172     if (!ret)
173         ret = skip_tag(in, MKBETAG('m', 'd', 'a', 't'));
174     return ret;
175 }
176
177 static int write_fragments(struct Tracks *tracks, int start_index,
178                            AVIOContext *in, const char *basename,
179                            int split, int ismf, const char* output_prefix)
180 {
181     char dirname[2048], filename[2048], idxname[2048];
182     int i, j, ret = 0, fragment_ret;
183     FILE* out = NULL;
184
185     if (ismf) {
186         snprintf(idxname, sizeof(idxname), "%s%s.ismf", output_prefix, basename);
187         out = fopen(idxname, "w");
188         if (!out) {
189             ret = AVERROR(errno);
190             perror(idxname);
191             goto fail;
192         }
193     }
194     for (i = start_index; i < tracks->nb_tracks; i++) {
195         struct Track *track = tracks->tracks[i];
196         const char *type    = track->is_video ? "video" : "audio";
197         snprintf(dirname, sizeof(dirname), "%sQualityLevels(%d)", output_prefix, track->bitrate);
198         if (split) {
199             if (mkdir(dirname, 0777) == -1 && errno != EEXIST) {
200                 ret = AVERROR(errno);
201                 perror(dirname);
202                 goto fail;
203             }
204         }
205         for (j = 0; j < track->chunks; j++) {
206             snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
207                      dirname, type, track->offsets[j].time);
208             avio_seek(in, track->offsets[j].offset, SEEK_SET);
209             if (ismf)
210                 fprintf(out, "%s %"PRId64, filename, avio_tell(in));
211             if (split)
212                 fragment_ret = write_fragment(filename, in);
213             else
214                 fragment_ret = skip_fragment(in);
215             if (ismf)
216                 fprintf(out, " %"PRId64"\n", avio_tell(in));
217             if (fragment_ret != 0) {
218                 fprintf(stderr, "failed fragment %d in track %d (%s)\n", j,
219                         track->track_id, track->name);
220                 ret = fragment_ret;
221             }
222         }
223     }
224 fail:
225     if (out)
226         fclose(out);
227     return ret;
228 }
229
230 static int64_t read_trun_duration(AVIOContext *in, int default_duration,
231                                   int64_t end)
232 {
233     int64_t ret = 0;
234     int64_t pos;
235     int flags, i;
236     int entries;
237     avio_r8(in); /* version */
238     flags = avio_rb24(in);
239     if (default_duration <= 0 && !(flags & MOV_TRUN_SAMPLE_DURATION)) {
240         fprintf(stderr, "No sample duration in trun flags\n");
241         return -1;
242     }
243     entries = avio_rb32(in);
244
245     if (flags & MOV_TRUN_DATA_OFFSET)        avio_rb32(in);
246     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_rb32(in);
247
248     pos = avio_tell(in);
249     for (i = 0; i < entries && pos < end; i++) {
250         int sample_duration = default_duration;
251         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(in);
252         if (flags & MOV_TRUN_SAMPLE_SIZE)     avio_rb32(in);
253         if (flags & MOV_TRUN_SAMPLE_FLAGS)    avio_rb32(in);
254         if (flags & MOV_TRUN_SAMPLE_CTS)      avio_rb32(in);
255         if (sample_duration < 0) {
256             fprintf(stderr, "Negative sample duration %d\n", sample_duration);
257             return -1;
258         }
259         ret += sample_duration;
260         pos = avio_tell(in);
261     }
262
263     return ret;
264 }
265
266 static int64_t read_moof_duration(AVIOContext *in, int64_t offset)
267 {
268     int64_t ret = -1;
269     int32_t moof_size, size, tag;
270     int64_t pos = 0;
271     int default_duration = 0;
272
273     avio_seek(in, offset, SEEK_SET);
274     moof_size = avio_rb32(in);
275     tag  = avio_rb32(in);
276     if (expect_tag(tag, MKBETAG('m', 'o', 'o', 'f')) != 0)
277         goto fail;
278     while (pos < offset + moof_size) {
279         pos = avio_tell(in);
280         size = avio_rb32(in);
281         tag  = avio_rb32(in);
282         if (tag == MKBETAG('t', 'r', 'a', 'f')) {
283             int64_t traf_pos = pos;
284             int64_t traf_size = size;
285             while (pos < traf_pos + traf_size) {
286                 pos = avio_tell(in);
287                 size = avio_rb32(in);
288                 tag  = avio_rb32(in);
289                 if (tag == MKBETAG('t', 'f', 'h', 'd')) {
290                     int flags = 0;
291                     avio_r8(in); /* version */
292                     flags = avio_rb24(in);
293                     avio_rb32(in); /* track_id */
294                     if (flags & MOV_TFHD_BASE_DATA_OFFSET)
295                         avio_rb64(in);
296                     if (flags & MOV_TFHD_STSD_ID)
297                         avio_rb32(in);
298                     if (flags & MOV_TFHD_DEFAULT_DURATION)
299                         default_duration = avio_rb32(in);
300                 }
301                 if (tag == MKBETAG('t', 'r', 'u', 'n')) {
302                     return read_trun_duration(in, default_duration,
303                                               pos + size);
304                 }
305                 avio_seek(in, pos + size, SEEK_SET);
306             }
307             fprintf(stderr, "Couldn't find trun\n");
308             goto fail;
309         }
310         avio_seek(in, pos + size, SEEK_SET);
311     }
312     fprintf(stderr, "Couldn't find traf\n");
313
314 fail:
315     return ret;
316 }
317
318 static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
319 {
320     int ret = AVERROR_EOF, track_id;
321     int version, fieldlength, i, j;
322     int64_t pos   = avio_tell(f);
323     uint32_t size = avio_rb32(f);
324     struct Track *track = NULL;
325
326     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
327         goto fail;
328     version = avio_r8(f);
329     avio_rb24(f);
330     track_id = avio_rb32(f); /* track id */
331     for (i = start_index; i < tracks->nb_tracks && !track; i++)
332         if (tracks->tracks[i]->track_id == track_id)
333             track = tracks->tracks[i];
334     if (!track) {
335         /* Ok, continue parsing the next atom */
336         ret = 0;
337         goto fail;
338     }
339     fieldlength = avio_rb32(f);
340     track->chunks  = avio_rb32(f);
341     track->offsets = av_mallocz_array(track->chunks, sizeof(*track->offsets));
342     if (!track->offsets) {
343         track->chunks = 0;
344         ret = AVERROR(ENOMEM);
345         goto fail;
346     }
347     // The duration here is always the difference between consecutive
348     // start times.
349     for (i = 0; i < track->chunks; i++) {
350         if (version == 1) {
351             track->offsets[i].time   = avio_rb64(f);
352             track->offsets[i].offset = avio_rb64(f);
353         } else {
354             track->offsets[i].time   = avio_rb32(f);
355             track->offsets[i].offset = avio_rb32(f);
356         }
357         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
358             avio_r8(f);
359         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
360             avio_r8(f);
361         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
362             avio_r8(f);
363         if (i > 0)
364             track->offsets[i - 1].duration = track->offsets[i].time -
365                                              track->offsets[i - 1].time;
366     }
367     if (track->chunks > 0) {
368         track->offsets[track->chunks - 1].duration = track->offsets[0].time +
369                                                      track->duration -
370                                                      track->offsets[track->chunks - 1].time;
371     }
372     // Now try and read the actual durations from the trun sample data.
373     for (i = 0; i < track->chunks; i++) {
374         int64_t duration = read_moof_duration(f, track->offsets[i].offset);
375         if (duration > 0 && abs(duration - track->offsets[i].duration) > 3) {
376             // 3 allows for integer duration to drift a few units,
377             // e.g., for 1/3 durations
378             track->offsets[i].duration = duration;
379         }
380     }
381     if (track->chunks > 0) {
382         if (track->offsets[track->chunks - 1].duration <= 0) {
383             fprintf(stderr, "Calculated last chunk duration for track %d "
384                     "was non-positive (%"PRId64"), probably due to missing "
385                     "fragments ", track->track_id,
386                     track->offsets[track->chunks - 1].duration);
387             if (track->chunks > 1) {
388                 track->offsets[track->chunks - 1].duration =
389                     track->offsets[track->chunks - 2].duration;
390             } else {
391                 track->offsets[track->chunks - 1].duration = 1;
392             }
393             fprintf(stderr, "corrected to %"PRId64"\n",
394                     track->offsets[track->chunks - 1].duration);
395             track->duration = track->offsets[track->chunks - 1].time +
396                               track->offsets[track->chunks - 1].duration -
397                               track->offsets[0].time;
398             fprintf(stderr, "Track duration corrected to %"PRId64"\n",
399                     track->duration);
400         }
401     }
402     ret = 0;
403
404 fail:
405     avio_seek(f, pos + size, SEEK_SET);
406     return ret;
407 }
408
409 static int read_mfra(struct Tracks *tracks, int start_index,
410                      const char *file, int split, int ismf,
411                      const char *basename, const char* output_prefix)
412 {
413     int err = 0;
414     const char* err_str = "";
415     AVIOContext *f = NULL;
416     int32_t mfra_size;
417
418     if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
419         goto fail;
420     avio_seek(f, avio_size(f) - 4, SEEK_SET);
421     mfra_size = avio_rb32(f);
422     avio_seek(f, -mfra_size, SEEK_CUR);
423     if (avio_rb32(f) != mfra_size) {
424         err = AVERROR_INVALIDDATA;
425         err_str = "mfra size mismatch";
426         goto fail;
427     }
428     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
429         err = AVERROR_INVALIDDATA;
430         err_str = "mfra tag mismatch";
431         goto fail;
432     }
433     while (!read_tfra(tracks, start_index, f)) {
434         /* Empty */
435     }
436
437     if (split || ismf)
438         err = write_fragments(tracks, start_index, f, basename, split, ismf,
439                               output_prefix);
440     err_str = "error in write_fragments";
441
442 fail:
443     if (f)
444         avio_close(f);
445     if (err)
446         fprintf(stderr, "Unable to read the MFRA atom in %s (%s)\n", file, err_str);
447     return err;
448 }
449
450 static int get_private_data(struct Track *track, AVCodecContext *codec)
451 {
452     track->codec_private_size = 0;
453     track->codec_private      = av_mallocz(codec->extradata_size);
454     if (!track->codec_private)
455         return AVERROR(ENOMEM);
456     track->codec_private_size = codec->extradata_size;
457     memcpy(track->codec_private, codec->extradata, codec->extradata_size);
458     return 0;
459 }
460
461 static int get_video_private_data(struct Track *track, AVCodecContext *codec)
462 {
463     AVIOContext *io = NULL;
464     uint16_t sps_size, pps_size;
465     int err;
466
467     if (codec->codec_id == AV_CODEC_ID_VC1)
468         return get_private_data(track, codec);
469
470     if ((err = avio_open_dyn_buf(&io)) < 0)
471         goto fail;
472     err = AVERROR(EINVAL);
473     if (codec->extradata_size < 11 || codec->extradata[0] != 1)
474         goto fail;
475     sps_size = AV_RB16(&codec->extradata[6]);
476     if (11 + sps_size > codec->extradata_size)
477         goto fail;
478     avio_wb32(io, 0x00000001);
479     avio_write(io, &codec->extradata[8], sps_size);
480     pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
481     if (11 + sps_size + pps_size > codec->extradata_size)
482         goto fail;
483     avio_wb32(io, 0x00000001);
484     avio_write(io, &codec->extradata[11 + sps_size], pps_size);
485     err = 0;
486
487 fail:
488     track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
489     return err;
490 }
491
492 static int handle_file(struct Tracks *tracks, const char *file, int split,
493                        int ismf, const char *basename,
494                        const char* output_prefix)
495 {
496     AVFormatContext *ctx = NULL;
497     int err = 0, i, orig_tracks = tracks->nb_tracks;
498     char errbuf[50], *ptr;
499     struct Track *track;
500
501     err = avformat_open_input(&ctx, file, NULL, NULL);
502     if (err < 0) {
503         av_strerror(err, errbuf, sizeof(errbuf));
504         fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
505         return 1;
506     }
507
508     err = avformat_find_stream_info(ctx, NULL);
509     if (err < 0) {
510         av_strerror(err, errbuf, sizeof(errbuf));
511         fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
512         goto fail;
513     }
514
515     if (ctx->nb_streams < 1) {
516         fprintf(stderr, "No streams found in %s\n", file);
517         goto fail;
518     }
519
520     for (i = 0; i < ctx->nb_streams; i++) {
521         struct Track **temp;
522         AVStream *st = ctx->streams[i];
523
524         if (st->codec->bit_rate == 0) {
525             fprintf(stderr, "Skipping track %d in %s as it has zero bitrate\n",
526                     st->id, file);
527             continue;
528         }
529
530         track = av_mallocz(sizeof(*track));
531         if (!track) {
532             err = AVERROR(ENOMEM);
533             goto fail;
534         }
535         temp = av_realloc_array(tracks->tracks,
536                                 tracks->nb_tracks + 1,
537                                 sizeof(*tracks->tracks));
538         if (!temp) {
539             av_free(track);
540             err = AVERROR(ENOMEM);
541             goto fail;
542         }
543         tracks->tracks = temp;
544         tracks->tracks[tracks->nb_tracks] = track;
545
546         track->name = file;
547         if ((ptr = strrchr(file, '/')))
548             track->name = ptr + 1;
549
550         track->bitrate   = st->codec->bit_rate;
551         track->track_id  = st->id;
552         track->timescale = st->time_base.den;
553         track->duration  = st->duration;
554         track->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
555         track->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
556
557         if (!track->is_audio && !track->is_video) {
558             fprintf(stderr,
559                     "Track %d in %s is neither video nor audio, skipping\n",
560                     track->track_id, file);
561             av_freep(&tracks->tracks[tracks->nb_tracks]);
562             continue;
563         }
564
565         tracks->duration = FFMAX(tracks->duration,
566                                  av_rescale_rnd(track->duration, AV_TIME_BASE,
567                                                 track->timescale, AV_ROUND_UP));
568
569         if (track->is_audio) {
570             if (tracks->audio_track < 0)
571                 tracks->audio_track = tracks->nb_tracks;
572             tracks->nb_audio_tracks++;
573             track->channels    = st->codec->channels;
574             track->sample_rate = st->codec->sample_rate;
575             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
576                 track->fourcc    = "AACL";
577                 track->tag       = 255;
578                 track->blocksize = 4;
579             } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
580                 track->fourcc    = "WMAP";
581                 track->tag       = st->codec->codec_tag;
582                 track->blocksize = st->codec->block_align;
583             }
584             get_private_data(track, st->codec);
585         }
586         if (track->is_video) {
587             if (tracks->video_track < 0)
588                 tracks->video_track = tracks->nb_tracks;
589             tracks->nb_video_tracks++;
590             track->width  = st->codec->width;
591             track->height = st->codec->height;
592             if (st->codec->codec_id == AV_CODEC_ID_H264)
593                 track->fourcc = "H264";
594             else if (st->codec->codec_id == AV_CODEC_ID_VC1)
595                 track->fourcc = "WVC1";
596             get_video_private_data(track, st->codec);
597         }
598
599         tracks->nb_tracks++;
600     }
601
602     avformat_close_input(&ctx);
603
604     err = read_mfra(tracks, orig_tracks, file, split, ismf, basename,
605                     output_prefix);
606
607 fail:
608     if (ctx)
609         avformat_close_input(&ctx);
610     return err;
611 }
612
613 static void output_server_manifest(struct Tracks *tracks, const char *basename,
614                                    const char *output_prefix,
615                                    const char *path_prefix,
616                                    const char *ismc_prefix)
617 {
618     char filename[1000];
619     FILE *out;
620     int i;
621
622     snprintf(filename, sizeof(filename), "%s%s.ism", output_prefix, basename);
623     out = fopen(filename, "w");
624     if (!out) {
625         perror(filename);
626         return;
627     }
628     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
629     fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
630     fprintf(out, "\t<head>\n");
631     fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
632                  "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
633     fprintf(out, "\t</head>\n");
634     fprintf(out, "\t<body>\n");
635     fprintf(out, "\t\t<switch>\n");
636     for (i = 0; i < tracks->nb_tracks; i++) {
637         struct Track *track = tracks->tracks[i];
638         const char *type    = track->is_video ? "video" : "audio";
639         fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
640                 type, path_prefix, track->name, track->bitrate);
641         fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
642                      "valueType=\"data\" />\n", track->track_id);
643         fprintf(out, "\t\t\t</%s>\n", type);
644     }
645     fprintf(out, "\t\t</switch>\n");
646     fprintf(out, "\t</body>\n");
647     fprintf(out, "</smil>\n");
648     fclose(out);
649 }
650
651 static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
652                                const char *type)
653 {
654     int i, j;
655     int64_t pos = 0;
656     struct Track *track = tracks->tracks[main];
657     int should_print_time_mismatch = 1;
658
659     for (i = 0; i < track->chunks; i++) {
660         for (j = main + 1; j < tracks->nb_tracks; j++) {
661             if (tracks->tracks[j]->is_audio == track->is_audio) {
662                 if (track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration) {
663                     fprintf(stderr, "Mismatched duration of %s chunk %d in %s (%d) and %s (%d)\n",
664                             type, i, track->name, main, tracks->tracks[j]->name, j);
665                     should_print_time_mismatch = 1;
666                 }
667                 if (track->offsets[i].time != tracks->tracks[j]->offsets[i].time) {
668                     if (should_print_time_mismatch)
669                         fprintf(stderr, "Mismatched (start) time of %s chunk %d in %s (%d) and %s (%d)\n",
670                                 type, i, track->name, main, tracks->tracks[j]->name, j);
671                     should_print_time_mismatch = 0;
672                 }
673             }
674         }
675         fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" ",
676                 i, track->offsets[i].duration);
677         if (pos != track->offsets[i].time) {
678             fprintf(out, "t=\"%"PRId64"\" ", track->offsets[i].time);
679             pos = track->offsets[i].time;
680         }
681         pos += track->offsets[i].duration;
682         fprintf(out, "/>\n");
683     }
684 }
685
686 static void output_client_manifest(struct Tracks *tracks, const char *basename,
687                                    const char *output_prefix, int split)
688 {
689     char filename[1000];
690     FILE *out;
691     int i, j;
692
693     if (split)
694         snprintf(filename, sizeof(filename), "%sManifest", output_prefix);
695     else
696         snprintf(filename, sizeof(filename), "%s%s.ismc", output_prefix, basename);
697     out = fopen(filename, "w");
698     if (!out) {
699         perror(filename);
700         return;
701     }
702     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
703     fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
704                  "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
705     if (tracks->video_track >= 0) {
706         struct Track *track = tracks->tracks[tracks->video_track];
707         struct Track *first_track = track;
708         int index = 0;
709         fprintf(out,
710                 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
711                 "Chunks=\"%d\" "
712                 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
713                 tracks->nb_video_tracks, track->chunks);
714         for (i = 0; i < tracks->nb_tracks; i++) {
715             track = tracks->tracks[i];
716             if (!track->is_video)
717                 continue;
718             fprintf(out,
719                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
720                     "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
721                     "CodecPrivateData=\"",
722                     index, track->bitrate, track->fourcc, track->width, track->height);
723             for (j = 0; j < track->codec_private_size; j++)
724                 fprintf(out, "%02X", track->codec_private[j]);
725             fprintf(out, "\" />\n");
726             index++;
727             if (track->chunks != first_track->chunks)
728                 fprintf(stderr, "Mismatched number of video chunks in %s (id: %d, chunks %d) and %s (id: %d, chunks %d)\n",
729                         track->name, track->track_id, track->chunks, first_track->name, first_track->track_id, first_track->chunks);
730         }
731         print_track_chunks(out, tracks, tracks->video_track, "video");
732         fprintf(out, "\t</StreamIndex>\n");
733     }
734     if (tracks->audio_track >= 0) {
735         struct Track *track = tracks->tracks[tracks->audio_track];
736         struct Track *first_track = track;
737         int index = 0;
738         fprintf(out,
739                 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
740                 "Chunks=\"%d\" "
741                 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
742                 tracks->nb_audio_tracks, track->chunks);
743         for (i = 0; i < tracks->nb_tracks; i++) {
744             track = tracks->tracks[i];
745             if (!track->is_audio)
746                 continue;
747             fprintf(out,
748                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
749                     "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
750                     "BitsPerSample=\"16\" PacketSize=\"%d\" "
751                     "AudioTag=\"%d\" CodecPrivateData=\"",
752                     index, track->bitrate, track->fourcc, track->sample_rate,
753                     track->channels, track->blocksize, track->tag);
754             for (j = 0; j < track->codec_private_size; j++)
755                 fprintf(out, "%02X", track->codec_private[j]);
756             fprintf(out, "\" />\n");
757             index++;
758             if (track->chunks != first_track->chunks)
759                 fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
760                         track->name, first_track->name);
761         }
762         print_track_chunks(out, tracks, tracks->audio_track, "audio");
763         fprintf(out, "\t</StreamIndex>\n");
764     }
765     fprintf(out, "</SmoothStreamingMedia>\n");
766     fclose(out);
767 }
768
769 static void clean_tracks(struct Tracks *tracks)
770 {
771     int i;
772     for (i = 0; i < tracks->nb_tracks; i++) {
773         av_freep(&tracks->tracks[i]->codec_private);
774         av_freep(&tracks->tracks[i]->offsets);
775         av_freep(&tracks->tracks[i]);
776     }
777     av_freep(&tracks->tracks);
778     tracks->nb_tracks = 0;
779 }
780
781 int main(int argc, char **argv)
782 {
783     const char *basename = NULL;
784     const char *path_prefix = "", *ismc_prefix = "";
785     const char *output_prefix = "";
786     char output_prefix_buf[2048];
787     int split = 0, ismf = 0, i;
788     struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
789
790     av_register_all();
791
792     for (i = 1; i < argc; i++) {
793         if (!strcmp(argv[i], "-n")) {
794             basename = argv[i + 1];
795             i++;
796         } else if (!strcmp(argv[i], "-path-prefix")) {
797             path_prefix = argv[i + 1];
798             i++;
799         } else if (!strcmp(argv[i], "-ismc-prefix")) {
800             ismc_prefix = argv[i + 1];
801             i++;
802         } else if (!strcmp(argv[i], "-output")) {
803             output_prefix = argv[i + 1];
804             i++;
805             if (output_prefix[strlen(output_prefix) - 1] != '/') {
806                 snprintf(output_prefix_buf, sizeof(output_prefix_buf),
807                          "%s/", output_prefix);
808                 output_prefix = output_prefix_buf;
809             }
810         } else if (!strcmp(argv[i], "-split")) {
811             split = 1;
812         } else if (!strcmp(argv[i], "-ismf")) {
813             ismf = 1;
814         } else if (argv[i][0] == '-') {
815             return usage(argv[0], 1);
816         } else {
817             if (!basename)
818                 ismf = 0;
819             if (handle_file(&tracks, argv[i], split, ismf,
820                             basename, output_prefix))
821                 return 1;
822         }
823     }
824     if (!tracks.nb_tracks || (!basename && !split))
825         return usage(argv[0], 1);
826
827     if (!split)
828         output_server_manifest(&tracks, basename, output_prefix,
829                                path_prefix, ismc_prefix);
830     output_client_manifest(&tracks, basename, output_prefix, split);
831
832     clean_tracks(&tracks);
833
834     return 0;
835 }