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