2 * Copyright (c) 2012 Martin Storsjo
4 * This file is part of Libav.
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.
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.
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
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
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.
40 #define mkdir(a, b) mkdir(a)
43 #include "libavformat/avformat.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/mathematics.h"
47 static int usage(const char *argv0, int ret)
49 fprintf(stderr, "%s [-split] [-n basename] file1 [file2] ...\n", argv0);
64 int is_audio, is_video;
67 int sample_rate, channels;
68 uint8_t *codec_private;
69 int codec_private_size;
70 struct MoofOffset *offsets;
80 struct VideoFile **files;
81 int video_file, audio_file;
82 int nb_video_files, nb_audio_files;
85 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
98 int len = FFMIN(sizeof(buf), size);
99 if (avio_read(in, buf, len) != len)
101 avio_write(out, buf, len);
107 static int write_fragment(const char *filename, AVIOContext *in)
109 AVIOContext *out = NULL;
112 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
114 copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
115 copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
123 static int write_fragments(struct VideoFiles *files, int start_index,
126 char dirname[100], filename[500];
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);
144 static int read_tfra(struct VideoFiles *files, int start_index, AVIOContext *f)
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;
152 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
154 version = avio_r8(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];
161 /* Ok, continue parsing the next atom */
165 fieldlength = avio_rb32(f);
166 vf->chunks = avio_rb32(f);
167 vf->offsets = av_mallocz(sizeof(*vf->offsets) * vf->chunks);
169 ret = AVERROR(ENOMEM);
172 for (i = 0; i < vf->chunks; i++) {
174 vf->offsets[i].time = avio_rb64(f);
175 vf->offsets[i].offset = avio_rb64(f);
177 vf->offsets[i].time = avio_rb32(f);
178 vf->offsets[i].offset = avio_rb32(f);
180 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
182 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
184 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
187 vf->offsets[i - 1].duration = vf->offsets[i].time -
188 vf->offsets[i - 1].time;
191 vf->offsets[vf->chunks - 1].duration = vf->duration -
192 vf->offsets[vf->chunks - 1].time;
196 avio_seek(f, pos + size, SEEK_SET);
200 static int read_mfra(struct VideoFiles *files, int start_index,
201 const char *file, int split)
204 AVIOContext *f = NULL;
207 if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
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)
214 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a'))
216 while (!read_tfra(files, start_index, f)) {
221 write_fragments(files, start_index, f);
229 static int get_private_data(struct VideoFile *vf, AVCodecContext *codec)
231 vf->codec_private_size = codec->extradata_size;
232 vf->codec_private = av_mallocz(codec->extradata_size);
233 if (!vf->codec_private)
234 return AVERROR(ENOMEM);
235 memcpy(vf->codec_private, codec->extradata, codec->extradata_size);
239 static int get_video_private_data(struct VideoFile *vf, AVCodecContext *codec)
241 AVIOContext *io = NULL;
242 uint16_t sps_size, pps_size;
243 int err = AVERROR(EINVAL);
245 if (codec->codec_id == CODEC_ID_VC1)
246 return get_private_data(vf, codec);
248 avio_open_dyn_buf(&io);
249 if (codec->extradata_size < 11 || codec->extradata[0] != 1)
251 sps_size = AV_RB16(&codec->extradata[6]);
252 if (11 + sps_size > codec->extradata_size)
254 avio_wb32(io, 0x00000001);
255 avio_write(io, &codec->extradata[8], sps_size);
256 pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
257 if (11 + sps_size + pps_size > codec->extradata_size)
259 avio_wb32(io, 0x00000001);
260 avio_write(io, &codec->extradata[11 + sps_size], pps_size);
264 vf->codec_private_size = avio_close_dyn_buf(io, &vf->codec_private);
268 static int handle_file(struct VideoFiles *files, const char *file, int split)
270 AVFormatContext *ctx = NULL;
271 int err = 0, i, orig_files = files->nb_files;
272 char errbuf[50], *ptr;
273 struct VideoFile *vf;
275 err = avformat_open_input(&ctx, file, NULL, NULL);
277 av_strerror(err, errbuf, sizeof(errbuf));
278 fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
282 err = avformat_find_stream_info(ctx, NULL);
284 av_strerror(err, errbuf, sizeof(errbuf));
285 fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
289 if (ctx->nb_streams < 1) {
290 fprintf(stderr, "No streams found in %s\n", file);
293 if (!files->duration)
294 files->duration = ctx->duration;
296 for (i = 0; i < ctx->nb_streams; i++) {
297 AVStream *st = ctx->streams[i];
298 vf = av_mallocz(sizeof(*vf));
299 files->files = av_realloc(files->files,
300 sizeof(*files->files) * (files->nb_files + 1));
301 files->files[files->nb_files] = vf;
304 if ((ptr = strrchr(file, '/')) != NULL)
307 vf->bitrate = st->codec->bit_rate;
308 vf->track_id = st->id;
309 vf->timescale = st->time_base.den;
310 vf->duration = av_rescale_rnd(ctx->duration, vf->timescale,
311 AV_TIME_BASE, AV_ROUND_UP);
312 vf->is_audio = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
313 vf->is_video = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
315 if (!vf->is_audio && !vf->is_video) {
317 "Track %d in %s is neither video nor audio, skipping\n",
319 av_freep(&files->files[files->nb_files]);
324 if (files->audio_file < 0)
325 files->audio_file = files->nb_files;
326 files->nb_audio_files++;
327 vf->channels = st->codec->channels;
328 vf->sample_rate = st->codec->sample_rate;
329 if (st->codec->codec_id == CODEC_ID_AAC) {
333 } else if (st->codec->codec_id == CODEC_ID_WMAPRO) {
335 vf->tag = st->codec->codec_tag;
336 vf->blocksize = st->codec->block_align;
338 get_private_data(vf, st->codec);
341 if (files->video_file < 0)
342 files->video_file = files->nb_files;
343 files->nb_video_files++;
344 vf->width = st->codec->width;
345 vf->height = st->codec->height;
346 if (st->codec->codec_id == CODEC_ID_H264)
348 else if (st->codec->codec_id == CODEC_ID_VC1)
350 get_video_private_data(vf, st->codec);
356 avformat_close_input(&ctx);
358 read_mfra(files, orig_files, file, split);
362 avformat_close_input(&ctx);
366 static void output_server_manifest(struct VideoFiles *files,
367 const char *basename)
373 snprintf(filename, sizeof(filename), "%s.ism", basename);
374 out = fopen(filename, "w");
379 fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
380 fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
381 fprintf(out, "\t<head>\n");
382 fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
383 "content=\"%s.ismc\" />\n", basename);
384 fprintf(out, "\t</head>\n");
385 fprintf(out, "\t<body>\n");
386 fprintf(out, "\t\t<switch>\n");
387 for (i = 0; i < files->nb_files; i++) {
388 struct VideoFile *vf = files->files[i];
389 const char *type = vf->is_video ? "video" : "audio";
390 fprintf(out, "\t\t\t<%s src=\"%s\" systemBitrate=\"%d\">\n",
391 type, vf->name, vf->bitrate);
392 fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
393 "valueType=\"data\" />\n", vf->track_id);
394 fprintf(out, "\t\t\t</%s>\n", type);
396 fprintf(out, "\t\t</switch>\n");
397 fprintf(out, "\t</body>\n");
398 fprintf(out, "</smil>\n");
402 static void output_client_manifest(struct VideoFiles *files,
403 const char *basename, int split)
410 snprintf(filename, sizeof(filename), "Manifest");
412 snprintf(filename, sizeof(filename), "%s.ismc", basename);
413 out = fopen(filename, "w");
418 fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
419 fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
420 "Duration=\"%"PRId64 "\">\n", files->duration * 10);
421 if (files->video_file >= 0) {
422 struct VideoFile *vf = files->files[files->video_file];
425 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
427 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
428 files->nb_video_files, vf->chunks);
429 for (i = 0; i < files->nb_files; i++) {
430 vf = files->files[i];
434 "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
435 "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
436 "CodecPrivateData=\"",
437 index, vf->bitrate, vf->fourcc, vf->width, vf->height);
438 for (j = 0; j < vf->codec_private_size; j++)
439 fprintf(out, "%02X", vf->codec_private[j]);
440 fprintf(out, "\" />\n");
443 vf = files->files[files->video_file];
444 for (i = 0; i < vf->chunks; i++)
445 fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n", i,
446 vf->offsets[i].duration);
447 fprintf(out, "\t</StreamIndex>\n");
449 if (files->audio_file >= 0) {
450 struct VideoFile *vf = files->files[files->audio_file];
453 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
455 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
456 files->nb_audio_files, vf->chunks);
457 for (i = 0; i < files->nb_files; i++) {
458 vf = files->files[i];
462 "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
463 "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
464 "BitsPerSample=\"16\" PacketSize=\"%d\" "
465 "AudioTag=\"%d\" CodecPrivateData=\"",
466 index, vf->bitrate, vf->fourcc, vf->sample_rate,
467 vf->channels, vf->blocksize, vf->tag);
468 for (j = 0; j < vf->codec_private_size; j++)
469 fprintf(out, "%02X", vf->codec_private[j]);
470 fprintf(out, "\" />\n");
473 vf = files->files[files->audio_file];
474 for (i = 0; i < vf->chunks; i++)
475 fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",
476 i, vf->offsets[i].duration);
477 fprintf(out, "\t</StreamIndex>\n");
479 fprintf(out, "</SmoothStreamingMedia>\n");
483 static void clean_files(struct VideoFiles *files)
486 for (i = 0; i < files->nb_files; i++) {
487 av_freep(&files->files[i]->codec_private);
488 av_freep(&files->files[i]->offsets);
489 av_freep(&files->files[i]);
491 av_freep(&files->files);
495 int main(int argc, char **argv)
497 const char *basename = NULL;
499 struct VideoFiles vf = { 0, .video_file = -1, .audio_file = -1 };
503 for (i = 1; i < argc; i++) {
504 if (!strcmp(argv[i], "-n")) {
505 basename = argv[i + 1];
507 } else if (!strcmp(argv[i], "-split")) {
509 } else if (argv[i][0] == '-') {
510 return usage(argv[0], 1);
512 handle_file(&vf, argv[i], split);
515 if (!vf.nb_files || (!basename && !split))
516 return usage(argv[0], 1);
519 output_server_manifest(&vf, basename);
520 output_client_manifest(&vf, basename, split);