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