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