]> git.sesse.net Git - ffmpeg/blob - tools/ismindex.c
Merge commit '73b704ac609d83e0be124589f24efd9b94947cf9'
[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 "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 VideoFile {
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 VideoFiles {
78     int nb_files;
79     int64_t duration;
80     struct VideoFile **files;
81     int video_file, audio_file;
82     int nb_video_files, nb_audio_files;
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 VideoFiles *files, int start_index,
124                            AVIOContext *in)
125 {
126     char dirname[100], filename[500];
127     int i, j;
128
129     for (i = start_index; i < files->nb_files; i++) {
130         struct VideoFile *vf = files->files[i];
131         const char *type     = vf->is_video ? "video" : "audio";
132         snprintf(dirname, sizeof(dirname), "QualityLevels(%d)", vf->bitrate);
133         mkdir(dirname, 0777);
134         for (j = 0; j < vf->chunks; j++) {
135             snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
136                      dirname, type, vf->offsets[j].time);
137             avio_seek(in, vf->offsets[j].offset, SEEK_SET);
138             write_fragment(filename, in);
139         }
140     }
141     return 0;
142 }
143
144 static int read_tfra(struct VideoFiles *files, 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 VideoFile *vf = 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 < files->nb_files && !vf; i++)
158         if (files->files[i]->track_id == track_id)
159             vf = files->files[i];
160     if (!vf) {
161         /* Ok, continue parsing the next atom */
162         ret = 0;
163         goto fail;
164     }
165     fieldlength = avio_rb32(f);
166     vf->chunks  = avio_rb32(f);
167     vf->offsets = av_mallocz(sizeof(*vf->offsets) * vf->chunks);
168     if (!vf->offsets) {
169         ret = AVERROR(ENOMEM);
170         goto fail;
171     }
172     for (i = 0; i < vf->chunks; i++) {
173         if (version == 1) {
174             vf->offsets[i].time   = avio_rb64(f);
175             vf->offsets[i].offset = avio_rb64(f);
176         } else {
177             vf->offsets[i].time   = avio_rb32(f);
178             vf->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             vf->offsets[i - 1].duration = vf->offsets[i].time -
188                                           vf->offsets[i - 1].time;
189     }
190     if (vf->chunks > 0)
191         vf->offsets[vf->chunks - 1].duration = vf->duration -
192                                                vf->offsets[vf->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 VideoFiles *files, 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(files, start_index, f)) {
221         /* Empty */
222     }
223
224     if (split)
225         write_fragments(files, 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 VideoFile *vf, AVCodecContext *codec)
236 {
237     vf->codec_private_size = codec->extradata_size;
238     vf->codec_private      = av_mallocz(codec->extradata_size);
239     if (!vf->codec_private)
240         return AVERROR(ENOMEM);
241     memcpy(vf->codec_private, codec->extradata, codec->extradata_size);
242     return 0;
243 }
244
245 static int get_video_private_data(struct VideoFile *vf, 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(vf, codec);
253
254     if (avio_open_dyn_buf(&io) < 0)  {
255         err = AVERROR(ENOMEM);
256         goto fail;
257     }
258     if (codec->extradata_size < 11 || codec->extradata[0] != 1)
259         goto fail;
260     sps_size = AV_RB16(&codec->extradata[6]);
261     if (11 + sps_size > codec->extradata_size)
262         goto fail;
263     avio_wb32(io, 0x00000001);
264     avio_write(io, &codec->extradata[8], sps_size);
265     pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
266     if (11 + sps_size + pps_size > codec->extradata_size)
267         goto fail;
268     avio_wb32(io, 0x00000001);
269     avio_write(io, &codec->extradata[11 + sps_size], pps_size);
270     err = 0;
271
272 fail:
273     vf->codec_private_size = avio_close_dyn_buf(io, &vf->codec_private);
274     return err;
275 }
276
277 static int handle_file(struct VideoFiles *files, const char *file, int split)
278 {
279     AVFormatContext *ctx = NULL;
280     int err = 0, i, orig_files = files->nb_files;
281     char errbuf[50], *ptr;
282     struct VideoFile *vf;
283
284     err = avformat_open_input(&ctx, file, NULL, NULL);
285     if (err < 0) {
286         av_strerror(err, errbuf, sizeof(errbuf));
287         fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
288         return 1;
289     }
290
291     err = avformat_find_stream_info(ctx, NULL);
292     if (err < 0) {
293         av_strerror(err, errbuf, sizeof(errbuf));
294         fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
295         goto fail;
296     }
297
298     if (ctx->nb_streams < 1) {
299         fprintf(stderr, "No streams found in %s\n", file);
300         goto fail;
301     }
302     if (!files->duration)
303         files->duration = ctx->duration;
304
305     for (i = 0; i < ctx->nb_streams; i++) {
306         AVStream *st = ctx->streams[i];
307         vf = av_mallocz(sizeof(*vf));
308         files->files = av_realloc(files->files,
309                                   sizeof(*files->files) * (files->nb_files + 1));
310         files->files[files->nb_files] = vf;
311
312         vf->name = file;
313         if ((ptr = strrchr(file, '/')) != NULL)
314             vf->name = ptr + 1;
315
316         vf->bitrate   = st->codec->bit_rate;
317         vf->track_id  = st->id;
318         vf->timescale = st->time_base.den;
319         vf->duration  = av_rescale_rnd(ctx->duration, vf->timescale,
320                                        AV_TIME_BASE, AV_ROUND_UP);
321         vf->is_audio  = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
322         vf->is_video  = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
323
324         if (!vf->is_audio && !vf->is_video) {
325             fprintf(stderr,
326                     "Track %d in %s is neither video nor audio, skipping\n",
327                     vf->track_id, file);
328             av_freep(&files->files[files->nb_files]);
329             continue;
330         }
331
332         if (vf->is_audio) {
333             if (files->audio_file < 0)
334                 files->audio_file = files->nb_files;
335             files->nb_audio_files++;
336             vf->channels    = st->codec->channels;
337             vf->sample_rate = st->codec->sample_rate;
338             if (st->codec->codec_id == AV_CODEC_ID_AAC) {
339                 vf->fourcc    = "AACL";
340                 vf->tag       = 255;
341                 vf->blocksize = 4;
342             } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
343                 vf->fourcc    = "WMAP";
344                 vf->tag       = st->codec->codec_tag;
345                 vf->blocksize = st->codec->block_align;
346             }
347             get_private_data(vf, st->codec);
348         }
349         if (vf->is_video) {
350             if (files->video_file < 0)
351                 files->video_file = files->nb_files;
352             files->nb_video_files++;
353             vf->width  = st->codec->width;
354             vf->height = st->codec->height;
355             if (st->codec->codec_id == AV_CODEC_ID_H264)
356                 vf->fourcc = "H264";
357             else if (st->codec->codec_id == AV_CODEC_ID_VC1)
358                 vf->fourcc = "WVC1";
359             get_video_private_data(vf, st->codec);
360         }
361
362         files->nb_files++;
363     }
364
365     avformat_close_input(&ctx);
366
367     err = read_mfra(files, orig_files, file, split);
368
369 fail:
370     if (ctx)
371         avformat_close_input(&ctx);
372     return err;
373 }
374
375 static void output_server_manifest(struct VideoFiles *files,
376                                    const char *basename)
377 {
378     char filename[1000];
379     FILE *out;
380     int i;
381
382     snprintf(filename, sizeof(filename), "%s.ism", basename);
383     out = fopen(filename, "w");
384     if (!out) {
385         perror(filename);
386         return;
387     }
388     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
389     fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
390     fprintf(out, "\t<head>\n");
391     fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
392                  "content=\"%s.ismc\" />\n", basename);
393     fprintf(out, "\t</head>\n");
394     fprintf(out, "\t<body>\n");
395     fprintf(out, "\t\t<switch>\n");
396     for (i = 0; i < files->nb_files; i++) {
397         struct VideoFile *vf = files->files[i];
398         const char *type     = vf->is_video ? "video" : "audio";
399         fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
400                 type, vf->name, vf->bitrate);
401         fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
402                      "valueType=\"data\" />\n", vf->track_id);
403         fprintf(out, "\t\t\t</%s>\n", type);
404     }
405     fprintf(out, "\t\t</switch>\n");
406     fprintf(out, "\t</body>\n");
407     fprintf(out, "</smil>\n");
408     fclose(out);
409 }
410
411 static void output_client_manifest(struct VideoFiles *files,
412                                    const char *basename, int split)
413 {
414     char filename[1000];
415     FILE *out;
416     int i, j;
417
418     if (split)
419         snprintf(filename, sizeof(filename), "Manifest");
420     else
421         snprintf(filename, sizeof(filename), "%s.ismc", basename);
422     out = fopen(filename, "w");
423     if (!out) {
424         perror(filename);
425         return;
426     }
427     fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
428     fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
429                  "Duration=\"%"PRId64 "\">\n", files->duration * 10);
430     if (files->video_file >= 0) {
431         struct VideoFile *vf = files->files[files->video_file];
432         struct VideoFile *first_vf = vf;
433         int index = 0;
434         fprintf(out,
435                 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
436                 "Chunks=\"%d\" "
437                 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
438                 files->nb_video_files, vf->chunks);
439         for (i = 0; i < files->nb_files; i++) {
440             vf = files->files[i];
441             if (!vf->is_video)
442                 continue;
443             fprintf(out,
444                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
445                     "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
446                     "CodecPrivateData=\"",
447                     index, vf->bitrate, vf->fourcc, vf->width, vf->height);
448             for (j = 0; j < vf->codec_private_size; j++)
449                 fprintf(out, "%02X", vf->codec_private[j]);
450             fprintf(out, "\" />\n");
451             index++;
452             if (vf->chunks != first_vf->chunks)
453                 fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
454                         vf->name, first_vf->name);
455         }
456         vf = first_vf;
457         for (i = 0; i < vf->chunks; i++) {
458             for (j = files->video_file + 1; j < files->nb_files; j++) {
459                 if (files->files[j]->is_video &&
460                     vf->offsets[i].duration != files->files[j]->offsets[i].duration)
461                     fprintf(stderr, "Mismatched duration of video chunk %d in %s and %s\n",
462                             i, vf->name, files->files[j]->name);
463             }
464             fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n", i,
465                     vf->offsets[i].duration);
466         }
467         fprintf(out, "\t</StreamIndex>\n");
468     }
469     if (files->audio_file >= 0) {
470         struct VideoFile *vf = files->files[files->audio_file];
471         struct VideoFile *first_vf = vf;
472         int index = 0;
473         fprintf(out,
474                 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
475                 "Chunks=\"%d\" "
476                 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
477                 files->nb_audio_files, vf->chunks);
478         for (i = 0; i < files->nb_files; i++) {
479             vf = files->files[i];
480             if (!vf->is_audio)
481                 continue;
482             fprintf(out,
483                     "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
484                     "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
485                     "BitsPerSample=\"16\" PacketSize=\"%d\" "
486                     "AudioTag=\"%d\" CodecPrivateData=\"",
487                     index, vf->bitrate, vf->fourcc, vf->sample_rate,
488                     vf->channels, vf->blocksize, vf->tag);
489             for (j = 0; j < vf->codec_private_size; j++)
490                 fprintf(out, "%02X", vf->codec_private[j]);
491             fprintf(out, "\" />\n");
492             index++;
493             if (vf->chunks != first_vf->chunks)
494                 fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
495                         vf->name, first_vf->name);
496         }
497         vf = first_vf;
498         for (i = 0; i < vf->chunks; i++) {
499             for (j = files->audio_file + 1; j < files->nb_files; j++) {
500                 if (files->files[j]->is_audio &&
501                     vf->offsets[i].duration != files->files[j]->offsets[i].duration)
502                     fprintf(stderr, "Mismatched duration of audio chunk %d in %s and %s\n",
503                             i, vf->name, files->files[j]->name);
504             }
505             fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",
506                     i, vf->offsets[i].duration);
507         }
508         fprintf(out, "\t</StreamIndex>\n");
509     }
510     fprintf(out, "</SmoothStreamingMedia>\n");
511     fclose(out);
512 }
513
514 static void clean_files(struct VideoFiles *files)
515 {
516     int i;
517     for (i = 0; i < files->nb_files; i++) {
518         av_freep(&files->files[i]->codec_private);
519         av_freep(&files->files[i]->offsets);
520         av_freep(&files->files[i]);
521     }
522     av_freep(&files->files);
523     files->nb_files = 0;
524 }
525
526 int main(int argc, char **argv)
527 {
528     const char *basename = NULL;
529     int split = 0, i;
530     struct VideoFiles vf = { 0, .video_file = -1, .audio_file = -1 };
531
532     av_register_all();
533
534     for (i = 1; i < argc; i++) {
535         if (!strcmp(argv[i], "-n")) {
536             basename = argv[i + 1];
537             i++;
538         } else if (!strcmp(argv[i], "-split")) {
539             split = 1;
540         } else if (argv[i][0] == '-') {
541             return usage(argv[0], 1);
542         } else {
543             if (handle_file(&vf, argv[i], split))
544                 return 1;
545         }
546     }
547     if (!vf.nb_files || (!basename && !split))
548         return usage(argv[0], 1);
549
550     if (!split)
551         output_server_manifest(&vf, basename);
552     output_client_manifest(&vf, basename, split);
553
554     clean_files(&vf);
555
556     return 0;
557 }