ismindex: Calculate the file duration among the included tracks
[ffmpeg.git] / tools / ismindex.c
1 /*
2  * Copyright (c) 2012 Martin Storsjo
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /*
22  * To create a simple file for smooth streaming:
23  * avconv <normal input/transcoding options> -movflags frag_keyframe foo.ismv
24  * ismindex -n foo foo.ismv
25  * This step creates foo.ism and foo.ismc that is required by IIS for
26  * serving it.
27  *
28  * To pre-split files for serving as static files by a web server without
29  * any extra server support, create the ismv file as above, and split it:
30  * ismindex -split foo.ismv
31  * This step creates a file Manifest and directories QualityLevel(...),
32  * that can be read directly by a smooth streaming player.
33  */
34
35 #include <stdio.h>
36 #include <string.h>
37
38 #include "libavformat/avformat.h"
39 #include "libavformat/os_support.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/mathematics.h"
42
43 static int usage(const char *argv0, int ret)
44 {
45     fprintf(stderr, "%s [-split] [-n basename] file1 [file2] ...\n", argv0);
46     return ret;
47 }
48
49 struct MoofOffset {
50     int64_t time;
51     int64_t offset;
52     int duration;
53 };
54
55 struct Track {
56     const char *name;
57     int64_t duration;
58     int bitrate;
59     int track_id;
60     int is_audio, is_video;
61     int width, height;
62     int chunks;
63     int sample_rate, channels;
64     uint8_t *codec_private;
65     int codec_private_size;
66     struct MoofOffset *offsets;
67     int timescale;
68     const char *fourcc;
69     int blocksize;
70     int tag;
71 };
72
73 struct Tracks {
74     int nb_tracks;
75     int64_t duration;
76     struct Track **tracks;
77     int video_track, audio_track;
78     int nb_video_tracks, nb_audio_tracks;
79 };
80
81 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
82 {
83     int32_t size, tag;
84
85     size = avio_rb32(in);
86     tag  = avio_rb32(in);
87     avio_wb32(out, size);
88     avio_wb32(out, tag);
89     if (tag != tag_name)
90         return -1;
91     size -= 8;
92     while (size > 0) {
93         char buf[1024];
94         int len = FFMIN(sizeof(buf), size);
95         if (avio_read(in, buf, len) != len)
96             break;
97         avio_write(out, buf, len);
98         size -= len;
99     }
100     return 0;
101 }
102
103 static int write_fragment(const char *filename, AVIOContext *in)
104 {
105     AVIOContext *out = NULL;
106     int ret;
107
108     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
109         return ret;
110     copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
111     copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
112
113     avio_flush(out);
114     avio_close(out);
115
116     return ret;
117 }
118
119 static int write_fragments(struct Tracks *tracks, int start_index,
120                            AVIOContext *in)
121 {
122     char dirname[100], filename[500];
123     int i, j;
124
125     for (i = start_index; i < tracks->nb_tracks; i++) {
126         struct Track *track = tracks->tracks[i];
127         const char *type    = track->is_video ? "video" : "audio";
128         snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", track->bitrate);
129         mkdir(dirname, 0777);
130         for (j = 0; j < track->chunks; j++) {
131             snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
132                      dirname, type, track->offsets[j].time);
133             avio_seek(in, track->offsets[j].offset, SEEK_SET);
134             write_fragment(filename, in);
135         }
136     }
137     return 0;
138 }
139
140 static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
141 {
142     int ret = AVERROR_EOF, track_id;
143     int version, fieldlength, i, j;
144     int64_t pos   = avio_tell(f);
145     uint32_t size = avio_rb32(f);
146     struct Track *track = NULL;
147
148     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
149         goto fail;
150     version = avio_r8(f);
151     avio_rb24(f);
152     track_id = avio_rb32(f); /* track id */
153     for (i = start_index; i < tracks->nb_tracks && !track; i++)
154         if (tracks->tracks[i]->track_id == track_id)
155             track = tracks->tracks[i];
156     if (!track) {
157         /* Ok, continue parsing the next atom */
158         ret = 0;
159         goto fail;
160     }
161     fieldlength = avio_rb32(f);
162     track->chunks  = avio_rb32(f);
163     track->offsets = av_mallocz(sizeof(*track->offsets) * track->chunks);
164     if (!track->offsets) {
165         ret = AVERROR(ENOMEM);
166         goto fail;
167     }
168     for (i = 0; i < track->chunks; i++) {
169         if (version == 1) {
170             track->offsets[i].time   = avio_rb64(f);
171             track->offsets[i].offset = avio_rb64(f);
172         } else {
173             track->offsets[i].time   = avio_rb32(f);
174             track->offsets[i].offset = avio_rb32(f);
175         }
176         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
177             avio_r8(f);
178         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
179             avio_r8(f);
180         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
181             avio_r8(f);
182         if (i > 0)
183             track->offsets[i - 1].duration = track->offsets[i].time -
184                                              track->offsets[i - 1].time;
185     }
186     if (track->chunks > 0)
187         track->offsets[track->chunks - 1].duration = track->duration -
188                                                      track->offsets[track->chunks - 1].time;
189     ret = 0;
190
191 fail:
192     avio_seek(f, pos + size, SEEK_SET);
193     return ret;
194 }
195
196 static int read_mfra(struct Tracks *tracks, int start_index,
197                      const char *file, int split)
198 {
199     int err = 0;
200     AVIOContext *f = NULL;
201     int32_t mfra_size;
202
203     if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
204         goto fail;
205     avio_seek(f, avio_size(f) - 4, SEEK_SET);
206     mfra_size = avio_rb32(f);
207     avio_seek(f, -mfra_size, SEEK_CUR);
208     if (avio_rb32(f) != mfra_size) {
209         err = AVERROR_INVALIDDATA;
210         goto fail;
211     }
212     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
213         err = AVERROR_INVALIDDATA;
214         goto fail;
215     }
216     while (!read_tfra(tracks, start_index, f)) {
217         /* Empty */
218     }
219
220     if (split)
221         write_fragments(tracks, start_index, f);
222
223 fail:
224     if (f)
225         avio_close(f);
226     if (err)
227         fprintf(stderr, "Unable to read the MFRA atom in %s\n", file);
228     return err;
229 }
230
231 static int get_private_data(struct Track *track, AVCodecContext *codec)
232 {
233     track->codec_private_size = codec->extradata_size;
234     track->codec_private      = av_mallocz(codec->extradata_size);
235     if (!track->codec_private)
236         return AVERROR(ENOMEM);
237     memcpy(track->codec_private, codec->extradata, codec->extradata_size);
238     return 0;
239 }
240
241 static int get_video_private_data(struct Track *track, AVCodecContext *codec)
242 {
243     AVIOContext *io = NULL;
244     uint16_t sps_size, pps_size;
245     int err = AVERROR(EINVAL);
246
247     if (codec->codec_id == AV_CODEC_ID_VC1)
248         return get_private_data(track, codec);
249
250     avio_open_dyn_buf(&io);
251     if (codec->extradata_size < 11 || codec->extradata[0] != 1)
252         goto fail;
253     sps_size = AV_RB16(&codec->extradata[6]);
254     if (11 + sps_size > codec->extradata_size)
255         goto fail;
256     avio_wb32(io, 0x00000001);
257     avio_write(io, &codec->extradata[8], sps_size);
258     pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
259     if (11 + sps_size + pps_size > codec->extradata_size)
260         goto fail;
261     avio_wb32(io, 0x00000001);
262     avio_write(io, &codec->extradata[11 + sps_size], pps_size);
263     err = 0;
264
265 fail:
266     track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
267     return err;
268 }
269
270 static int handle_file(struct Tracks *tracks, const char *file, int split)
271 {
272     AVFormatContext *ctx = NULL;
273     int err = 0, i, orig_tracks = tracks->nb_tracks;
274     char errbuf[50], *ptr;
275     struct Track *track;
276
277     err = avformat_open_input(&ctx, file, NULL, NULL);
278     if (err < 0) {
279         av_strerror(err, errbuf, sizeof(errbuf));
280         fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
281         return 1;
282     }
283
284     err = avformat_find_stream_info(ctx, NULL);
285     if (err < 0) {
286         av_strerror(err, errbuf, sizeof(errbuf));
287         fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
288         goto fail;
289     }
290
291     if (ctx->nb_streams < 1) {
292         fprintf(stderr, "No streams found in %s\n", file);
293         goto fail;
294     }
295
296     for (i = 0; i < ctx->nb_streams; i++) {
297         struct Track **temp;
298         AVStream *st = ctx->streams[i];
299         track = av_mallocz(sizeof(*track));
300         if (!track) {
301             err = AVERROR(ENOMEM);
302             goto fail;
303         }
304         temp = av_realloc(tracks->tracks,
305                           sizeof(*tracks->tracks) * (tracks->nb_tracks + 1));
306         if (!temp) {
307             av_free(track);
308             err = AVERROR(ENOMEM);
309             goto fail;
310         }
311         tracks->tracks = temp;
312         tracks->tracks[tracks->nb_tracks] = track;
313
314         track->name = file;
315         if ((ptr = strrchr(file, '/')) != NULL)
316             track->name = ptr + 1;
317
318         track->bitrate   = st->codec->bit_rate;
319         track->track_id  = st->id;
320         track->timescale = st->time_base.den;
321         track->duration  = st->duration;
322         track->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
323         track->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
324
325         if (!track->is_audio && !track->is_video) {
326             fprintf(stderr,
327                     "Track %d in %s is neither video nor audio, skipping\n",
328                     track->track_id, file);
329             av_freep(&tracks->tracks[tracks->nb_tracks]);
330             continue;
331         }
332
333         tracks->duration = FFMAX(tracks->duration,
334                                  av_rescale_rnd(track->duration, AV_TIME_BASE,
335                                                 track->timescale, AV_ROUND_UP));
336
337         if (track->is_audio) {
338             if (tracks->audio_track < 0)
339                 tracks->audio_track = tracks->nb_tracks;
340             tracks->nb_audio_tracks++;
341             track->channels    = st->codec->channels;
342             track->sample_rate = st->codec->sample_rate;
343             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
344                 track->fourcc    = "AACL";
345                 track->tag       = 255;
346                 track->blocksize = 4;
347             } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
348                 track->fourcc    = "WMAP";
349                 track->tag       = st->codec->codec_tag;
350                 track->blocksize = st->codec->block_align;
351             }
352             get_private_data(track, st->codec);
353         }
354         if (track->is_video) {
355             if (tracks->video_track < 0)
356                 tracks->video_track = tracks->nb_tracks;
357             tracks->nb_video_tracks++;
358             track->width  = st->codec->width;
359             track->height = st->codec->height;
360             if (st->codec->codec_id == AV_CODEC_ID_H264)
361                 track->fourcc = "H264";
362             else if (st->codec->codec_id == AV_CODEC_ID_VC1)
363                 track->fourcc = "WVC1";
364             get_video_private_data(track, st->codec);
365         }
366
367         tracks->nb_tracks++;
368     }
369
370     avformat_close_input(&ctx);
371
372     err = read_mfra(tracks, orig_tracks, file, split);
373
374 fail:
375     if (ctx)
376         avformat_close_input(&ctx);
377     return err;
378 }
379
380 static void output_server_manifest(struct Tracks *tracks,
381                                    const char *basename)
382 {
383     char filename[1000];
384     FILE *out;
385     int i;
386
387     snprintf(filename, sizeof(filename), "%s.ism", basename);
388     out = fopen(filename, "w");
389     if (!out) {
390         perror(filename);
391         return;
392     }
393     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
394     fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
395     fprintf(out, "\t<head>\n");
396     fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
397                  "content=\"%s.ismc\" />\n", basename);
398     fprintf(out, "\t</head>\n");
399     fprintf(out, "\t<body>\n");
400     fprintf(out, "\t\t<switch>\n");
401     for (i = 0; i < tracks->nb_tracks; i++) {
402         struct Track *track = tracks->tracks[i];
403         const char *type    = track->is_video ? "video" : "audio";
404         fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
405                 type, track->name, track->bitrate);
406         fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
407                      "valueType=\"data\" />\n", track->track_id);
408         fprintf(out, "\t\t\t</%s>\n", type);
409     }
410     fprintf(out, "\t\t</switch>\n");
411     fprintf(out, "\t</body>\n");
412     fprintf(out, "</smil>\n");
413     fclose(out);
414 }
415
416 static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
417                                const char *type)
418 {
419     int i, j;
420     struct Track *track = tracks->tracks[main];
421     for (i = 0; i < track->chunks; i++) {
422         for (j = main + 1; j < tracks->nb_tracks; j++) {
423             if (tracks->tracks[j]->is_audio == track->is_audio &&
424                 track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration)
425                 fprintf(stderr, "Mismatched duration of %s chunk %d in %s and %s\n",
426                         type, i, track->name, tracks->tracks[j]->name);
427         }
428         fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",
429                 i, track->offsets[i].duration);
430     }
431 }
432
433 static void output_client_manifest(struct Tracks *tracks,
434                                    const char *basename, int split)
435 {
436     char filename[1000];
437     FILE *out;
438     int i, j;
439
440     if (split)
441         snprintf(filename, sizeof(filename), "Manifest");
442     else
443         snprintf(filename, sizeof(filename), "%s.ismc", basename);
444     out = fopen(filename, "w");
445     if (!out) {
446         perror(filename);
447         return;
448     }
449     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
450     fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
451                  "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
452     if (tracks->video_track >= 0) {
453         struct Track *track = tracks->tracks[tracks->video_track];
454         struct Track *first_track = track;
455         int index = 0;
456         fprintf(out,
457                 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
458                 "Chunks=\"%d\" "
459                 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
460                 tracks->nb_video_tracks, track->chunks);
461         for (i = 0; i < tracks->nb_tracks; i++) {
462             track = tracks->tracks[i];
463             if (!track->is_video)
464                 continue;
465             fprintf(out,
466                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
467                     "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
468                     "CodecPrivateData=\"",
469                     index, track->bitrate, track->fourcc, track->width, track->height);
470             for (j = 0; j < track->codec_private_size; j++)
471                 fprintf(out, "%02X", track->codec_private[j]);
472             fprintf(out, "\" />\n");
473             index++;
474             if (track->chunks != first_track->chunks)
475                 fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
476                         track->name, first_track->name);
477         }
478         print_track_chunks(out, tracks, tracks->video_track, "video");
479         fprintf(out, "\t</StreamIndex>\n");
480     }
481     if (tracks->audio_track >= 0) {
482         struct Track *track = tracks->tracks[tracks->audio_track];
483         struct Track *first_track = track;
484         int index = 0;
485         fprintf(out,
486                 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
487                 "Chunks=\"%d\" "
488                 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
489                 tracks->nb_audio_tracks, track->chunks);
490         for (i = 0; i < tracks->nb_tracks; i++) {
491             track = tracks->tracks[i];
492             if (!track->is_audio)
493                 continue;
494             fprintf(out,
495                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
496                     "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
497                     "BitsPerSample=\"16\" PacketSize=\"%d\" "
498                     "AudioTag=\"%d\" CodecPrivateData=\"",
499                     index, track->bitrate, track->fourcc, track->sample_rate,
500                     track->channels, track->blocksize, track->tag);
501             for (j = 0; j < track->codec_private_size; j++)
502                 fprintf(out, "%02X", track->codec_private[j]);
503             fprintf(out, "\" />\n");
504             index++;
505             if (track->chunks != first_track->chunks)
506                 fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
507                         track->name, first_track->name);
508         }
509         print_track_chunks(out, tracks, tracks->audio_track, "audio");
510         fprintf(out, "\t</StreamIndex>\n");
511     }
512     fprintf(out, "</SmoothStreamingMedia>\n");
513     fclose(out);
514 }
515
516 static void clean_tracks(struct Tracks *tracks)
517 {
518     int i;
519     for (i = 0; i < tracks->nb_tracks; i++) {
520         av_freep(&tracks->tracks[i]->codec_private);
521         av_freep(&tracks->tracks[i]->offsets);
522         av_freep(&tracks->tracks[i]);
523     }
524     av_freep(&tracks->tracks);
525     tracks->nb_tracks = 0;
526 }
527
528 int main(int argc, char **argv)
529 {
530     const char *basename = NULL;
531     int split = 0, i;
532     struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
533
534     av_register_all();
535
536     for (i = 1; i < argc; i++) {
537         if (!strcmp(argv[i], "-n")) {
538             basename = argv[i + 1];
539             i++;
540         } else if (!strcmp(argv[i], "-split")) {
541             split = 1;
542         } else if (argv[i][0] == '-') {
543             return usage(argv[0], 1);
544         } else {
545             if (handle_file(&tracks, argv[i], split))
546                 return 1;
547         }
548     }
549     if (!tracks.nb_tracks || (!basename && !split))
550         return usage(argv[0], 1);
551
552     if (!split)
553         output_server_manifest(&tracks, basename);
554     output_client_manifest(&tracks, basename, split);
555
556     clean_tracks(&tracks);
557
558     return 0;
559 }