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