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