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