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