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