2 * Copyright (c) 2012 Martin Storsjo
4 * This file is part of FFmpeg.
6 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 * 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.
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.
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.)
49 #include "libavformat/avformat.h"
50 #include "libavformat/os_support.h"
51 #include "libavutil/intreadwrite.h"
52 #include "libavutil/mathematics.h"
54 static int usage(const char *argv0, int ret)
56 fprintf(stderr, "%s [-split] [-n basename] [-path-prefix prefix] "
57 "[-ismc-prefix prefix] [-output dir] file1 [file2] ...\n", argv0);
72 int is_audio, is_video;
75 int sample_rate, channels;
76 uint8_t *codec_private;
77 int codec_private_size;
78 struct MoofOffset *offsets;
88 struct Track **tracks;
89 int video_track, audio_track;
90 int nb_video_tracks, nb_audio_tracks;
93 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
106 int len = FFMIN(sizeof(buf), size);
107 if (avio_read(in, buf, len) != len)
109 avio_write(out, buf, len);
115 static int write_fragment(const char *filename, AVIOContext *in)
117 AVIOContext *out = NULL;
120 if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0)
122 copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
123 copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
131 static int write_fragments(struct Tracks *tracks, int start_index,
132 AVIOContext *in, const char *output_prefix)
134 char dirname[2048], filename[2048];
137 for (i = start_index; i < tracks->nb_tracks; i++) {
138 struct Track *track = tracks->tracks[i];
139 const char *type = track->is_video ? "video" : "audio";
140 snprintf(dirname, sizeof(dirname), "%sQualityLevels(%d)", output_prefix, track->bitrate);
141 if (mkdir(dirname, 0777) == -1)
142 return AVERROR(errno);
143 for (j = 0; j < track->chunks; j++) {
144 snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
145 dirname, type, track->offsets[j].time);
146 avio_seek(in, track->offsets[j].offset, SEEK_SET);
147 write_fragment(filename, in);
153 static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
155 int ret = AVERROR_EOF, track_id;
156 int version, fieldlength, i, j;
157 int64_t pos = avio_tell(f);
158 uint32_t size = avio_rb32(f);
159 struct Track *track = NULL;
161 if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
163 version = avio_r8(f);
165 track_id = avio_rb32(f); /* track id */
166 for (i = start_index; i < tracks->nb_tracks && !track; i++)
167 if (tracks->tracks[i]->track_id == track_id)
168 track = tracks->tracks[i];
170 /* Ok, continue parsing the next atom */
174 fieldlength = avio_rb32(f);
175 track->chunks = avio_rb32(f);
176 track->offsets = av_mallocz_array(track->chunks, sizeof(*track->offsets));
177 if (!track->offsets) {
178 ret = AVERROR(ENOMEM);
181 for (i = 0; i < track->chunks; i++) {
183 track->offsets[i].time = avio_rb64(f);
184 track->offsets[i].offset = avio_rb64(f);
186 track->offsets[i].time = avio_rb32(f);
187 track->offsets[i].offset = avio_rb32(f);
189 for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
191 for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
193 for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
196 track->offsets[i - 1].duration = track->offsets[i].time -
197 track->offsets[i - 1].time;
199 if (track->chunks > 0)
200 track->offsets[track->chunks - 1].duration = track->duration -
201 track->offsets[track->chunks - 1].time;
205 avio_seek(f, pos + size, SEEK_SET);
209 static int read_mfra(struct Tracks *tracks, int start_index,
210 const char *file, int split, const char *output_prefix)
213 AVIOContext *f = NULL;
216 if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
218 avio_seek(f, avio_size(f) - 4, SEEK_SET);
219 mfra_size = avio_rb32(f);
220 avio_seek(f, -mfra_size, SEEK_CUR);
221 if (avio_rb32(f) != mfra_size) {
222 err = AVERROR_INVALIDDATA;
225 if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
226 err = AVERROR_INVALIDDATA;
229 while (!read_tfra(tracks, start_index, f)) {
234 err = write_fragments(tracks, start_index, f, output_prefix);
240 fprintf(stderr, "Unable to read the MFRA atom in %s\n", file);
244 static int get_private_data(struct Track *track, AVCodecContext *codec)
246 track->codec_private_size = codec->extradata_size;
247 track->codec_private = av_mallocz(codec->extradata_size);
248 if (!track->codec_private)
249 return AVERROR(ENOMEM);
250 memcpy(track->codec_private, codec->extradata, codec->extradata_size);
254 static int get_video_private_data(struct Track *track, AVCodecContext *codec)
256 AVIOContext *io = NULL;
257 uint16_t sps_size, pps_size;
258 int err = AVERROR(EINVAL);
260 if (codec->codec_id == AV_CODEC_ID_VC1)
261 return get_private_data(track, codec);
263 if (avio_open_dyn_buf(&io) < 0) {
264 err = AVERROR(ENOMEM);
267 if (codec->extradata_size < 11 || codec->extradata[0] != 1)
269 sps_size = AV_RB16(&codec->extradata[6]);
270 if (11 + sps_size > codec->extradata_size)
272 avio_wb32(io, 0x00000001);
273 avio_write(io, &codec->extradata[8], sps_size);
274 pps_size = AV_RB16(&codec->extradata[9 + sps_size]);
275 if (11 + sps_size + pps_size > codec->extradata_size)
277 avio_wb32(io, 0x00000001);
278 avio_write(io, &codec->extradata[11 + sps_size], pps_size);
282 track->codec_private_size = avio_close_dyn_buf(io, &track->codec_private);
286 static int handle_file(struct Tracks *tracks, const char *file, int split,
287 const char *output_prefix)
289 AVFormatContext *ctx = NULL;
290 int err = 0, i, orig_tracks = tracks->nb_tracks;
291 char errbuf[50], *ptr;
294 err = avformat_open_input(&ctx, file, NULL, NULL);
296 av_strerror(err, errbuf, sizeof(errbuf));
297 fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
301 err = avformat_find_stream_info(ctx, NULL);
303 av_strerror(err, errbuf, sizeof(errbuf));
304 fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
308 if (ctx->nb_streams < 1) {
309 fprintf(stderr, "No streams found in %s\n", file);
313 for (i = 0; i < ctx->nb_streams; i++) {
315 AVStream *st = ctx->streams[i];
316 track = av_mallocz(sizeof(*track));
318 err = AVERROR(ENOMEM);
321 temp = av_realloc(tracks->tracks,
322 sizeof(*tracks->tracks) * (tracks->nb_tracks + 1));
325 err = AVERROR(ENOMEM);
328 tracks->tracks = temp;
329 tracks->tracks[tracks->nb_tracks] = track;
332 if ((ptr = strrchr(file, '/')) != NULL)
333 track->name = ptr + 1;
335 track->bitrate = st->codec->bit_rate;
336 track->track_id = st->id;
337 track->timescale = st->time_base.den;
338 track->duration = st->duration;
339 track->is_audio = st->codec->codec_type == AVMEDIA_TYPE_AUDIO;
340 track->is_video = st->codec->codec_type == AVMEDIA_TYPE_VIDEO;
342 if (!track->is_audio && !track->is_video) {
344 "Track %d in %s is neither video nor audio, skipping\n",
345 track->track_id, file);
346 av_freep(&tracks->tracks[tracks->nb_tracks]);
350 tracks->duration = FFMAX(tracks->duration,
351 av_rescale_rnd(track->duration, AV_TIME_BASE,
352 track->timescale, AV_ROUND_UP));
354 if (track->is_audio) {
355 if (tracks->audio_track < 0)
356 tracks->audio_track = tracks->nb_tracks;
357 tracks->nb_audio_tracks++;
358 track->channels = st->codec->channels;
359 track->sample_rate = st->codec->sample_rate;
360 if (st->codec->codec_id == AV_CODEC_ID_AAC) {
361 track->fourcc = "AACL";
363 track->blocksize = 4;
364 } else if (st->codec->codec_id == AV_CODEC_ID_WMAPRO) {
365 track->fourcc = "WMAP";
366 track->tag = st->codec->codec_tag;
367 track->blocksize = st->codec->block_align;
369 get_private_data(track, st->codec);
371 if (track->is_video) {
372 if (tracks->video_track < 0)
373 tracks->video_track = tracks->nb_tracks;
374 tracks->nb_video_tracks++;
375 track->width = st->codec->width;
376 track->height = st->codec->height;
377 if (st->codec->codec_id == AV_CODEC_ID_H264)
378 track->fourcc = "H264";
379 else if (st->codec->codec_id == AV_CODEC_ID_VC1)
380 track->fourcc = "WVC1";
381 get_video_private_data(track, st->codec);
387 avformat_close_input(&ctx);
389 err = read_mfra(tracks, orig_tracks, file, split, output_prefix);
393 avformat_close_input(&ctx);
397 static void output_server_manifest(struct Tracks *tracks, const char *basename,
398 const char *output_prefix,
399 const char *path_prefix,
400 const char *ismc_prefix)
406 snprintf(filename, sizeof(filename), "%s%s.ism", output_prefix, basename);
407 out = fopen(filename, "w");
412 fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
413 fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
414 fprintf(out, "\t<head>\n");
415 fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
416 "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
417 fprintf(out, "\t</head>\n");
418 fprintf(out, "\t<body>\n");
419 fprintf(out, "\t\t<switch>\n");
420 for (i = 0; i < tracks->nb_tracks; i++) {
421 struct Track *track = tracks->tracks[i];
422 const char *type = track->is_video ? "video" : "audio";
423 fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
424 type, path_prefix, track->name, track->bitrate);
425 fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
426 "valueType=\"data\" />\n", track->track_id);
427 fprintf(out, "\t\t\t</%s>\n", type);
429 fprintf(out, "\t\t</switch>\n");
430 fprintf(out, "\t</body>\n");
431 fprintf(out, "</smil>\n");
435 static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
439 struct Track *track = tracks->tracks[main];
440 for (i = 0; i < track->chunks; i++) {
441 for (j = main + 1; j < tracks->nb_tracks; j++) {
442 if (tracks->tracks[j]->is_audio == track->is_audio &&
443 track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration)
444 fprintf(stderr, "Mismatched duration of %s chunk %d in %s and %s\n",
445 type, i, track->name, tracks->tracks[j]->name);
447 fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" />\n",
448 i, track->offsets[i].duration);
452 static void output_client_manifest(struct Tracks *tracks, const char *basename,
453 const char *output_prefix, int split)
460 snprintf(filename, sizeof(filename), "%sManifest", output_prefix);
462 snprintf(filename, sizeof(filename), "%s%s.ismc", output_prefix, basename);
463 out = fopen(filename, "w");
468 fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
469 fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
470 "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
471 if (tracks->video_track >= 0) {
472 struct Track *track = tracks->tracks[tracks->video_track];
473 struct Track *first_track = track;
476 "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
478 "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
479 tracks->nb_video_tracks, track->chunks);
480 for (i = 0; i < tracks->nb_tracks; i++) {
481 track = tracks->tracks[i];
482 if (!track->is_video)
485 "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
486 "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
487 "CodecPrivateData=\"",
488 index, track->bitrate, track->fourcc, track->width, track->height);
489 for (j = 0; j < track->codec_private_size; j++)
490 fprintf(out, "%02X", track->codec_private[j]);
491 fprintf(out, "\" />\n");
493 if (track->chunks != first_track->chunks)
494 fprintf(stderr, "Mismatched number of video chunks in %s and %s\n",
495 track->name, first_track->name);
497 print_track_chunks(out, tracks, tracks->video_track, "video");
498 fprintf(out, "\t</StreamIndex>\n");
500 if (tracks->audio_track >= 0) {
501 struct Track *track = tracks->tracks[tracks->audio_track];
502 struct Track *first_track = track;
505 "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
507 "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
508 tracks->nb_audio_tracks, track->chunks);
509 for (i = 0; i < tracks->nb_tracks; i++) {
510 track = tracks->tracks[i];
511 if (!track->is_audio)
514 "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
515 "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
516 "BitsPerSample=\"16\" PacketSize=\"%d\" "
517 "AudioTag=\"%d\" CodecPrivateData=\"",
518 index, track->bitrate, track->fourcc, track->sample_rate,
519 track->channels, track->blocksize, track->tag);
520 for (j = 0; j < track->codec_private_size; j++)
521 fprintf(out, "%02X", track->codec_private[j]);
522 fprintf(out, "\" />\n");
524 if (track->chunks != first_track->chunks)
525 fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
526 track->name, first_track->name);
528 print_track_chunks(out, tracks, tracks->audio_track, "audio");
529 fprintf(out, "\t</StreamIndex>\n");
531 fprintf(out, "</SmoothStreamingMedia>\n");
535 static void clean_tracks(struct Tracks *tracks)
538 for (i = 0; i < tracks->nb_tracks; i++) {
539 av_freep(&tracks->tracks[i]->codec_private);
540 av_freep(&tracks->tracks[i]->offsets);
541 av_freep(&tracks->tracks[i]);
543 av_freep(&tracks->tracks);
544 tracks->nb_tracks = 0;
547 int main(int argc, char **argv)
549 const char *basename = NULL;
550 const char *path_prefix = "", *ismc_prefix = "";
551 const char *output_prefix = "";
552 char output_prefix_buf[2048];
554 struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
558 for (i = 1; i < argc; i++) {
559 if (!strcmp(argv[i], "-n")) {
560 basename = argv[i + 1];
562 } else if (!strcmp(argv[i], "-path-prefix")) {
563 path_prefix = argv[i + 1];
565 } else if (!strcmp(argv[i], "-ismc-prefix")) {
566 ismc_prefix = argv[i + 1];
568 } else if (!strcmp(argv[i], "-output")) {
569 output_prefix = argv[i + 1];
571 if (output_prefix[strlen(output_prefix) - 1] != '/') {
572 snprintf(output_prefix_buf, sizeof(output_prefix_buf),
573 "%s/", output_prefix);
574 output_prefix = output_prefix_buf;
576 } else if (!strcmp(argv[i], "-split")) {
578 } else if (argv[i][0] == '-') {
579 return usage(argv[0], 1);
581 if (handle_file(&tracks, argv[i], split, output_prefix))
585 if (!tracks.nb_tracks || (!basename && !split))
586 return usage(argv[0], 1);
589 output_server_manifest(&tracks, basename, output_prefix,
590 path_prefix, ismc_prefix);
591 output_client_manifest(&tracks, basename, output_prefix, split);
593 clean_tracks(&tracks);