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