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