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 FFmpeg.
5  *
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.
10  *
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.
15  *
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
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  * With -ismf, it also creates foo.ismf, which maps fragment names to
29  * start-end offsets in the ismv, for use in your own streaming server.
30  *
31  * By adding -path-prefix path/, the produced foo.ism will refer to the
32  * files foo.ismv as "path/foo.ismv" - the prefix for the generated ismc
33  * file can be set with the -ismc-prefix option similarly.
34  *
35  * To pre-split files for serving as static files by a web server without
36  * any extra server support, create the ismv file as above, and split it:
37  * ismindex -split foo.ismv
38  * This step creates a file Manifest and directories QualityLevel(...),
39  * that can be read directly by a smooth streaming player.
40  *
41  * The -output dir option can be used to request that output files
42  * (both .ism/.ismc, or Manifest/QualityLevels* when splitting)
43  * should be written to this directory instead of in the current directory.
44  * (The directory itself isn't created if it doesn't already exist.)
45  */
46 
47 #include <stdio.h>
48 #include <string.h>
49 
50 #include "cmdutils.h"
51 
52 #include "libavformat/avformat.h"
53 #include "libavformat/isom.h"
54 #include "libavformat/os_support.h"
55 #include "libavutil/intreadwrite.h"
56 #include "libavutil/mathematics.h"
57 
58 static int usage(const char *argv0, int ret)
59 {
60  fprintf(stderr, "%s [-split] [-ismf] [-n basename] [-path-prefix prefix] "
61  "[-ismc-prefix prefix] [-output dir] file1 [file2] ...\n", argv0);
62  return ret;
63 }
64 
65 struct MoofOffset {
66  int64_t time;
67  int64_t offset;
68  int64_t duration;
69 };
70 
71 struct Track {
72  const char *name;
73  int64_t duration;
74  int bitrate;
75  int track_id;
77  int width, height;
78  int chunks;
83  int timescale;
84  const char *fourcc;
85  int blocksize;
86  int tag;
87 };
88 
89 struct Tracks {
90  int nb_tracks;
91  int64_t duration;
92  struct Track **tracks;
95 };
96 
97 static int expect_tag(int32_t got_tag, int32_t expected_tag) {
98  if (got_tag != expected_tag) {
99  char got_tag_str[4], expected_tag_str[4];
100  AV_WB32(got_tag_str, got_tag);
101  AV_WB32(expected_tag_str, expected_tag);
102  fprintf(stderr, "wanted tag %.4s, got %.4s\n", expected_tag_str,
103  got_tag_str);
104  return -1;
105  }
106  return 0;
107 }
108 
109 static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
110 {
111  int32_t size, tag;
112 
113  size = avio_rb32(in);
114  tag = avio_rb32(in);
115  avio_wb32(out, size);
116  avio_wb32(out, tag);
117  if (expect_tag(tag, tag_name) != 0)
118  return -1;
119  size -= 8;
120  while (size > 0) {
121  char buf[1024];
122  int len = FFMIN(sizeof(buf), size);
123  int got;
124  if ((got = avio_read(in, buf, len)) != len) {
125  fprintf(stderr, "short read, wanted %d, got %d\n", len, got);
126  break;
127  }
128  avio_write(out, buf, len);
129  size -= len;
130  }
131  return 0;
132 }
133 
134 static int skip_tag(AVIOContext *in, int32_t tag_name)
135 {
136  int64_t pos = avio_tell(in);
137  int32_t size, tag;
138 
139  size = avio_rb32(in);
140  tag = avio_rb32(in);
141  if (expect_tag(tag, tag_name) != 0)
142  return -1;
143  avio_seek(in, pos + size, SEEK_SET);
144  return 0;
145 }
146 
147 static int write_fragment(const char *filename, AVIOContext *in)
148 {
149  AVIOContext *out = NULL;
150  int ret;
151 
152  if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, NULL, NULL)) < 0) {
153  char errbuf[100];
154  av_strerror(ret, errbuf, sizeof(errbuf));
155  fprintf(stderr, "Unable to open %s: %s\n", filename, errbuf);
156  return ret;
157  }
158  ret = copy_tag(in, out, MKBETAG('m', 'o', 'o', 'f'));
159  if (!ret)
160  ret = copy_tag(in, out, MKBETAG('m', 'd', 'a', 't'));
161 
162  avio_flush(out);
163  avio_close(out);
164 
165  return ret;
166 }
167 
169 {
170  int ret;
171  ret = skip_tag(in, MKBETAG('m', 'o', 'o', 'f'));
172  if (!ret)
173  ret = skip_tag(in, MKBETAG('m', 'd', 'a', 't'));
174  return ret;
175 }
176 
177 static int write_fragments(struct Tracks *tracks, int start_index,
178  AVIOContext *in, const char *basename,
179  int split, int ismf, const char* output_prefix)
180 {
181  char dirname[2048], filename[2048], idxname[2048];
182  int i, j, ret = 0, fragment_ret;
183  FILE* out = NULL;
184 
185  if (ismf) {
186  snprintf(idxname, sizeof(idxname), "%s%s.ismf", output_prefix, basename);
187  out = fopen(idxname, "w");
188  if (!out) {
189  ret = AVERROR(errno);
190  perror(idxname);
191  goto fail;
192  }
193  }
194  for (i = start_index; i < tracks->nb_tracks; i++) {
195  struct Track *track = tracks->tracks[i];
196  const char *type = track->is_video ? "video" : "audio";
197  snprintf(dirname, sizeof(dirname), "%sQualityLevels(%d)", output_prefix, track->bitrate);
198  if (split) {
199  if (mkdir(dirname, 0777) == -1 && errno != EEXIST) {
200  ret = AVERROR(errno);
201  perror(dirname);
202  goto fail;
203  }
204  }
205  for (j = 0; j < track->chunks; j++) {
206  snprintf(filename, sizeof(filename), "%s/Fragments(%s=%"PRId64")",
207  dirname, type, track->offsets[j].time);
208  avio_seek(in, track->offsets[j].offset, SEEK_SET);
209  if (ismf)
210  fprintf(out, "%s %"PRId64, filename, avio_tell(in));
211  if (split)
212  fragment_ret = write_fragment(filename, in);
213  else
214  fragment_ret = skip_fragment(in);
215  if (ismf)
216  fprintf(out, " %"PRId64"\n", avio_tell(in));
217  if (fragment_ret != 0) {
218  fprintf(stderr, "failed fragment %d in track %d (%s)\n", j,
219  track->track_id, track->name);
220  ret = fragment_ret;
221  }
222  }
223  }
224 fail:
225  if (out)
226  fclose(out);
227  return ret;
228 }
229 
230 static int64_t read_trun_duration(AVIOContext *in, int default_duration,
231  int64_t end)
232 {
233  int64_t dts = 0;
234  int64_t pos;
235  int flags, i;
236  int entries;
237  int64_t first_pts = 0;
238  int64_t max_pts = 0;
239  avio_r8(in); /* version */
240  flags = avio_rb24(in);
241  if (default_duration <= 0 && !(flags & MOV_TRUN_SAMPLE_DURATION)) {
242  fprintf(stderr, "No sample duration in trun flags\n");
243  return -1;
244  }
245  entries = avio_rb32(in);
246 
247  if (flags & MOV_TRUN_DATA_OFFSET) avio_rb32(in);
248  if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_rb32(in);
249 
250  pos = avio_tell(in);
251  for (i = 0; i < entries && pos < end; i++) {
252  int sample_duration = default_duration;
253  int64_t pts = dts;
254  if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(in);
255  if (flags & MOV_TRUN_SAMPLE_SIZE) avio_rb32(in);
256  if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_rb32(in);
257  if (flags & MOV_TRUN_SAMPLE_CTS) pts += avio_rb32(in);
258  if (sample_duration < 0) {
259  fprintf(stderr, "Negative sample duration %d\n", sample_duration);
260  return -1;
261  }
262  if (i == 0)
263  first_pts = pts;
264  max_pts = FFMAX(max_pts, pts + sample_duration);
265  dts += sample_duration;
266  pos = avio_tell(in);
267  }
268 
269  return max_pts - first_pts;
270 }
271 
272 static int64_t read_moof_duration(AVIOContext *in, int64_t offset)
273 {
274  int64_t ret = -1;
275  int32_t moof_size, size, tag;
276  int64_t pos = 0;
277  int default_duration = 0;
278 
279  avio_seek(in, offset, SEEK_SET);
280  moof_size = avio_rb32(in);
281  tag = avio_rb32(in);
282  if (expect_tag(tag, MKBETAG('m', 'o', 'o', 'f')) != 0)
283  goto fail;
284  while (pos < offset + moof_size) {
285  pos = avio_tell(in);
286  size = avio_rb32(in);
287  tag = avio_rb32(in);
288  if (tag == MKBETAG('t', 'r', 'a', 'f')) {
289  int64_t traf_pos = pos;
290  int64_t traf_size = size;
291  while (pos < traf_pos + traf_size) {
292  pos = avio_tell(in);
293  size = avio_rb32(in);
294  tag = avio_rb32(in);
295  if (tag == MKBETAG('t', 'f', 'h', 'd')) {
296  int flags = 0;
297  avio_r8(in); /* version */
298  flags = avio_rb24(in);
299  avio_rb32(in); /* track_id */
300  if (flags & MOV_TFHD_BASE_DATA_OFFSET)
301  avio_rb64(in);
302  if (flags & MOV_TFHD_STSD_ID)
303  avio_rb32(in);
304  if (flags & MOV_TFHD_DEFAULT_DURATION)
305  default_duration = avio_rb32(in);
306  }
307  if (tag == MKBETAG('t', 'r', 'u', 'n')) {
308  return read_trun_duration(in, default_duration,
309  pos + size);
310  }
311  avio_seek(in, pos + size, SEEK_SET);
312  }
313  fprintf(stderr, "Couldn't find trun\n");
314  goto fail;
315  }
316  avio_seek(in, pos + size, SEEK_SET);
317  }
318  fprintf(stderr, "Couldn't find traf\n");
319 
320 fail:
321  return ret;
322 }
323 
324 static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
325 {
326  int ret = AVERROR_EOF, track_id;
327  int version, fieldlength, i, j;
328  int64_t pos = avio_tell(f);
329  uint32_t size = avio_rb32(f);
330  struct Track *track = NULL;
331 
332  if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a'))
333  goto fail;
334  version = avio_r8(f);
335  avio_rb24(f);
336  track_id = avio_rb32(f); /* track id */
337  for (i = start_index; i < tracks->nb_tracks && !track; i++)
338  if (tracks->tracks[i]->track_id == track_id)
339  track = tracks->tracks[i];
340  if (!track) {
341  /* Ok, continue parsing the next atom */
342  ret = 0;
343  goto fail;
344  }
345  fieldlength = avio_rb32(f);
346  track->chunks = avio_rb32(f);
347  track->offsets = av_mallocz_array(track->chunks, sizeof(*track->offsets));
348  if (!track->offsets) {
349  track->chunks = 0;
350  ret = AVERROR(ENOMEM);
351  goto fail;
352  }
353  // The duration here is always the difference between consecutive
354  // start times.
355  for (i = 0; i < track->chunks; i++) {
356  if (version == 1) {
357  track->offsets[i].time = avio_rb64(f);
358  track->offsets[i].offset = avio_rb64(f);
359  } else {
360  track->offsets[i].time = avio_rb32(f);
361  track->offsets[i].offset = avio_rb32(f);
362  }
363  for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
364  avio_r8(f);
365  for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
366  avio_r8(f);
367  for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
368  avio_r8(f);
369  if (i > 0)
370  track->offsets[i - 1].duration = track->offsets[i].time -
371  track->offsets[i - 1].time;
372  }
373  if (track->chunks > 0) {
374  track->offsets[track->chunks - 1].duration = track->offsets[0].time +
375  track->duration -
376  track->offsets[track->chunks - 1].time;
377  }
378  // Now try and read the actual durations from the trun sample data.
379  for (i = 0; i < track->chunks; i++) {
380  int64_t duration = read_moof_duration(f, track->offsets[i].offset);
381  if (duration > 0 && llabs(duration - track->offsets[i].duration) > 3) {
382  // 3 allows for integer duration to drift a few units,
383  // e.g., for 1/3 durations
384  track->offsets[i].duration = duration;
385  }
386  }
387  if (track->chunks > 0) {
388  if (track->offsets[track->chunks - 1].duration <= 0) {
389  fprintf(stderr, "Calculated last chunk duration for track %d "
390  "was non-positive (%"PRId64"), probably due to missing "
391  "fragments ", track->track_id,
392  track->offsets[track->chunks - 1].duration);
393  if (track->chunks > 1) {
394  track->offsets[track->chunks - 1].duration =
395  track->offsets[track->chunks - 2].duration;
396  } else {
397  track->offsets[track->chunks - 1].duration = 1;
398  }
399  fprintf(stderr, "corrected to %"PRId64"\n",
400  track->offsets[track->chunks - 1].duration);
401  track->duration = track->offsets[track->chunks - 1].time +
402  track->offsets[track->chunks - 1].duration -
403  track->offsets[0].time;
404  fprintf(stderr, "Track duration corrected to %"PRId64"\n",
405  track->duration);
406  }
407  }
408  ret = 0;
409 
410 fail:
411  avio_seek(f, pos + size, SEEK_SET);
412  return ret;
413 }
414 
415 static int read_mfra(struct Tracks *tracks, int start_index,
416  const char *file, int split, int ismf,
417  const char *basename, const char* output_prefix)
418 {
419  int err = 0;
420  const char* err_str = "";
421  AVIOContext *f = NULL;
422  int32_t mfra_size;
423 
424  if ((err = avio_open2(&f, file, AVIO_FLAG_READ, NULL, NULL)) < 0)
425  goto fail;
426  avio_seek(f, avio_size(f) - 4, SEEK_SET);
427  mfra_size = avio_rb32(f);
428  avio_seek(f, -mfra_size, SEEK_CUR);
429  if (avio_rb32(f) != mfra_size) {
430  err = AVERROR_INVALIDDATA;
431  err_str = "mfra size mismatch";
432  goto fail;
433  }
434  if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
435  err = AVERROR_INVALIDDATA;
436  err_str = "mfra tag mismatch";
437  goto fail;
438  }
439  while (!read_tfra(tracks, start_index, f)) {
440  /* Empty */
441  }
442 
443  if (split || ismf)
444  err = write_fragments(tracks, start_index, f, basename, split, ismf,
445  output_prefix);
446  err_str = "error in write_fragments";
447 
448 fail:
449  if (f)
450  avio_close(f);
451  if (err)
452  fprintf(stderr, "Unable to read the MFRA atom in %s (%s)\n", file, err_str);
453  return err;
454 }
455 
456 static int get_private_data(struct Track *track, AVCodecParameters *codecpar)
457 {
458  track->codec_private_size = 0;
459  track->codec_private = av_mallocz(codecpar->extradata_size);
460  if (!track->codec_private)
461  return AVERROR(ENOMEM);
462  track->codec_private_size = codecpar->extradata_size;
463  memcpy(track->codec_private, codecpar->extradata, codecpar->extradata_size);
464  return 0;
465 }
466 
467 static int get_video_private_data(struct Track *track, AVCodecParameters *codecpar)
468 {
469  AVIOContext *io = NULL;
470  uint16_t sps_size, pps_size;
471  int err;
472 
473  if (codecpar->codec_id == AV_CODEC_ID_VC1)
474  return get_private_data(track, codecpar);
475 
476  if ((err = avio_open_dyn_buf(&io)) < 0)
477  goto fail;
478  err = AVERROR(EINVAL);
479  if (codecpar->extradata_size < 11 || codecpar->extradata[0] != 1)
480  goto fail;
481  sps_size = AV_RB16(&codecpar->extradata[6]);
482  if (11 + sps_size > codecpar->extradata_size)
483  goto fail;
484  avio_wb32(io, 0x00000001);
485  avio_write(io, &codecpar->extradata[8], sps_size);
486  pps_size = AV_RB16(&codecpar->extradata[9 + sps_size]);
487  if (11 + sps_size + pps_size > codecpar->extradata_size)
488  goto fail;
489  avio_wb32(io, 0x00000001);
490  avio_write(io, &codecpar->extradata[11 + sps_size], pps_size);
491  err = 0;
492 
493 fail:
495  return err;
496 }
497 
498 static int handle_file(struct Tracks *tracks, const char *file, int split,
499  int ismf, const char *basename,
500  const char* output_prefix)
501 {
503  int err = 0, i, orig_tracks = tracks->nb_tracks;
504  char errbuf[50], *ptr;
505  struct Track *track;
506 
507  err = avformat_open_input(&ctx, file, NULL, NULL);
508  if (err < 0) {
509  av_strerror(err, errbuf, sizeof(errbuf));
510  fprintf(stderr, "Unable to open %s: %s\n", file, errbuf);
511  return 1;
512  }
513 
514  err = avformat_find_stream_info(ctx, NULL);
515  if (err < 0) {
516  av_strerror(err, errbuf, sizeof(errbuf));
517  fprintf(stderr, "Unable to identify %s: %s\n", file, errbuf);
518  goto fail;
519  }
520 
521  if (ctx->nb_streams < 1) {
522  fprintf(stderr, "No streams found in %s\n", file);
523  goto fail;
524  }
525 
526  for (i = 0; i < ctx->nb_streams; i++) {
527  struct Track **temp;
528  AVStream *st = ctx->streams[i];
529 
530  if (st->codecpar->bit_rate == 0) {
531  fprintf(stderr, "Skipping track %d in %s as it has zero bitrate\n",
532  st->id, file);
533  continue;
534  }
535 
536  track = av_mallocz(sizeof(*track));
537  if (!track) {
538  err = AVERROR(ENOMEM);
539  goto fail;
540  }
541  temp = av_realloc_array(tracks->tracks,
542  tracks->nb_tracks + 1,
543  sizeof(*tracks->tracks));
544  if (!temp) {
545  av_free(track);
546  err = AVERROR(ENOMEM);
547  goto fail;
548  }
549  tracks->tracks = temp;
550  tracks->tracks[tracks->nb_tracks] = track;
551 
552  track->name = file;
553  if ((ptr = strrchr(file, '/')))
554  track->name = ptr + 1;
555 
556  track->bitrate = st->codecpar->bit_rate;
557  track->track_id = st->id;
558  track->timescale = st->time_base.den;
559  track->duration = st->duration;
562 
563  if (!track->is_audio && !track->is_video) {
564  fprintf(stderr,
565  "Track %d in %s is neither video nor audio, skipping\n",
566  track->track_id, file);
567  av_freep(&tracks->tracks[tracks->nb_tracks]);
568  continue;
569  }
570 
571  tracks->duration = FFMAX(tracks->duration,
573  track->timescale, AV_ROUND_UP));
574 
575  if (track->is_audio) {
576  if (tracks->audio_track < 0)
577  tracks->audio_track = tracks->nb_tracks;
578  tracks->nb_audio_tracks++;
579  track->channels = st->codecpar->channels;
580  track->sample_rate = st->codecpar->sample_rate;
581  if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
582  track->fourcc = "AACL";
583  track->tag = 255;
584  track->blocksize = 4;
585  } else if (st->codecpar->codec_id == AV_CODEC_ID_WMAPRO) {
586  track->fourcc = "WMAP";
587  track->tag = st->codecpar->codec_tag;
588  track->blocksize = st->codecpar->block_align;
589  }
590  get_private_data(track, st->codecpar);
591  }
592  if (track->is_video) {
593  if (tracks->video_track < 0)
594  tracks->video_track = tracks->nb_tracks;
595  tracks->nb_video_tracks++;
596  track->width = st->codecpar->width;
597  track->height = st->codecpar->height;
598  if (st->codecpar->codec_id == AV_CODEC_ID_H264)
599  track->fourcc = "H264";
600  else if (st->codecpar->codec_id == AV_CODEC_ID_VC1)
601  track->fourcc = "WVC1";
602  get_video_private_data(track, st->codecpar);
603  }
604 
605  tracks->nb_tracks++;
606  }
607 
608  avformat_close_input(&ctx);
609 
610  err = read_mfra(tracks, orig_tracks, file, split, ismf, basename,
611  output_prefix);
612 
613 fail:
614  if (ctx)
615  avformat_close_input(&ctx);
616  return err;
617 }
618 
619 static void output_server_manifest(struct Tracks *tracks, const char *basename,
620  const char *output_prefix,
621  const char *path_prefix,
622  const char *ismc_prefix)
623 {
624  char filename[1000];
625  FILE *out;
626  int i;
627 
628  snprintf(filename, sizeof(filename), "%s%s.ism", output_prefix, basename);
629  out = fopen(filename, "w");
630  if (!out) {
631  perror(filename);
632  return;
633  }
634  fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
635  fprintf(out, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
636  fprintf(out, "\t<head>\n");
637  fprintf(out, "\t\t<meta name=\"clientManifestRelativePath\" "
638  "content=\"%s%s.ismc\" />\n", ismc_prefix, basename);
639  fprintf(out, "\t</head>\n");
640  fprintf(out, "\t<body>\n");
641  fprintf(out, "\t\t<switch>\n");
642  for (i = 0; i < tracks->nb_tracks; i++) {
643  struct Track *track = tracks->tracks[i];
644  const char *type = track->is_video ? "video" : "audio";
645  fprintf(out, "\t\t\t<%s src=\"%s%s\" systemBitrate=\"%d\">\n",
646  type, path_prefix, track->name, track->bitrate);
647  fprintf(out, "\t\t\t\t<param name=\"trackID\" value=\"%d\" "
648  "valueType=\"data\" />\n", track->track_id);
649  fprintf(out, "\t\t\t</%s>\n", type);
650  }
651  fprintf(out, "\t\t</switch>\n");
652  fprintf(out, "\t</body>\n");
653  fprintf(out, "</smil>\n");
654  fclose(out);
655 }
656 
657 static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,
658  const char *type)
659 {
660  int i, j;
661  int64_t pos = 0;
662  struct Track *track = tracks->tracks[main];
663  int should_print_time_mismatch = 1;
664 
665  for (i = 0; i < track->chunks; i++) {
666  for (j = main + 1; j < tracks->nb_tracks; j++) {
667  if (tracks->tracks[j]->is_audio == track->is_audio) {
668  if (track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration) {
669  fprintf(stderr, "Mismatched duration of %s chunk %d in %s (%d) and %s (%d)\n",
670  type, i, track->name, main, tracks->tracks[j]->name, j);
671  should_print_time_mismatch = 1;
672  }
673  if (track->offsets[i].time != tracks->tracks[j]->offsets[i].time) {
674  if (should_print_time_mismatch)
675  fprintf(stderr, "Mismatched (start) time of %s chunk %d in %s (%d) and %s (%d)\n",
676  type, i, track->name, main, tracks->tracks[j]->name, j);
677  should_print_time_mismatch = 0;
678  }
679  }
680  }
681  fprintf(out, "\t\t<c n=\"%d\" d=\"%"PRId64"\" ",
682  i, track->offsets[i].duration);
683  if (pos != track->offsets[i].time) {
684  fprintf(out, "t=\"%"PRId64"\" ", track->offsets[i].time);
685  pos = track->offsets[i].time;
686  }
687  pos += track->offsets[i].duration;
688  fprintf(out, "/>\n");
689  }
690 }
691 
692 static void output_client_manifest(struct Tracks *tracks, const char *basename,
693  const char *output_prefix, int split)
694 {
695  char filename[1000];
696  FILE *out;
697  int i, j;
698 
699  if (split)
700  snprintf(filename, sizeof(filename), "%sManifest", output_prefix);
701  else
702  snprintf(filename, sizeof(filename), "%s%s.ismc", output_prefix, basename);
703  out = fopen(filename, "w");
704  if (!out) {
705  perror(filename);
706  return;
707  }
708  fprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
709  fprintf(out, "<SmoothStreamingMedia MajorVersion=\"2\" MinorVersion=\"0\" "
710  "Duration=\"%"PRId64 "\">\n", tracks->duration * 10);
711  if (tracks->video_track >= 0) {
712  struct Track *track = tracks->tracks[tracks->video_track];
713  struct Track *first_track = track;
714  int index = 0;
715  fprintf(out,
716  "\t<StreamIndex Type=\"video\" QualityLevels=\"%d\" "
717  "Chunks=\"%d\" "
718  "Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n",
719  tracks->nb_video_tracks, track->chunks);
720  for (i = 0; i < tracks->nb_tracks; i++) {
721  track = tracks->tracks[i];
722  if (!track->is_video)
723  continue;
724  fprintf(out,
725  "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
726  "FourCC=\"%s\" MaxWidth=\"%d\" MaxHeight=\"%d\" "
727  "CodecPrivateData=\"",
728  index, track->bitrate, track->fourcc, track->width, track->height);
729  for (j = 0; j < track->codec_private_size; j++)
730  fprintf(out, "%02X", track->codec_private[j]);
731  fprintf(out, "\" />\n");
732  index++;
733  if (track->chunks != first_track->chunks)
734  fprintf(stderr, "Mismatched number of video chunks in %s (id: %d, chunks %d) and %s (id: %d, chunks %d)\n",
735  track->name, track->track_id, track->chunks, first_track->name, first_track->track_id, first_track->chunks);
736  }
737  print_track_chunks(out, tracks, tracks->video_track, "video");
738  fprintf(out, "\t</StreamIndex>\n");
739  }
740  if (tracks->audio_track >= 0) {
741  struct Track *track = tracks->tracks[tracks->audio_track];
742  struct Track *first_track = track;
743  int index = 0;
744  fprintf(out,
745  "\t<StreamIndex Type=\"audio\" QualityLevels=\"%d\" "
746  "Chunks=\"%d\" "
747  "Url=\"QualityLevels({bitrate})/Fragments(audio={start time})\">\n",
748  tracks->nb_audio_tracks, track->chunks);
749  for (i = 0; i < tracks->nb_tracks; i++) {
750  track = tracks->tracks[i];
751  if (!track->is_audio)
752  continue;
753  fprintf(out,
754  "\t\t<QualityLevel Index=\"%d\" Bitrate=\"%d\" "
755  "FourCC=\"%s\" SamplingRate=\"%d\" Channels=\"%d\" "
756  "BitsPerSample=\"16\" PacketSize=\"%d\" "
757  "AudioTag=\"%d\" CodecPrivateData=\"",
758  index, track->bitrate, track->fourcc, track->sample_rate,
759  track->channels, track->blocksize, track->tag);
760  for (j = 0; j < track->codec_private_size; j++)
761  fprintf(out, "%02X", track->codec_private[j]);
762  fprintf(out, "\" />\n");
763  index++;
764  if (track->chunks != first_track->chunks)
765  fprintf(stderr, "Mismatched number of audio chunks in %s and %s\n",
766  track->name, first_track->name);
767  }
768  print_track_chunks(out, tracks, tracks->audio_track, "audio");
769  fprintf(out, "\t</StreamIndex>\n");
770  }
771  fprintf(out, "</SmoothStreamingMedia>\n");
772  fclose(out);
773 }
774 
775 static void clean_tracks(struct Tracks *tracks)
776 {
777  int i;
778  for (i = 0; i < tracks->nb_tracks; i++) {
779  av_freep(&tracks->tracks[i]->codec_private);
780  av_freep(&tracks->tracks[i]->offsets);
781  av_freep(&tracks->tracks[i]);
782  }
783  av_freep(&tracks->tracks);
784  tracks->nb_tracks = 0;
785 }
786 
787 int main(int argc, char **argv)
788 {
789  const char *basename = NULL;
790  const char *path_prefix = "", *ismc_prefix = "";
791  const char *output_prefix = "";
792  char output_prefix_buf[2048];
793  int split = 0, ismf = 0, i;
794  struct Tracks tracks = { 0, .video_track = -1, .audio_track = -1 };
795 
796  av_register_all();
797 
798  for (i = 1; i < argc; i++) {
799  if (!strcmp(argv[i], "-n")) {
800  basename = argv[i + 1];
801  i++;
802  } else if (!strcmp(argv[i], "-path-prefix")) {
803  path_prefix = argv[i + 1];
804  i++;
805  } else if (!strcmp(argv[i], "-ismc-prefix")) {
806  ismc_prefix = argv[i + 1];
807  i++;
808  } else if (!strcmp(argv[i], "-output")) {
809  output_prefix = argv[i + 1];
810  i++;
811  if (output_prefix[strlen(output_prefix) - 1] != '/') {
812  snprintf(output_prefix_buf, sizeof(output_prefix_buf),
813  "%s/", output_prefix);
814  output_prefix = output_prefix_buf;
815  }
816  } else if (!strcmp(argv[i], "-split")) {
817  split = 1;
818  } else if (!strcmp(argv[i], "-ismf")) {
819  ismf = 1;
820  } else if (argv[i][0] == '-') {
821  return usage(argv[0], 1);
822  } else {
823  if (!basename)
824  ismf = 0;
825  if (handle_file(&tracks, argv[i], split, ismf,
826  basename, output_prefix))
827  return 1;
828  }
829  }
830  if (!tracks.nb_tracks || (!basename && !split))
831  return usage(argv[0], 1);
832 
833  if (!split)
834  output_server_manifest(&tracks, basename, output_prefix,
835  path_prefix, ismc_prefix);
836  output_client_manifest(&tracks, basename, output_prefix, split);
837 
838  clean_tracks(&tracks);
839 
840  return 0;
841 }
static int copy_tag(AVIOContext *in, AVIOContext *out, int32_t tag_name)
Definition: ismindex.c:109
#define NULL
Definition: coverity.c:32
Bytestream IO Context.
Definition: avio.h:147
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:309
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition: aviobuf.c:1278
static int usage(const char *argv0, int ret)
Definition: ismindex.c:58
#define MOV_TFHD_DEFAULT_DURATION
Definition: isom.h:257
else temp
Definition: vf_mcdeint.c:259
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3969
#define MOV_TRUN_SAMPLE_CTS
Definition: isom.h:268
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:230
#define AVIO_FLAG_READ
read-only
Definition: avio.h:606
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:607
static int expect_tag(int32_t got_tag, int32_t expected_tag)
Definition: ismindex.c:97
int version
Definition: avisynth_c.h:766
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:252
int is_audio
Definition: ismindex.c:76
static void print_track_chunks(FILE *out, struct Tracks *tracks, int main, const char *type)
Definition: ismindex.c:657
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:87
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition: aviobuf.c:1266
int tag
Definition: ismindex.c:86
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3961
int height
Definition: ismindex.c:77
Format I/O context.
Definition: avformat.h:1330
uint8_t
Round toward +infinity.
Definition: mathematics.h:83
struct MoofOffset * offsets
Definition: ismindex.c:82
int width
Video only.
Definition: avcodec.h:4035
miscellaneous OS support macros and functions.
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:757
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int id
Format-specific stream ID.
Definition: avformat.h:888
int bitrate
Definition: ismindex.c:74
int nb_tracks
Definition: ismindex.c:90
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1398
int64_t duration
Definition: movenc.c:63
static int skip_fragment(AVIOContext *in)
Definition: ismindex.c:168
#define MOV_TRUN_SAMPLE_SIZE
Definition: isom.h:266
uint32_t tag
Definition: movenc.c:1378
#define AVERROR_EOF
End of file.
Definition: error.h:55
Definition: ismindex.c:71
int64_t time
Definition: ismindex.c:66
ptrdiff_t size
Definition: opengl_enc.c:101
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:824
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:511
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:204
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:208
static int write_fragment(const char *filename, AVIOContext *in)
Definition: ismindex.c:147
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:604
int width
Definition: ismindex.c:77
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: avcodec.h:3998
int is_video
Definition: ismindex.c:76
int channels
Definition: ismindex.c:79
#define AVERROR(e)
Definition: error.h:43
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:1069
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3965
int sample_rate
Definition: ismindex.c:79
static void output_client_manifest(struct Tracks *tracks, const char *basename, const char *output_prefix, int split)
Definition: ismindex.c:692
static int read_mfra(struct Tracks *tracks, int start_index, const char *file, int split, int ismf, const char *basename, const char *output_prefix)
Definition: ismindex.c:415
int64_t duration
Definition: ismindex.c:91
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
#define FFMAX(a, b)
Definition: common.h:94
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:226
#define fail()
Definition: checkasm.h:82
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3987
static char * split(char *message, char delim)
Definition: af_channelmap.c:81
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:595
const char * fourcc
Definition: ismindex.c:84
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1386
int block_align
Audio only.
Definition: avcodec.h:4086
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:224
unsigned int avio_rb24(AVIOContext *s)
Definition: aviobuf.c:750
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:248
#define FFMIN(a, b)
Definition: common.h:96
static int handle_file(struct Tracks *tracks, const char *file, int split, int ismf, const char *basename, const char *output_prefix)
Definition: ismindex.c:498
int chunks
Definition: ismindex.c:78
int32_t
AVFormatContext * ctx
Definition: movenc.c:48
int audio_track
Definition: ismindex.c:93
#define MOV_TRUN_SAMPLE_DURATION
Definition: isom.h:265
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
Rescale a 64-bit integer with specified rounding.
Definition: mathematics.c:58
Stream structure.
Definition: avformat.h:881
static int64_t read_moof_duration(AVIOContext *in, int64_t offset)
Definition: ismindex.c:272
const char * name
Definition: ismindex.c:72
static int skip_tag(AVIOContext *in, int32_t tag_name)
Definition: ismindex.c:134
int64_t duration
Definition: ismindex.c:73
uint8_t * codec_private
Definition: ismindex.c:80
#define MOV_TRUN_FIRST_SAMPLE_FLAGS
Definition: isom.h:264
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31))))#defineSET_CONV_FUNC_GROUP(ofmt, ifmt) staticvoidset_generic_function(AudioConvert *ac){}voidff_audio_convert_free(AudioConvert **ac){if(!*ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);}AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, intsample_rate, intapply_map){AudioConvert *ac;intin_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) returnNULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method!=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt)>2){ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc){av_free(ac);returnNULL;}returnac;}in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar){ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar?ac->channels:1;}elseif(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;elseac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);returnac;}intff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in){intuse_generic=1;intlen=in->nb_samples;intp;if(ac->dc){av_log(ac->avr, AV_LOG_TRACE,"%dsamples-audio_convert:%sto%s(dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));returnff_convert_dither(ac-> in
int timescale
Definition: ismindex.c:83
void * buf
Definition: avisynth_c.h:690
GLint GLenum type
Definition: opengl_enc.c:105
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
int index
Definition: gxfenc.c:89
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:1057
#define snprintf
Definition: snprintf.h:34
static void clean_tracks(struct Tracks *tracks)
Definition: ismindex.c:775
#define MOV_TRUN_SAMPLE_FLAGS
Definition: isom.h:267
struct Track ** tracks
Definition: ismindex.c:92
#define MOV_TFHD_STSD_ID
Definition: isom.h:256
int track_id
Definition: ismindex.c:75
static int64_t pts
Global timestamp for the audio frames.
static int flags
Definition: cpu.c:47
int64_t duration
Definition: ismindex.c:68
int codec_private_size
Definition: ismindex.c:81
int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
Put a description of the AVERROR code errnum in errbuf.
Definition: error.c:105
static int get_video_private_data(struct Track *track, AVCodecParameters *codecpar)
Definition: ismindex.c:467
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:935
int sample_rate
Audio only.
Definition: avcodec.h:4079
Main libavformat public API header.
int video_track
Definition: ismindex.c:93
int blocksize
Definition: ismindex.c:85
#define MOV_TFHD_BASE_DATA_OFFSET
Definition: isom.h:255
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3326
static int write_fragments(struct Tracks *tracks, int start_index, AVIOContext *in, const char *basename, int split, int ismf, const char *output_prefix)
Definition: ismindex.c:177
int den
Denominator.
Definition: rational.h:60
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4154
#define MKBETAG(a, b, c, d)
Definition: common.h:343
#define av_free(p)
int len
int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:503
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3983
#define MOV_TRUN_DATA_OFFSET
Definition: isom.h:263
int channels
Audio only.
Definition: avcodec.h:4075
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:354
FILE * out
Definition: movenc.c:54
#define av_freep(p)
static int read_tfra(struct Tracks *tracks, int start_index, AVIOContext *f)
Definition: ismindex.c:324
static int get_private_data(struct Track *track, AVCodecParameters *codecpar)
Definition: ismindex.c:456
AVCodecParameters * codecpar
Definition: avformat.h:1233
int nb_audio_tracks
Definition: ismindex.c:94
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:3973
int main(int argc, char **argv)
Definition: ismindex.c:787
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:918
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:44
static void output_server_manifest(struct Tracks *tracks, const char *basename, const char *output_prefix, const char *path_prefix, const char *ismc_prefix)
Definition: ismindex.c:619
int64_t offset
Definition: ismindex.c:67
static int64_t read_trun_duration(AVIOContext *in, int default_duration, int64_t end)
Definition: ismindex.c:230
int nb_video_tracks
Definition: ismindex.c:94