mov.c
Go to the documentation of this file.
1 /*
2  * MOV demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include <limits.h>
24 
25 //#define DEBUG
26 //#define MOV_EXPORT_ALL_METADATA
27 
28 #include "libavutil/audioconvert.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/intfloat.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/dict.h"
34 #include "libavcodec/ac3tab.h"
35 #include "avformat.h"
36 #include "internal.h"
37 #include "avio_internal.h"
38 #include "riff.h"
39 #include "isom.h"
40 #include "libavcodec/get_bits.h"
41 #include "id3v1.h"
42 #include "mov_chan.h"
43 
44 #if CONFIG_ZLIB
45 #include <zlib.h>
46 #endif
47 
48 /*
49  * First version by Francois Revol revol@free.fr
50  * Seek function by Gael Chardon gael.dev@4now.net
51  */
52 
53 #include "qtpalette.h"
54 
55 
56 #undef NDEBUG
57 #include <assert.h>
58 
59 /* those functions parse an atom */
60 /* links atom IDs to parse functions */
61 typedef struct MOVParseTableEntry {
62  uint32_t type;
63  int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
65 
67 
69  unsigned len, const char *key)
70 {
71  char buf[16];
72 
73  short current, total;
74  avio_rb16(pb); // unknown
75  current = avio_rb16(pb);
76  total = avio_rb16(pb);
77  if (!total)
78  snprintf(buf, sizeof(buf), "%d", current);
79  else
80  snprintf(buf, sizeof(buf), "%d/%d", current, total);
81  av_dict_set(&c->fc->metadata, key, buf, 0);
82 
83  return 0;
84 }
85 
87  unsigned len, const char *key)
88 {
89  char buf[16];
90 
91  /* bypass padding bytes */
92  avio_r8(pb);
93  avio_r8(pb);
94  avio_r8(pb);
95 
96  snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
97  av_dict_set(&c->fc->metadata, key, buf, 0);
98 
99  return 0;
100 }
101 
103  unsigned len, const char *key)
104 {
105  char buf[16];
106 
107  snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
108  av_dict_set(&c->fc->metadata, key, buf, 0);
109 
110  return 0;
111 }
112 
114  unsigned len, const char *key)
115 {
116  short genre;
117  char buf[20];
118 
119  avio_r8(pb); // unknown
120 
121  genre = avio_r8(pb);
122  if (genre < 1 || genre > ID3v1_GENRE_MAX)
123  return 0;
124  snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
125  av_dict_set(&c->fc->metadata, key, buf, 0);
126 
127  return 0;
128 }
129 
130 static const uint32_t mac_to_unicode[128] = {
131  0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
132  0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
133  0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
134  0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
135  0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
136  0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
137  0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
138  0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
139  0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
140  0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
141  0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
142  0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
143  0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
144  0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
145  0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
146  0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
147 };
148 
150  char *dst, int dstlen)
151 {
152  char *p = dst;
153  char *end = dst+dstlen-1;
154  int i;
155 
156  for (i = 0; i < len; i++) {
157  uint8_t t, c = avio_r8(pb);
158  if (c < 0x80 && p < end)
159  *p++ = c;
160  else
161  PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
162  }
163  *p = 0;
164  return p - dst;
165 }
166 
168 {
169 #ifdef MOV_EXPORT_ALL_METADATA
170  char tmp_key[5];
171 #endif
172  char str[1024], key2[16], language[4] = {0};
173  const char *key = NULL;
174  uint16_t str_size, langcode = 0;
175  uint32_t data_type = 0;
176  int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
177 
178  switch (atom.type) {
179  case MKTAG(0xa9,'n','a','m'): key = "title"; break;
180  case MKTAG(0xa9,'a','u','t'):
181  case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
182  case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
183  case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
184  case MKTAG( 'c','p','r','t'):
185  case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
186  case MKTAG(0xa9,'c','m','t'):
187  case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
188  case MKTAG(0xa9,'a','l','b'): key = "album"; break;
189  case MKTAG(0xa9,'d','a','y'): key = "date"; break;
190  case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
191  case MKTAG( 'g','n','r','e'): key = "genre";
192  parse = mov_metadata_gnre; break;
193  case MKTAG(0xa9,'t','o','o'):
194  case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
195  case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
196  case MKTAG( 'd','e','s','c'): key = "description";break;
197  case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
198  case MKTAG( 't','v','s','h'): key = "show"; break;
199  case MKTAG( 't','v','e','n'): key = "episode_id";break;
200  case MKTAG( 't','v','n','n'): key = "network"; break;
201  case MKTAG( 't','r','k','n'): key = "track";
203  case MKTAG( 'd','i','s','k'): key = "disc";
205  case MKTAG( 't','v','e','s'): key = "episode_sort";
207  case MKTAG( 't','v','s','n'): key = "season_number";
209  case MKTAG( 's','t','i','k'): key = "media_type";
211  case MKTAG( 'h','d','v','d'): key = "hd_video";
213  case MKTAG( 'p','g','a','p'): key = "gapless_playback";
215  }
216 
217  if (c->itunes_metadata && atom.size > 8) {
218  int data_size = avio_rb32(pb);
219  int tag = avio_rl32(pb);
220  if (tag == MKTAG('d','a','t','a')) {
221  data_type = avio_rb32(pb); // type
222  avio_rb32(pb); // unknown
223  str_size = data_size - 16;
224  atom.size -= 16;
225  } else return 0;
226  } else if (atom.size > 4 && key && !c->itunes_metadata) {
227  str_size = avio_rb16(pb); // string length
228  langcode = avio_rb16(pb);
229  ff_mov_lang_to_iso639(langcode, language);
230  atom.size -= 4;
231  } else
232  str_size = atom.size;
233 
234 #ifdef MOV_EXPORT_ALL_METADATA
235  if (!key) {
236  snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
237  key = tmp_key;
238  }
239 #endif
240 
241  if (!key)
242  return 0;
243  if (atom.size < 0)
244  return AVERROR_INVALIDDATA;
245 
246  str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
247 
248  if (parse)
249  parse(c, pb, str_size, key);
250  else {
251  if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
252  mov_read_mac_string(c, pb, str_size, str, sizeof(str));
253  } else {
254  avio_read(pb, str, str_size);
255  str[str_size] = 0;
256  }
257  av_dict_set(&c->fc->metadata, key, str, 0);
258  if (*language && strcmp(language, "und")) {
259  snprintf(key2, sizeof(key2), "%s-%s", key, language);
260  av_dict_set(&c->fc->metadata, key2, str, 0);
261  }
262  }
263  av_dlog(c->fc, "lang \"%3s\" ", language);
264  av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
265  key, str, (char*)&atom.type, str_size, atom.size);
266 
267  return 0;
268 }
269 
270 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
271 {
272  int64_t start;
273  int i, nb_chapters, str_len, version;
274  char str[256+1];
275 
276  if ((atom.size -= 5) < 0)
277  return 0;
278 
279  version = avio_r8(pb);
280  avio_rb24(pb);
281  if (version)
282  avio_rb32(pb); // ???
283  nb_chapters = avio_r8(pb);
284 
285  for (i = 0; i < nb_chapters; i++) {
286  if (atom.size < 9)
287  return 0;
288 
289  start = avio_rb64(pb);
290  str_len = avio_r8(pb);
291 
292  if ((atom.size -= 9+str_len) < 0)
293  return 0;
294 
295  avio_read(pb, str, str_len);
296  str[str_len] = 0;
297  avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
298  }
299  return 0;
300 }
301 
303 {
304  int64_t total_size = 0;
305  MOVAtom a;
306  int i;
307 
308  if (atom.size < 0)
309  atom.size = INT64_MAX;
310  while (total_size + 8 < atom.size && !pb->eof_reached) {
311  int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
312  a.size = atom.size;
313  a.type=0;
314  if (atom.size >= 8) {
315  a.size = avio_rb32(pb);
316  a.type = avio_rl32(pb);
317  }
318  av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
319  a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
320  total_size += 8;
321  if (a.size == 1) { /* 64 bit extended size */
322  a.size = avio_rb64(pb) - 8;
323  total_size += 8;
324  }
325  if (a.size == 0) {
326  a.size = atom.size - total_size;
327  if (a.size <= 8)
328  break;
329  }
330  a.size -= 8;
331  if (a.size < 0)
332  break;
333  a.size = FFMIN(a.size, atom.size - total_size);
334 
335  for (i = 0; mov_default_parse_table[i].type; i++)
336  if (mov_default_parse_table[i].type == a.type) {
337  parse = mov_default_parse_table[i].parse;
338  break;
339  }
340 
341  // container is user data
342  if (!parse && (atom.type == MKTAG('u','d','t','a') ||
343  atom.type == MKTAG('i','l','s','t')))
345 
346  if (!parse) { /* skip leaf atoms data */
347  avio_skip(pb, a.size);
348  } else {
349  int64_t start_pos = avio_tell(pb);
350  int64_t left;
351  int err = parse(c, pb, a);
352  if (err < 0)
353  return err;
354  if (c->found_moov && c->found_mdat &&
355  (!pb->seekable || start_pos + a.size == avio_size(pb)))
356  return 0;
357  left = a.size - avio_tell(pb) + start_pos;
358  if (left > 0) /* skip garbage at atom end */
359  avio_skip(pb, left);
360  else if (left < 0) {
362  "overread end of atom '%.4s' by %"PRId64" bytes\n",
363  (char*)&a.type, -left);
364  avio_seek(pb, left, SEEK_CUR);
365  }
366  }
367 
368  total_size += a.size;
369  }
370 
371  if (total_size < atom.size && atom.size < 0x7ffff)
372  avio_skip(pb, atom.size - total_size);
373 
374  return 0;
375 }
376 
377 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
378 {
379  AVStream *st;
380  MOVStreamContext *sc;
381  int entries, i, j;
382 
383  if (c->fc->nb_streams < 1)
384  return 0;
385  st = c->fc->streams[c->fc->nb_streams-1];
386  sc = st->priv_data;
387 
388  avio_rb32(pb); // version + flags
389  entries = avio_rb32(pb);
390  if (!entries ||
391  entries >= UINT_MAX / sizeof(*sc->drefs))
392  return AVERROR_INVALIDDATA;
393  sc->drefs_count = 0;
394  sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
395  if (!sc->drefs)
396  return AVERROR(ENOMEM);
397  sc->drefs_count = entries;
398 
399  for (i = 0; i < sc->drefs_count; i++) {
400  MOVDref *dref = &sc->drefs[i];
401  uint32_t size = avio_rb32(pb);
402  int64_t next = avio_tell(pb) + size - 4;
403 
404  if (size < 12)
405  return AVERROR_INVALIDDATA;
406 
407  dref->type = avio_rl32(pb);
408  avio_rb32(pb); // version + flags
409  av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
410 
411  if (dref->type == MKTAG('a','l','i','s') && size > 150) {
412  /* macintosh alias record */
413  uint16_t volume_len, len;
414  int16_t type;
415 
416  avio_skip(pb, 10);
417 
418  volume_len = avio_r8(pb);
419  volume_len = FFMIN(volume_len, 27);
420  avio_read(pb, dref->volume, 27);
421  dref->volume[volume_len] = 0;
422  av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
423 
424  avio_skip(pb, 12);
425 
426  len = avio_r8(pb);
427  len = FFMIN(len, 63);
428  avio_read(pb, dref->filename, 63);
429  dref->filename[len] = 0;
430  av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
431 
432  avio_skip(pb, 16);
433 
434  /* read next level up_from_alias/down_to_target */
435  dref->nlvl_from = avio_rb16(pb);
436  dref->nlvl_to = avio_rb16(pb);
437  av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
438  dref->nlvl_from, dref->nlvl_to);
439 
440  avio_skip(pb, 16);
441 
442  for (type = 0; type != -1 && avio_tell(pb) < next; ) {
443  type = avio_rb16(pb);
444  len = avio_rb16(pb);
445  av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
446  if (len&1)
447  len += 1;
448  if (type == 2) { // absolute path
449  av_free(dref->path);
450  dref->path = av_mallocz(len+1);
451  if (!dref->path)
452  return AVERROR(ENOMEM);
453  avio_read(pb, dref->path, len);
454  if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
455  len -= volume_len;
456  memmove(dref->path, dref->path+volume_len, len);
457  dref->path[len] = 0;
458  }
459  for (j = 0; j < len; j++)
460  if (dref->path[j] == ':')
461  dref->path[j] = '/';
462  av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
463  } else if (type == 0) { // directory name
464  av_free(dref->dir);
465  dref->dir = av_malloc(len+1);
466  if (!dref->dir)
467  return AVERROR(ENOMEM);
468  avio_read(pb, dref->dir, len);
469  dref->dir[len] = 0;
470  for (j = 0; j < len; j++)
471  if (dref->dir[j] == ':')
472  dref->dir[j] = '/';
473  av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
474  } else
475  avio_skip(pb, len);
476  }
477  }
478  avio_seek(pb, next, SEEK_SET);
479  }
480  return 0;
481 }
482 
483 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
484 {
485  AVStream *st;
486  uint32_t type;
487  uint32_t av_unused ctype;
488 
489  if (c->fc->nb_streams < 1) // meta before first trak
490  return 0;
491 
492  st = c->fc->streams[c->fc->nb_streams-1];
493 
494  avio_r8(pb); /* version */
495  avio_rb24(pb); /* flags */
496 
497  /* component type */
498  ctype = avio_rl32(pb);
499  type = avio_rl32(pb); /* component subtype */
500 
501  av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
502  av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
503 
504  if (type == MKTAG('v','i','d','e'))
506  else if (type == MKTAG('s','o','u','n'))
508  else if (type == MKTAG('m','1','a',' '))
509  st->codec->codec_id = CODEC_ID_MP2;
510  else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
512 
513  avio_rb32(pb); /* component manufacture */
514  avio_rb32(pb); /* component flags */
515  avio_rb32(pb); /* component flags mask */
516 
517  return 0;
518 }
519 
521 {
522  AVStream *st;
523  int tag;
524 
525  if (fc->nb_streams < 1)
526  return 0;
527  st = fc->streams[fc->nb_streams-1];
528 
529  avio_rb32(pb); /* version + flags */
530  ff_mp4_read_descr(fc, pb, &tag);
531  if (tag == MP4ESDescrTag) {
533  } else
534  avio_rb16(pb); /* ID */
535 
536  ff_mp4_read_descr(fc, pb, &tag);
537  if (tag == MP4DecConfigDescrTag)
538  ff_mp4_read_dec_config_descr(fc, st, pb);
539  return 0;
540 }
541 
542 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
543 {
544  return ff_mov_read_esds(c->fc, pb, atom);
545 }
546 
547 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
548 {
549  AVStream *st;
550  int ac3info, acmod, lfeon, bsmod;
551 
552  if (c->fc->nb_streams < 1)
553  return 0;
554  st = c->fc->streams[c->fc->nb_streams-1];
555 
556  ac3info = avio_rb24(pb);
557  bsmod = (ac3info >> 14) & 0x7;
558  acmod = (ac3info >> 11) & 0x7;
559  lfeon = (ac3info >> 10) & 0x1;
560  st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
562  if (lfeon)
564  st->codec->audio_service_type = bsmod;
565  if (st->codec->channels > 1 && bsmod == 0x7)
567 
568  return 0;
569 }
570 
571 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
572 {
573  AVStream *st;
574  uint8_t version;
575  uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
576  int i;
577 
578  if (c->fc->nb_streams < 1)
579  return 0;
580  st = c->fc->streams[c->fc->nb_streams-1];
581 
582  if (atom.size < 16)
583  return 0;
584 
585  version = avio_r8(pb);
586  flags = avio_rb24(pb);
587 
588  layout_tag = avio_rb32(pb);
589  bitmap = avio_rb32(pb);
590  num_descr = avio_rb32(pb);
591 
592  if (atom.size < 16ULL + num_descr * 20ULL)
593  return 0;
594 
595  av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
596  atom.size, version, flags, layout_tag, bitmap, num_descr);
597 
598  label_mask = 0;
599  for (i = 0; i < num_descr; i++) {
600  uint32_t label, cflags;
601  label = avio_rb32(pb); // mChannelLabel
602  cflags = avio_rb32(pb); // mChannelFlags
603  avio_rl32(pb); // mCoordinates[0]
604  avio_rl32(pb); // mCoordinates[1]
605  avio_rl32(pb); // mCoordinates[2]
606  if (layout_tag == 0) {
607  uint32_t mask_incr = ff_mov_get_channel_label(label);
608  if (mask_incr == 0) {
609  label_mask = 0;
610  break;
611  }
612  label_mask |= mask_incr;
613  }
614  }
615  if (layout_tag == 0)
616  st->codec->channel_layout = label_mask;
617  else
618  st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
619 
620  return 0;
621 }
622 
623 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
624 {
625  AVStream *st;
626 
627  if (c->fc->nb_streams < 1)
628  return 0;
629  st = c->fc->streams[c->fc->nb_streams-1];
630 
631  ff_get_wav_header(pb, st->codec, atom.size);
632 
633  return 0;
634 }
635 
636 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
637 {
638  const int num = avio_rb32(pb);
639  const int den = avio_rb32(pb);
640  AVStream *st;
641 
642  if (c->fc->nb_streams < 1)
643  return 0;
644  st = c->fc->streams[c->fc->nb_streams-1];
645 
646  if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
647  (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
649  "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
651  num, den);
652  } else if (den != 0) {
653  st->sample_aspect_ratio.num = num;
654  st->sample_aspect_ratio.den = den;
655  }
656  return 0;
657 }
658 
659 /* this atom contains actual media data */
660 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
661 {
662  if (atom.size == 0) /* wrong one (MP4) */
663  return 0;
664  c->found_mdat=1;
665  return 0; /* now go for moov */
666 }
667 
668 /* read major brand, minor version and compatible brands and store them as metadata */
669 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
670 {
671  uint32_t minor_ver;
672  int comp_brand_size;
673  char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
674  char* comp_brands_str;
675  uint8_t type[5] = {0};
676 
677  avio_read(pb, type, 4);
678  if (strcmp(type, "qt "))
679  c->isom = 1;
680  av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
681  av_dict_set(&c->fc->metadata, "major_brand", type, 0);
682  minor_ver = avio_rb32(pb); /* minor version */
683  snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
684  av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
685 
686  comp_brand_size = atom.size - 8;
687  if (comp_brand_size < 0)
688  return AVERROR_INVALIDDATA;
689  comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
690  if (!comp_brands_str)
691  return AVERROR(ENOMEM);
692  avio_read(pb, comp_brands_str, comp_brand_size);
693  comp_brands_str[comp_brand_size] = 0;
694  av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
695  av_freep(&comp_brands_str);
696 
697  return 0;
698 }
699 
700 /* this atom should contain all header atoms */
701 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
702 {
703  int ret;
704 
705  if ((ret = mov_read_default(c, pb, atom)) < 0)
706  return ret;
707  /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
708  /* so we don't parse the whole file if over a network */
709  c->found_moov=1;
710  return 0; /* now go for mdat */
711 }
712 
713 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
714 {
715  c->fragment.moof_offset = avio_tell(pb) - 8;
716  av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
717  return mov_read_default(c, pb, atom);
718 }
719 
721 {
722  char buffer[32];
723  if (time) {
724  struct tm *ptm;
725  time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
726  ptm = gmtime(&time);
727  if (!ptm) return;
728  strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
729  av_dict_set(metadata, "creation_time", buffer, 0);
730  }
731 }
732 
733 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
734 {
735  AVStream *st;
736  MOVStreamContext *sc;
737  int version;
738  char language[4] = {0};
739  unsigned lang;
740  time_t creation_time;
741 
742  if (c->fc->nb_streams < 1)
743  return 0;
744  st = c->fc->streams[c->fc->nb_streams-1];
745  sc = st->priv_data;
746 
747  if (sc->time_scale) {
748  av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
749  return AVERROR_INVALIDDATA;
750  }
751 
752  version = avio_r8(pb);
753  if (version > 1) {
754  av_log_ask_for_sample(c, "unsupported version %d\n", version);
755  return AVERROR_PATCHWELCOME;
756  }
757  avio_rb24(pb); /* flags */
758  if (version == 1) {
759  creation_time = avio_rb64(pb);
760  avio_rb64(pb);
761  } else {
762  creation_time = avio_rb32(pb);
763  avio_rb32(pb); /* modification time */
764  }
765  mov_metadata_creation_time(&st->metadata, creation_time);
766 
767  sc->time_scale = avio_rb32(pb);
768  st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
769 
770  lang = avio_rb16(pb); /* language */
771  if (ff_mov_lang_to_iso639(lang, language))
772  av_dict_set(&st->metadata, "language", language, 0);
773  avio_rb16(pb); /* quality */
774 
775  return 0;
776 }
777 
778 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
779 {
780  time_t creation_time;
781  int version = avio_r8(pb); /* version */
782  avio_rb24(pb); /* flags */
783 
784  if (version == 1) {
785  creation_time = avio_rb64(pb);
786  avio_rb64(pb);
787  } else {
788  creation_time = avio_rb32(pb);
789  avio_rb32(pb); /* modification time */
790  }
791  mov_metadata_creation_time(&c->fc->metadata, creation_time);
792  c->time_scale = avio_rb32(pb); /* time scale */
793 
794  av_dlog(c->fc, "time scale = %i\n", c->time_scale);
795 
796  c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
797  avio_rb32(pb); /* preferred scale */
798 
799  avio_rb16(pb); /* preferred volume */
800 
801  avio_skip(pb, 10); /* reserved */
802 
803  avio_skip(pb, 36); /* display matrix */
804 
805  avio_rb32(pb); /* preview time */
806  avio_rb32(pb); /* preview duration */
807  avio_rb32(pb); /* poster time */
808  avio_rb32(pb); /* selection time */
809  avio_rb32(pb); /* selection duration */
810  avio_rb32(pb); /* current time */
811  avio_rb32(pb); /* next track ID */
812 
813  return 0;
814 }
815 
816 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
817 {
818  AVStream *st;
819 
820  if (c->fc->nb_streams < 1)
821  return 0;
822  st = c->fc->streams[c->fc->nb_streams-1];
823 
824  if ((uint64_t)atom.size > (1<<30))
825  return AVERROR_INVALIDDATA;
826 
827  // currently SVQ3 decoder expect full STSD header - so let's fake it
828  // this should be fixed and just SMI header should be passed
829  av_free(st->codec->extradata);
831  if (!st->codec->extradata)
832  return AVERROR(ENOMEM);
833  st->codec->extradata_size = 0x5a + atom.size;
834  memcpy(st->codec->extradata, "SVQ3", 4); // fake
835  avio_read(pb, st->codec->extradata + 0x5a, atom.size);
836  av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
837  return 0;
838 }
839 
840 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
841 {
842  AVStream *st;
843  int little_endian;
844 
845  if (c->fc->nb_streams < 1)
846  return 0;
847  st = c->fc->streams[c->fc->nb_streams-1];
848 
849  little_endian = avio_rb16(pb);
850  av_dlog(c->fc, "enda %d\n", little_endian);
851  if (little_endian == 1) {
852  switch (st->codec->codec_id) {
853  case CODEC_ID_PCM_S24BE:
855  break;
856  case CODEC_ID_PCM_S32BE:
858  break;
859  case CODEC_ID_PCM_F32BE:
861  break;
862  case CODEC_ID_PCM_F64BE:
864  break;
865  default:
866  break;
867  }
868  }
869  return 0;
870 }
871 
872 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
873 {
874  AVStream *st;
875  unsigned mov_field_order;
876  enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
877 
878  if (c->fc->nb_streams < 1) // will happen with jp2 files
879  return 0;
880  st = c->fc->streams[c->fc->nb_streams-1];
881  if (atom.size < 2)
882  return AVERROR_INVALIDDATA;
883  mov_field_order = avio_rb16(pb);
884  if ((mov_field_order & 0xFF00) == 0x0100)
885  decoded_field_order = AV_FIELD_PROGRESSIVE;
886  else if ((mov_field_order & 0xFF00) == 0x0200) {
887  switch (mov_field_order & 0xFF) {
888  case 0x01: decoded_field_order = AV_FIELD_TT;
889  break;
890  case 0x06: decoded_field_order = AV_FIELD_BB;
891  break;
892  case 0x09: decoded_field_order = AV_FIELD_TB;
893  break;
894  case 0x0E: decoded_field_order = AV_FIELD_BT;
895  break;
896  }
897  }
898  if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
899  av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
900  }
901  st->codec->field_order = decoded_field_order;
902 
903  return 0;
904 }
905 
906 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
908 {
909  AVStream *st;
910  uint64_t size;
911  uint8_t *buf;
912 
913  if (c->fc->nb_streams < 1) // will happen with jp2 files
914  return 0;
915  st= c->fc->streams[c->fc->nb_streams-1];
916  size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
917  if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
918  return AVERROR_INVALIDDATA;
919  buf= av_realloc(st->codec->extradata, size);
920  if (!buf)
921  return AVERROR(ENOMEM);
922  st->codec->extradata= buf;
923  buf+= st->codec->extradata_size;
925  AV_WB32( buf , atom.size + 8);
926  AV_WL32( buf + 4, atom.type);
927  avio_read(pb, buf + 8, atom.size);
928  return 0;
929 }
930 
931 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
932 {
933  AVStream *st;
934 
935  if (c->fc->nb_streams < 1)
936  return 0;
937  st = c->fc->streams[c->fc->nb_streams-1];
938 
939  if ((uint64_t)atom.size > (1<<30))
940  return AVERROR_INVALIDDATA;
941 
942  if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
943  // pass all frma atom to codec, needed at least for QDMC and QDM2
944  av_free(st->codec->extradata);
946  if (!st->codec->extradata)
947  return AVERROR(ENOMEM);
948  st->codec->extradata_size = atom.size;
949  avio_read(pb, st->codec->extradata, atom.size);
950  } else if (atom.size > 8) { /* to read frma, esds atoms */
951  int ret;
952  if ((ret = mov_read_default(c, pb, atom)) < 0)
953  return ret;
954  } else
955  avio_skip(pb, atom.size);
956  return 0;
957 }
958 
963 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
964 {
965  AVStream *st;
966 
967  if (c->fc->nb_streams < 1)
968  return 0;
969  st = c->fc->streams[c->fc->nb_streams-1];
970 
971  if ((uint64_t)atom.size > (1<<30))
972  return AVERROR_INVALIDDATA;
973 
974  if (atom.size >= 10) {
975  // Broken files created by legacy versions of Libav and FFmpeg will
976  // wrap a whole fiel atom inside of a glbl atom.
977  unsigned size = avio_rb32(pb);
978  unsigned type = avio_rl32(pb);
979  avio_seek(pb, -8, SEEK_CUR);
980  if (type == MKTAG('f','i','e','l') && size == atom.size)
981  return mov_read_default(c, pb, atom);
982  }
983  av_free(st->codec->extradata);
985  if (!st->codec->extradata)
986  return AVERROR(ENOMEM);
987  st->codec->extradata_size = atom.size;
988  avio_read(pb, st->codec->extradata, atom.size);
989  return 0;
990 }
991 
997 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
998 {
999  AVStream *st;
1000 
1001  if (c->fc->nb_streams < 1)
1002  return 0;
1003  if (atom.size <= 40)
1004  return 0;
1005  st = c->fc->streams[c->fc->nb_streams-1];
1006 
1007  if ((uint64_t)atom.size > (1<<30))
1008  return AVERROR_INVALIDDATA;
1009 
1010  av_free(st->codec->extradata);
1012  if (!st->codec->extradata)
1013  return AVERROR(ENOMEM);
1014  st->codec->extradata_size = atom.size - 40;
1015  avio_skip(pb, 40);
1016  avio_read(pb, st->codec->extradata, atom.size - 40);
1017  return 0;
1018 }
1019 
1020 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1021 {
1022  AVStream *st;
1023  MOVStreamContext *sc;
1024  unsigned int i, entries;
1025 
1026  if (c->fc->nb_streams < 1)
1027  return 0;
1028  st = c->fc->streams[c->fc->nb_streams-1];
1029  sc = st->priv_data;
1030 
1031  avio_r8(pb); /* version */
1032  avio_rb24(pb); /* flags */
1033 
1034  entries = avio_rb32(pb);
1035 
1036  if (!entries)
1037  return 0;
1038  if (entries >= UINT_MAX/sizeof(int64_t))
1039  return AVERROR_INVALIDDATA;
1040 
1041  sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1042  if (!sc->chunk_offsets)
1043  return AVERROR(ENOMEM);
1044  sc->chunk_count = entries;
1045 
1046  if (atom.type == MKTAG('s','t','c','o'))
1047  for (i=0; i<entries; i++)
1048  sc->chunk_offsets[i] = avio_rb32(pb);
1049  else if (atom.type == MKTAG('c','o','6','4'))
1050  for (i=0; i<entries; i++)
1051  sc->chunk_offsets[i] = avio_rb64(pb);
1052  else
1053  return AVERROR_INVALIDDATA;
1054 
1055  return 0;
1056 }
1057 
1063 {
1064  if (flags & 1) { // floating point
1065  if (flags & 2) { // big endian
1066  if (bps == 32) return CODEC_ID_PCM_F32BE;
1067  else if (bps == 64) return CODEC_ID_PCM_F64BE;
1068  } else {
1069  if (bps == 32) return CODEC_ID_PCM_F32LE;
1070  else if (bps == 64) return CODEC_ID_PCM_F64LE;
1071  }
1072  } else {
1073  if (flags & 2) {
1074  if (bps == 8)
1075  // signed integer
1076  if (flags & 4) return CODEC_ID_PCM_S8;
1077  else return CODEC_ID_PCM_U8;
1078  else if (bps == 16) return CODEC_ID_PCM_S16BE;
1079  else if (bps == 24) return CODEC_ID_PCM_S24BE;
1080  else if (bps == 32) return CODEC_ID_PCM_S32BE;
1081  } else {
1082  if (bps == 8)
1083  if (flags & 4) return CODEC_ID_PCM_S8;
1084  else return CODEC_ID_PCM_U8;
1085  else if (bps == 16) return CODEC_ID_PCM_S16LE;
1086  else if (bps == 24) return CODEC_ID_PCM_S24LE;
1087  else if (bps == 32) return CODEC_ID_PCM_S32LE;
1088  }
1089  }
1090  return CODEC_ID_NONE;
1091 }
1092 
1094 {
1095  AVStream *st;
1096  MOVStreamContext *sc;
1097  int j, pseudo_stream_id;
1098 
1099  if (c->fc->nb_streams < 1)
1100  return 0;
1101  st = c->fc->streams[c->fc->nb_streams-1];
1102  sc = st->priv_data;
1103 
1104  for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1105  //Parsing Sample description table
1106  enum CodecID id;
1107  int dref_id = 1;
1108  MOVAtom a = { AV_RL32("stsd") };
1109  int64_t start_pos = avio_tell(pb);
1110  int size = avio_rb32(pb); /* size */
1111  uint32_t format = avio_rl32(pb); /* data format */
1112 
1113  if (size >= 16) {
1114  avio_rb32(pb); /* reserved */
1115  avio_rb16(pb); /* reserved */
1116  dref_id = avio_rb16(pb);
1117  }
1118 
1119  if (st->codec->codec_tag &&
1120  st->codec->codec_tag != format &&
1122  : st->codec->codec_tag != MKTAG('j','p','e','g'))
1123  ){
1124  /* Multiple fourcc, we skip JPEG. This is not correct, we should
1125  * export it as a separate AVStream but this needs a few changes
1126  * in the MOV demuxer, patch welcome. */
1127  multiple_stsd:
1128  av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1129  avio_skip(pb, size - (avio_tell(pb) - start_pos));
1130  continue;
1131  }
1132  /* we cannot demux concatenated h264 streams because of different extradata */
1133  if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1134  goto multiple_stsd;
1135  sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1136  sc->dref_id= dref_id;
1137 
1138  st->codec->codec_tag = format;
1139  id = ff_codec_get_id(codec_movaudio_tags, format);
1140  if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1141  id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1142 
1143  if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1145  } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1146  format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1147  id = ff_codec_get_id(codec_movvideo_tags, format);
1148  if (id <= 0)
1149  id = ff_codec_get_id(ff_codec_bmp_tags, format);
1150  if (id > 0)
1152  else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1154  if (id > 0)
1156  }
1157  }
1158 
1159  av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1160  (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1161  (format >> 24) & 0xff, st->codec->codec_type);
1162 
1163  if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1164  unsigned int color_depth, len;
1165  int color_greyscale;
1166 
1167  st->codec->codec_id = id;
1168  avio_rb16(pb); /* version */
1169  avio_rb16(pb); /* revision level */
1170  avio_rb32(pb); /* vendor */
1171  avio_rb32(pb); /* temporal quality */
1172  avio_rb32(pb); /* spatial quality */
1173 
1174  st->codec->width = avio_rb16(pb); /* width */
1175  st->codec->height = avio_rb16(pb); /* height */
1176 
1177  avio_rb32(pb); /* horiz resolution */
1178  avio_rb32(pb); /* vert resolution */
1179  avio_rb32(pb); /* data size, always 0 */
1180  avio_rb16(pb); /* frames per samples */
1181 
1182  len = avio_r8(pb); /* codec name, pascal string */
1183  if (len > 31)
1184  len = 31;
1185  mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1186  if (len < 31)
1187  avio_skip(pb, 31 - len);
1188  /* codec_tag YV12 triggers an UV swap in rawdec.c */
1189  if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1190  st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1191 
1192  st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1193  st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1194  av_dlog(c->fc, "depth %d, ctab id %d\n",
1196  /* figure out the palette situation */
1197  color_depth = st->codec->bits_per_coded_sample & 0x1F;
1198  color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1199 
1200  /* if the depth is 2, 4, or 8 bpp, file is palettized */
1201  if ((color_depth == 2) || (color_depth == 4) ||
1202  (color_depth == 8)) {
1203  /* for palette traversal */
1204  unsigned int color_start, color_count, color_end;
1205  unsigned char r, g, b;
1206 
1207  if (color_greyscale) {
1208  int color_index, color_dec;
1209  /* compute the greyscale palette */
1210  st->codec->bits_per_coded_sample = color_depth;
1211  color_count = 1 << color_depth;
1212  color_index = 255;
1213  color_dec = 256 / (color_count - 1);
1214  for (j = 0; j < color_count; j++) {
1215  r = g = b = color_index;
1216  sc->palette[j] =
1217  (r << 16) | (g << 8) | (b);
1218  color_index -= color_dec;
1219  if (color_index < 0)
1220  color_index = 0;
1221  }
1222  } else if (st->codec->color_table_id) {
1223  const uint8_t *color_table;
1224  /* if flag bit 3 is set, use the default palette */
1225  color_count = 1 << color_depth;
1226  if (color_depth == 2)
1227  color_table = ff_qt_default_palette_4;
1228  else if (color_depth == 4)
1229  color_table = ff_qt_default_palette_16;
1230  else
1231  color_table = ff_qt_default_palette_256;
1232 
1233  for (j = 0; j < color_count; j++) {
1234  r = color_table[j * 3 + 0];
1235  g = color_table[j * 3 + 1];
1236  b = color_table[j * 3 + 2];
1237  sc->palette[j] =
1238  (r << 16) | (g << 8) | (b);
1239  }
1240  } else {
1241  /* load the palette from the file */
1242  color_start = avio_rb32(pb);
1243  color_count = avio_rb16(pb);
1244  color_end = avio_rb16(pb);
1245  if ((color_start <= 255) &&
1246  (color_end <= 255)) {
1247  for (j = color_start; j <= color_end; j++) {
1248  /* each R, G, or B component is 16 bits;
1249  * only use the top 8 bits; skip alpha bytes
1250  * up front */
1251  avio_r8(pb);
1252  avio_r8(pb);
1253  r = avio_r8(pb);
1254  avio_r8(pb);
1255  g = avio_r8(pb);
1256  avio_r8(pb);
1257  b = avio_r8(pb);
1258  avio_r8(pb);
1259  sc->palette[j] =
1260  (r << 16) | (g << 8) | (b);
1261  }
1262  }
1263  }
1264  sc->has_palette = 1;
1265  }
1266  } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1267  int bits_per_sample, flags;
1268  uint16_t version = avio_rb16(pb);
1269 
1270  st->codec->codec_id = id;
1271  avio_rb16(pb); /* revision level */
1272  avio_rb32(pb); /* vendor */
1273 
1274  st->codec->channels = avio_rb16(pb); /* channel count */
1275  av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1276  st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1277 
1278  sc->audio_cid = avio_rb16(pb);
1279  avio_rb16(pb); /* packet size = 0 */
1280 
1281  st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1282 
1283  //Read QT version 1 fields. In version 0 these do not exist.
1284  av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1285  if (!c->isom) {
1286  if (version==1) {
1287  sc->samples_per_frame = avio_rb32(pb);
1288  avio_rb32(pb); /* bytes per packet */
1289  sc->bytes_per_frame = avio_rb32(pb);
1290  avio_rb32(pb); /* bytes per sample */
1291  } else if (version==2) {
1292  avio_rb32(pb); /* sizeof struct only */
1293  st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1294  st->codec->channels = avio_rb32(pb);
1295  avio_rb32(pb); /* always 0x7F000000 */
1296  st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1297  flags = avio_rb32(pb); /* lpcm format specific flag */
1298  sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1299  sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1300  if (format == MKTAG('l','p','c','m'))
1302  }
1303  }
1304 
1305  switch (st->codec->codec_id) {
1306  case CODEC_ID_PCM_S8:
1307  case CODEC_ID_PCM_U8:
1308  if (st->codec->bits_per_coded_sample == 16)
1310  break;
1311  case CODEC_ID_PCM_S16LE:
1312  case CODEC_ID_PCM_S16BE:
1313  if (st->codec->bits_per_coded_sample == 8)
1315  else if (st->codec->bits_per_coded_sample == 24)
1316  st->codec->codec_id =
1319  break;
1320  /* set values for old format before stsd version 1 appeared */
1321  case CODEC_ID_MACE3:
1322  sc->samples_per_frame = 6;
1323  sc->bytes_per_frame = 2*st->codec->channels;
1324  break;
1325  case CODEC_ID_MACE6:
1326  sc->samples_per_frame = 6;
1327  sc->bytes_per_frame = 1*st->codec->channels;
1328  break;
1329  case CODEC_ID_ADPCM_IMA_QT:
1330  sc->samples_per_frame = 64;
1331  sc->bytes_per_frame = 34*st->codec->channels;
1332  break;
1333  case CODEC_ID_GSM:
1334  sc->samples_per_frame = 160;
1335  sc->bytes_per_frame = 33;
1336  break;
1337  default:
1338  break;
1339  }
1340 
1341  bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1342  if (bits_per_sample) {
1343  st->codec->bits_per_coded_sample = bits_per_sample;
1344  sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1345  }
1346  } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1347  // ttxt stsd contains display flags, justification, background
1348  // color, fonts, and default styles, so fake an atom to read it
1349  MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1350  if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1351  mov_read_glbl(c, pb, fake_atom);
1352  st->codec->codec_id= id;
1353  st->codec->width = sc->width;
1354  st->codec->height = sc->height;
1355  } else {
1356  /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1357  avio_skip(pb, size - (avio_tell(pb) - start_pos));
1358  }
1359  /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1360  a.size = size - (avio_tell(pb) - start_pos);
1361  if (a.size > 8) {
1362  int ret;
1363  if ((ret = mov_read_default(c, pb, a)) < 0)
1364  return ret;
1365  } else if (a.size > 0)
1366  avio_skip(pb, a.size);
1367  }
1368 
1369  if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1370  st->codec->sample_rate= sc->time_scale;
1371 
1372  /* special codec parameters handling */
1373  switch (st->codec->codec_id) {
1374 #if CONFIG_DV_DEMUXER
1375  case CODEC_ID_DVAUDIO:
1378  if (!c->dv_demux) {
1379  av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1380  return AVERROR(ENOMEM);
1381  }
1382  sc->dv_audio_container = 1;
1384  break;
1385 #endif
1386  /* no ifdef since parameters are always those */
1387  case CODEC_ID_QCELP:
1388  // force sample rate for qcelp when not stored in mov
1389  if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1390  st->codec->sample_rate = 8000;
1391  st->codec->frame_size= 160;
1392  st->codec->channels= 1; /* really needed */
1393  break;
1394  case CODEC_ID_AMR_NB:
1395  st->codec->channels= 1; /* really needed */
1396  /* force sample rate for amr, stsd in 3gp does not store sample rate */
1397  st->codec->sample_rate = 8000;
1398  /* force frame_size, too, samples_per_frame isn't always set properly */
1399  st->codec->frame_size = 160;
1400  break;
1401  case CODEC_ID_AMR_WB:
1402  st->codec->channels = 1;
1403  st->codec->sample_rate = 16000;
1404  st->codec->frame_size = 320;
1405  break;
1406  case CODEC_ID_MP2:
1407  case CODEC_ID_MP3:
1408  st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1410  break;
1411  case CODEC_ID_GSM:
1412  case CODEC_ID_ADPCM_MS:
1414  st->codec->frame_size = sc->samples_per_frame;
1415  st->codec->block_align = sc->bytes_per_frame;
1416  break;
1417  case CODEC_ID_ALAC:
1418  if (st->codec->extradata_size == 36) {
1419  st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1420  st->codec->channels = AV_RB8 (st->codec->extradata+21);
1421  st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1422  }
1423  break;
1424  default:
1425  break;
1426  }
1427 
1428  return 0;
1429 }
1430 
1431 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1432 {
1433  int entries;
1434 
1435  avio_r8(pb); /* version */
1436  avio_rb24(pb); /* flags */
1437  entries = avio_rb32(pb);
1438 
1439  return ff_mov_read_stsd_entries(c, pb, entries);
1440 }
1441 
1442 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1443 {
1444  AVStream *st;
1445  MOVStreamContext *sc;
1446  unsigned int i, entries;
1447 
1448  if (c->fc->nb_streams < 1)
1449  return 0;
1450  st = c->fc->streams[c->fc->nb_streams-1];
1451  sc = st->priv_data;
1452 
1453  avio_r8(pb); /* version */
1454  avio_rb24(pb); /* flags */
1455 
1456  entries = avio_rb32(pb);
1457 
1458  av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1459 
1460  if (!entries)
1461  return 0;
1462  if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1463  return AVERROR_INVALIDDATA;
1464  sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1465  if (!sc->stsc_data)
1466  return AVERROR(ENOMEM);
1467  sc->stsc_count = entries;
1468 
1469  for (i=0; i<entries; i++) {
1470  sc->stsc_data[i].first = avio_rb32(pb);
1471  sc->stsc_data[i].count = avio_rb32(pb);
1472  sc->stsc_data[i].id = avio_rb32(pb);
1473  }
1474  return 0;
1475 }
1476 
1477 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1478 {
1479  AVStream *st;
1480  MOVStreamContext *sc;
1481  unsigned i, entries;
1482 
1483  if (c->fc->nb_streams < 1)
1484  return 0;
1485  st = c->fc->streams[c->fc->nb_streams-1];
1486  sc = st->priv_data;
1487 
1488  avio_rb32(pb); // version + flags
1489 
1490  entries = avio_rb32(pb);
1491  if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1492  return AVERROR_INVALIDDATA;
1493  sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1494  if (!sc->stps_data)
1495  return AVERROR(ENOMEM);
1496  sc->stps_count = entries;
1497 
1498  for (i = 0; i < entries; i++) {
1499  sc->stps_data[i] = avio_rb32(pb);
1500  //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1501  }
1502 
1503  return 0;
1504 }
1505 
1506 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1507 {
1508  AVStream *st;
1509  MOVStreamContext *sc;
1510  unsigned int i, entries;
1511 
1512  if (c->fc->nb_streams < 1)
1513  return 0;
1514  st = c->fc->streams[c->fc->nb_streams-1];
1515  sc = st->priv_data;
1516 
1517  avio_r8(pb); /* version */
1518  avio_rb24(pb); /* flags */
1519 
1520  entries = avio_rb32(pb);
1521 
1522  av_dlog(c->fc, "keyframe_count = %d\n", entries);
1523 
1524  if (!entries)
1525  return 0;
1526  if (entries >= UINT_MAX / sizeof(int))
1527  return AVERROR_INVALIDDATA;
1528  av_freep(&sc->keyframes);
1529  sc->keyframes = av_malloc(entries * sizeof(int));
1530  if (!sc->keyframes)
1531  return AVERROR(ENOMEM);
1532  sc->keyframe_count = entries;
1533 
1534  for (i=0; i<entries; i++) {
1535  sc->keyframes[i] = avio_rb32(pb);
1536  //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1537  }
1538  return 0;
1539 }
1540 
1541 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1542 {
1543  AVStream *st;
1544  MOVStreamContext *sc;
1545  unsigned int i, entries, sample_size, field_size, num_bytes;
1546  GetBitContext gb;
1547  unsigned char* buf;
1548 
1549  if (c->fc->nb_streams < 1)
1550  return 0;
1551  st = c->fc->streams[c->fc->nb_streams-1];
1552  sc = st->priv_data;
1553 
1554  avio_r8(pb); /* version */
1555  avio_rb24(pb); /* flags */
1556 
1557  if (atom.type == MKTAG('s','t','s','z')) {
1558  sample_size = avio_rb32(pb);
1559  if (!sc->sample_size) /* do not overwrite value computed in stsd */
1560  sc->sample_size = sample_size;
1561  field_size = 32;
1562  } else {
1563  sample_size = 0;
1564  avio_rb24(pb); /* reserved */
1565  field_size = avio_r8(pb);
1566  }
1567  entries = avio_rb32(pb);
1568 
1569  av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1570 
1571  sc->sample_count = entries;
1572  if (sample_size)
1573  return 0;
1574 
1575  if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1576  av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1577  return AVERROR_INVALIDDATA;
1578  }
1579 
1580  if (!entries)
1581  return 0;
1582  if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1583  return AVERROR_INVALIDDATA;
1584  sc->sample_sizes = av_malloc(entries * sizeof(int));
1585  if (!sc->sample_sizes)
1586  return AVERROR(ENOMEM);
1587 
1588  num_bytes = (entries*field_size+4)>>3;
1589 
1590  buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1591  if (!buf) {
1592  av_freep(&sc->sample_sizes);
1593  return AVERROR(ENOMEM);
1594  }
1595 
1596  if (avio_read(pb, buf, num_bytes) < num_bytes) {
1597  av_freep(&sc->sample_sizes);
1598  av_free(buf);
1599  return AVERROR_INVALIDDATA;
1600  }
1601 
1602  init_get_bits(&gb, buf, 8*num_bytes);
1603 
1604  for (i=0; i<entries; i++)
1605  sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1606 
1607  av_free(buf);
1608  return 0;
1609 }
1610 
1611 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1612 {
1613  AVStream *st;
1614  MOVStreamContext *sc;
1615  unsigned int i, entries;
1616  int64_t duration=0;
1617  int64_t total_sample_count=0;
1618 
1619  if (c->fc->nb_streams < 1)
1620  return 0;
1621  st = c->fc->streams[c->fc->nb_streams-1];
1622  sc = st->priv_data;
1623 
1624  avio_r8(pb); /* version */
1625  avio_rb24(pb); /* flags */
1626  entries = avio_rb32(pb);
1627 
1628  av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1629  c->fc->nb_streams-1, entries);
1630 
1631  if (!entries)
1632  return 0;
1633  if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1634  return AVERROR(EINVAL);
1635 
1636  av_free(sc->stts_data);
1637  sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1638  if (!sc->stts_data)
1639  return AVERROR(ENOMEM);
1640 
1641  sc->stts_count = entries;
1642 
1643  for (i=0; i<entries; i++) {
1644  int sample_duration;
1645  int sample_count;
1646 
1647  sample_count=avio_rb32(pb);
1648  sample_duration = avio_rb32(pb);
1649  if (sample_count < 0) {
1650  av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
1651  return AVERROR_INVALIDDATA;
1652  }
1653  sc->stts_data[i].count= sample_count;
1654  sc->stts_data[i].duration= sample_duration;
1655 
1656  av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1657  sample_count, sample_duration);
1658 
1659  duration+=(int64_t)sample_duration*sample_count;
1660  total_sample_count+=sample_count;
1661  }
1662 
1663  st->nb_frames= total_sample_count;
1664  if (duration)
1665  st->duration= duration;
1666  return 0;
1667 }
1668 
1669 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1670 {
1671  AVStream *st;
1672  MOVStreamContext *sc;
1673  unsigned int i, entries;
1674 
1675  if (c->fc->nb_streams < 1)
1676  return 0;
1677  st = c->fc->streams[c->fc->nb_streams-1];
1678  sc = st->priv_data;
1679 
1680  avio_r8(pb); /* version */
1681  avio_rb24(pb); /* flags */
1682  entries = avio_rb32(pb);
1683 
1684  av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1685 
1686  if (!entries)
1687  return 0;
1688  if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1689  return AVERROR_INVALIDDATA;
1690  sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1691  if (!sc->ctts_data)
1692  return AVERROR(ENOMEM);
1693  sc->ctts_count = entries;
1694 
1695  for (i=0; i<entries; i++) {
1696  int count =avio_rb32(pb);
1697  int duration =avio_rb32(pb);
1698 
1699  sc->ctts_data[i].count = count;
1700  sc->ctts_data[i].duration= duration;
1701  if (duration < 0)
1702  sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1703  }
1704 
1705  av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1706 
1707  return 0;
1708 }
1709 
1710 static void mov_build_index(MOVContext *mov, AVStream *st)
1711 {
1712  MOVStreamContext *sc = st->priv_data;
1713  int64_t current_offset;
1714  int64_t current_dts = 0;
1715  unsigned int stts_index = 0;
1716  unsigned int stsc_index = 0;
1717  unsigned int stss_index = 0;
1718  unsigned int stps_index = 0;
1719  unsigned int i, j;
1720  uint64_t stream_size = 0;
1721  AVIndexEntry *mem;
1722 
1723  /* adjust first dts according to edit list */
1724  if (sc->time_offset && mov->time_scale > 0) {
1725  if (sc->time_offset < 0)
1726  sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1727  current_dts = -sc->time_offset;
1728  if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1729  sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1730  /* more than 16 frames delay, dts are likely wrong
1731  this happens with files created by iMovie */
1732  sc->wrong_dts = 1;
1733  st->codec->has_b_frames = 1;
1734  }
1735  }
1736 
1737  /* only use old uncompressed audio chunk demuxing when stts specifies it */
1738  if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1739  sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1740  unsigned int current_sample = 0;
1741  unsigned int stts_sample = 0;
1742  unsigned int sample_size;
1743  unsigned int distance = 0;
1744  int key_off = sc->keyframes && sc->keyframes[0] == 1;
1745 
1746  current_dts -= sc->dts_shift;
1747 
1748  if (!sc->sample_count)
1749  return;
1750  if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1751  return;
1752  mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1753  if (!mem)
1754  return;
1755  st->index_entries = mem;
1757 
1758  for (i = 0; i < sc->chunk_count; i++) {
1759  current_offset = sc->chunk_offsets[i];
1760  while (stsc_index + 1 < sc->stsc_count &&
1761  i + 1 == sc->stsc_data[stsc_index + 1].first)
1762  stsc_index++;
1763  for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1764  int keyframe = 0;
1765  if (current_sample >= sc->sample_count) {
1766  av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1767  return;
1768  }
1769 
1770  if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1771  keyframe = 1;
1772  if (stss_index + 1 < sc->keyframe_count)
1773  stss_index++;
1774  } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1775  keyframe = 1;
1776  if (stps_index + 1 < sc->stps_count)
1777  stps_index++;
1778  }
1779  if (keyframe)
1780  distance = 0;
1781  sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1782  if (sc->pseudo_stream_id == -1 ||
1783  sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1784  AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1785  e->pos = current_offset;
1786  e->timestamp = current_dts;
1787  e->size = sample_size;
1788  e->min_distance = distance;
1789  e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1790  av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1791  "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1792  current_offset, current_dts, sample_size, distance, keyframe);
1793  }
1794 
1795  current_offset += sample_size;
1796  stream_size += sample_size;
1797  current_dts += sc->stts_data[stts_index].duration;
1798  distance++;
1799  stts_sample++;
1800  current_sample++;
1801  if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1802  stts_sample = 0;
1803  stts_index++;
1804  }
1805  }
1806  }
1807  if (st->duration > 0)
1808  st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1809  } else {
1810  unsigned chunk_samples, total = 0;
1811 
1812  // compute total chunk count
1813  for (i = 0; i < sc->stsc_count; i++) {
1814  unsigned count, chunk_count;
1815 
1816  chunk_samples = sc->stsc_data[i].count;
1817  if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1818  av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1819  return;
1820  }
1821 
1822  if (sc->samples_per_frame >= 160) { // gsm
1823  count = chunk_samples / sc->samples_per_frame;
1824  } else if (sc->samples_per_frame > 1) {
1825  unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1826  count = (chunk_samples+samples-1) / samples;
1827  } else {
1828  count = (chunk_samples+1023) / 1024;
1829  }
1830 
1831  if (i < sc->stsc_count - 1)
1832  chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1833  else
1834  chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1835  total += chunk_count * count;
1836  }
1837 
1838  av_dlog(mov->fc, "chunk count %d\n", total);
1839  if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1840  return;
1841  mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1842  if (!mem)
1843  return;
1844  st->index_entries = mem;
1845  st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1846 
1847  // populate index
1848  for (i = 0; i < sc->chunk_count; i++) {
1849  current_offset = sc->chunk_offsets[i];
1850  if (stsc_index + 1 < sc->stsc_count &&
1851  i + 1 == sc->stsc_data[stsc_index + 1].first)
1852  stsc_index++;
1853  chunk_samples = sc->stsc_data[stsc_index].count;
1854 
1855  while (chunk_samples > 0) {
1856  AVIndexEntry *e;
1857  unsigned size, samples;
1858 
1859  if (sc->samples_per_frame >= 160) { // gsm
1860  samples = sc->samples_per_frame;
1861  size = sc->bytes_per_frame;
1862  } else {
1863  if (sc->samples_per_frame > 1) {
1864  samples = FFMIN((1024 / sc->samples_per_frame)*
1865  sc->samples_per_frame, chunk_samples);
1866  size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1867  } else {
1868  samples = FFMIN(1024, chunk_samples);
1869  size = samples * sc->sample_size;
1870  }
1871  }
1872 
1873  if (st->nb_index_entries >= total) {
1874  av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1875  return;
1876  }
1877  e = &st->index_entries[st->nb_index_entries++];
1878  e->pos = current_offset;
1879  e->timestamp = current_dts;
1880  e->size = size;
1881  e->min_distance = 0;
1882  e->flags = AVINDEX_KEYFRAME;
1883  av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1884  "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1885  size, samples);
1886 
1887  current_offset += size;
1888  current_dts += samples;
1889  chunk_samples -= samples;
1890  }
1891  }
1892  }
1893 }
1894 
1895 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1897 {
1898  /* try relative path, we do not try the absolute because it can leak information about our
1899  system to an attacker */
1900  if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1901  char filename[1024];
1902  char *src_path;
1903  int i, l;
1904 
1905  /* find a source dir */
1906  src_path = strrchr(src, '/');
1907  if (src_path)
1908  src_path++;
1909  else
1910  src_path = src;
1911 
1912  /* find a next level down to target */
1913  for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1914  if (ref->path[l] == '/') {
1915  if (i == ref->nlvl_to - 1)
1916  break;
1917  else
1918  i++;
1919  }
1920 
1921  /* compose filename if next level down to target was found */
1922  if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
1923  memcpy(filename, src, src_path - src);
1924  filename[src_path - src] = 0;
1925 
1926  for (i = 1; i < ref->nlvl_from; i++)
1927  av_strlcat(filename, "../", 1024);
1928 
1929  av_strlcat(filename, ref->path + l + 1, 1024);
1930 
1931  if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1932  return 0;
1933  }
1934  }
1935 
1936  return AVERROR(ENOENT);
1937 }
1938 
1939 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1940 {
1941  AVStream *st;
1942  MOVStreamContext *sc;
1943  int ret;
1944 
1945  st = avformat_new_stream(c->fc, NULL);
1946  if (!st) return AVERROR(ENOMEM);
1947  st->id = c->fc->nb_streams;
1948  sc = av_mallocz(sizeof(MOVStreamContext));
1949  if (!sc) return AVERROR(ENOMEM);
1950 
1951  st->priv_data = sc;
1953  sc->ffindex = st->index;
1954 
1955  if ((ret = mov_read_default(c, pb, atom)) < 0)
1956  return ret;
1957 
1958  /* sanity checks */
1959  if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1960  (!sc->sample_size && !sc->sample_count))) {
1961  av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1962  st->index);
1963  return 0;
1964  }
1965 
1966  if (sc->time_scale <= 0) {
1967  av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1968  sc->time_scale = c->time_scale;
1969  if (sc->time_scale <= 0)
1970  sc->time_scale = 1;
1971  }
1972 
1973  avpriv_set_pts_info(st, 64, 1, sc->time_scale);
1974 
1975  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1976  !st->codec->frame_size && sc->stts_count == 1) {
1978  st->codec->sample_rate, sc->time_scale);
1979  av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
1980  }
1981 
1982  mov_build_index(c, st);
1983 
1984  if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1985  MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1986  if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
1987  av_log(c->fc, AV_LOG_ERROR,
1988  "stream %d, error opening alias: path='%s', dir='%s', "
1989  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1990  st->index, dref->path, dref->dir, dref->filename,
1991  dref->volume, dref->nlvl_from, dref->nlvl_to);
1992  } else
1993  sc->pb = c->fc->pb;
1994 
1995  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1996  if (!st->sample_aspect_ratio.num &&
1997  (st->codec->width != sc->width || st->codec->height != sc->height)) {
1998  st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1999  ((double)st->codec->width * sc->height), INT_MAX);
2000  }
2001 
2003  sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2004 
2005  if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2007  sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2008  }
2009 
2010  switch (st->codec->codec_id) {
2011 #if CONFIG_H261_DECODER
2012  case CODEC_ID_H261:
2013 #endif
2014 #if CONFIG_H263_DECODER
2015  case CODEC_ID_H263:
2016 #endif
2017 #if CONFIG_MPEG4_DECODER
2018  case CODEC_ID_MPEG4:
2019 #endif
2020  st->codec->width = 0; /* let decoder init width/height */
2021  st->codec->height= 0;
2022  break;
2023  }
2024 
2025  /* Do not need those anymore. */
2026  av_freep(&sc->chunk_offsets);
2027  av_freep(&sc->stsc_data);
2028  av_freep(&sc->sample_sizes);
2029  av_freep(&sc->keyframes);
2030  av_freep(&sc->stts_data);
2031  av_freep(&sc->stps_data);
2032 
2033  return 0;
2034 }
2035 
2036 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2037 {
2038  int ret;
2039  c->itunes_metadata = 1;
2040  ret = mov_read_default(c, pb, atom);
2041  c->itunes_metadata = 0;
2042  return ret;
2043 }
2044 
2045 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2046 {
2047  while (atom.size > 8) {
2048  uint32_t tag = avio_rl32(pb);
2049  atom.size -= 4;
2050  if (tag == MKTAG('h','d','l','r')) {
2051  avio_seek(pb, -8, SEEK_CUR);
2052  atom.size += 8;
2053  return mov_read_default(c, pb, atom);
2054  }
2055  }
2056  return 0;
2057 }
2058 
2059 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2060 {
2061  int i;
2062  int width;
2063  int height;
2064  int64_t disp_transform[2];
2065  int display_matrix[3][2];
2066  AVStream *st;
2067  MOVStreamContext *sc;
2068  int version;
2069 
2070  if (c->fc->nb_streams < 1)
2071  return 0;
2072  st = c->fc->streams[c->fc->nb_streams-1];
2073  sc = st->priv_data;
2074 
2075  version = avio_r8(pb);
2076  avio_rb24(pb); /* flags */
2077  /*
2078  MOV_TRACK_ENABLED 0x0001
2079  MOV_TRACK_IN_MOVIE 0x0002
2080  MOV_TRACK_IN_PREVIEW 0x0004
2081  MOV_TRACK_IN_POSTER 0x0008
2082  */
2083 
2084  if (version == 1) {
2085  avio_rb64(pb);
2086  avio_rb64(pb);
2087  } else {
2088  avio_rb32(pb); /* creation time */
2089  avio_rb32(pb); /* modification time */
2090  }
2091  st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2092  avio_rb32(pb); /* reserved */
2093 
2094  /* highlevel (considering edits) duration in movie timebase */
2095  (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2096  avio_rb32(pb); /* reserved */
2097  avio_rb32(pb); /* reserved */
2098 
2099  avio_rb16(pb); /* layer */
2100  avio_rb16(pb); /* alternate group */
2101  avio_rb16(pb); /* volume */
2102  avio_rb16(pb); /* reserved */
2103 
2104  //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2105  // they're kept in fixed point format through all calculations
2106  // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2107  for (i = 0; i < 3; i++) {
2108  display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2109  display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2110  avio_rb32(pb); // 2.30 fixed point (not used)
2111  }
2112 
2113  width = avio_rb32(pb); // 16.16 fixed point track width
2114  height = avio_rb32(pb); // 16.16 fixed point track height
2115  sc->width = width >> 16;
2116  sc->height = height >> 16;
2117 
2118  // transform the display width/height according to the matrix
2119  // skip this if the display matrix is the default identity matrix
2120  // or if it is rotating the picture, ex iPhone 3GS
2121  // to keep the same scale, use [width height 1<<16]
2122  if (width && height &&
2123  ((display_matrix[0][0] != 65536 ||
2124  display_matrix[1][1] != 65536) &&
2125  !display_matrix[0][1] &&
2126  !display_matrix[1][0] &&
2127  !display_matrix[2][0] && !display_matrix[2][1])) {
2128  for (i = 0; i < 2; i++)
2129  disp_transform[i] =
2130  (int64_t) width * display_matrix[0][i] +
2131  (int64_t) height * display_matrix[1][i] +
2132  ((int64_t) display_matrix[2][i] << 16);
2133 
2134  //sample aspect ratio is new width/height divided by old width/height
2136  ((double) disp_transform[0] * height) /
2137  ((double) disp_transform[1] * width), INT_MAX);
2138  }
2139  return 0;
2140 }
2141 
2142 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2143 {
2144  MOVFragment *frag = &c->fragment;
2145  MOVTrackExt *trex = NULL;
2146  int flags, track_id, i;
2147 
2148  avio_r8(pb); /* version */
2149  flags = avio_rb24(pb);
2150 
2151  track_id = avio_rb32(pb);
2152  if (!track_id)
2153  return AVERROR_INVALIDDATA;
2154  frag->track_id = track_id;
2155  for (i = 0; i < c->trex_count; i++)
2156  if (c->trex_data[i].track_id == frag->track_id) {
2157  trex = &c->trex_data[i];
2158  break;
2159  }
2160  if (!trex) {
2161  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2162  return AVERROR_INVALIDDATA;
2163  }
2164 
2165  if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
2166  else frag->base_data_offset = frag->moof_offset;
2167  if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
2168  else frag->stsd_id = trex->stsd_id;
2169 
2170  frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2171  frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
2172  frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2173  av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2174  return 0;
2175 }
2176 
2177 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2178 {
2179  c->chapter_track = avio_rb32(pb);
2180  return 0;
2181 }
2182 
2183 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2184 {
2185  MOVTrackExt *trex;
2186 
2187  if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2188  return AVERROR_INVALIDDATA;
2189  trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2190  if (!trex)
2191  return AVERROR(ENOMEM);
2192  c->trex_data = trex;
2193  trex = &c->trex_data[c->trex_count++];
2194  avio_r8(pb); /* version */
2195  avio_rb24(pb); /* flags */
2196  trex->track_id = avio_rb32(pb);
2197  trex->stsd_id = avio_rb32(pb);
2198  trex->duration = avio_rb32(pb);
2199  trex->size = avio_rb32(pb);
2200  trex->flags = avio_rb32(pb);
2201  return 0;
2202 }
2203 
2204 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2205 {
2206  MOVFragment *frag = &c->fragment;
2207  AVStream *st = NULL;
2208  MOVStreamContext *sc;
2209  MOVStts *ctts_data;
2210  uint64_t offset;
2211  int64_t dts;
2212  int data_offset = 0;
2213  unsigned entries, first_sample_flags = frag->flags;
2214  int flags, distance, i;
2215 
2216  for (i = 0; i < c->fc->nb_streams; i++) {
2217  if (c->fc->streams[i]->id == frag->track_id) {
2218  st = c->fc->streams[i];
2219  break;
2220  }
2221  }
2222  if (!st) {
2223  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2224  return AVERROR_INVALIDDATA;
2225  }
2226  sc = st->priv_data;
2227  if (sc->pseudo_stream_id+1 != frag->stsd_id)
2228  return 0;
2229  avio_r8(pb); /* version */
2230  flags = avio_rb24(pb);
2231  entries = avio_rb32(pb);
2232  av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2233 
2234  /* Always assume the presence of composition time offsets.
2235  * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2236  * 1) in the initial movie, there are no samples.
2237  * 2) in the first movie fragment, there is only one sample without composition time offset.
2238  * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2239  if (!sc->ctts_count && sc->sample_count)
2240  {
2241  /* Complement ctts table if moov atom doesn't have ctts atom. */
2242  ctts_data = av_malloc(sizeof(*sc->ctts_data));
2243  if (!ctts_data)
2244  return AVERROR(ENOMEM);
2245  sc->ctts_data = ctts_data;
2246  sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2247  sc->ctts_data[sc->ctts_count].duration = 0;
2248  sc->ctts_count++;
2249  }
2250  if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2251  return AVERROR_INVALIDDATA;
2252  ctts_data = av_realloc(sc->ctts_data,
2253  (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2254  if (!ctts_data)
2255  return AVERROR(ENOMEM);
2256  sc->ctts_data = ctts_data;
2257 
2258  if (flags & 0x001) data_offset = avio_rb32(pb);
2259  if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2260  dts = st->duration - sc->time_offset;
2261  offset = frag->base_data_offset + data_offset;
2262  distance = 0;
2263  av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2264  for (i = 0; i < entries; i++) {
2265  unsigned sample_size = frag->size;
2266  int sample_flags = i ? frag->flags : first_sample_flags;
2267  unsigned sample_duration = frag->duration;
2268  int keyframe;
2269 
2270  if (flags & 0x100) sample_duration = avio_rb32(pb);
2271  if (flags & 0x200) sample_size = avio_rb32(pb);
2272  if (flags & 0x400) sample_flags = avio_rb32(pb);
2273  sc->ctts_data[sc->ctts_count].count = 1;
2274  sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2275  sc->ctts_count++;
2276  if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2277  (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2278  distance = 0;
2279  av_add_index_entry(st, offset, dts, sample_size, distance,
2280  keyframe ? AVINDEX_KEYFRAME : 0);
2281  av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2282  "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2283  offset, dts, sample_size, distance, keyframe);
2284  distance++;
2285  dts += sample_duration;
2286  offset += sample_size;
2287  }
2288  frag->moof_offset = offset;
2289  st->duration = dts + sc->time_offset;
2290  return 0;
2291 }
2292 
2293 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2294 /* like the files created with Adobe Premiere 5.0, for samples see */
2295 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2296 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2297 {
2298  int err;
2299 
2300  if (atom.size < 8)
2301  return 0; /* continue */
2302  if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2303  avio_skip(pb, atom.size - 4);
2304  return 0;
2305  }
2306  atom.type = avio_rl32(pb);
2307  atom.size -= 8;
2308  if (atom.type != MKTAG('m','d','a','t')) {
2309  avio_skip(pb, atom.size);
2310  return 0;
2311  }
2312  err = mov_read_mdat(c, pb, atom);
2313  return err;
2314 }
2315 
2316 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2317 {
2318 #if CONFIG_ZLIB
2319  AVIOContext ctx;
2320  uint8_t *cmov_data;
2321  uint8_t *moov_data; /* uncompressed data */
2322  long cmov_len, moov_len;
2323  int ret = -1;
2324 
2325  avio_rb32(pb); /* dcom atom */
2326  if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2327  return AVERROR_INVALIDDATA;
2328  if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2329  av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2330  return AVERROR_INVALIDDATA;
2331  }
2332  avio_rb32(pb); /* cmvd atom */
2333  if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2334  return AVERROR_INVALIDDATA;
2335  moov_len = avio_rb32(pb); /* uncompressed size */
2336  cmov_len = atom.size - 6 * 4;
2337 
2338  cmov_data = av_malloc(cmov_len);
2339  if (!cmov_data)
2340  return AVERROR(ENOMEM);
2341  moov_data = av_malloc(moov_len);
2342  if (!moov_data) {
2343  av_free(cmov_data);
2344  return AVERROR(ENOMEM);
2345  }
2346  avio_read(pb, cmov_data, cmov_len);
2347  if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2348  goto free_and_return;
2349  if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2350  goto free_and_return;
2351  atom.type = MKTAG('m','o','o','v');
2352  atom.size = moov_len;
2353  ret = mov_read_default(c, &ctx, atom);
2354 free_and_return:
2355  av_free(moov_data);
2356  av_free(cmov_data);
2357  return ret;
2358 #else
2359  av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2360  return AVERROR(ENOSYS);
2361 #endif
2362 }
2363 
2364 /* edit list atom */
2365 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2366 {
2367  MOVStreamContext *sc;
2368  int i, edit_count, version;
2369 
2370  if (c->fc->nb_streams < 1)
2371  return 0;
2372  sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2373 
2374  version = avio_r8(pb); /* version */
2375  avio_rb24(pb); /* flags */
2376  edit_count = avio_rb32(pb); /* entries */
2377 
2378  if ((uint64_t)edit_count*12+8 > atom.size)
2379  return AVERROR_INVALIDDATA;
2380 
2381  for (i=0; i<edit_count; i++){
2382  int64_t time;
2383  int64_t duration;
2384  if (version == 1) {
2385  duration = avio_rb64(pb);
2386  time = avio_rb64(pb);
2387  } else {
2388  duration = avio_rb32(pb); /* segment duration */
2389  time = (int32_t)avio_rb32(pb); /* media time */
2390  }
2391  avio_rb32(pb); /* Media rate */
2392  if (i == 0 && time >= -1) {
2393  sc->time_offset = time != -1 ? time : -duration;
2394  }
2395  }
2396 
2397  if (edit_count > 1)
2398  av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2399  "a/v desync might occur, patch welcome\n");
2400 
2401  av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2402  return 0;
2403 }
2404 
2405 static const MOVParseTableEntry mov_default_parse_table[] = {
2406 { MKTAG('a','v','s','s'), mov_read_extradata },
2407 { MKTAG('c','h','p','l'), mov_read_chpl },
2408 { MKTAG('c','o','6','4'), mov_read_stco },
2409 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2410 { MKTAG('d','i','n','f'), mov_read_default },
2411 { MKTAG('d','r','e','f'), mov_read_dref },
2412 { MKTAG('e','d','t','s'), mov_read_default },
2413 { MKTAG('e','l','s','t'), mov_read_elst },
2414 { MKTAG('e','n','d','a'), mov_read_enda },
2415 { MKTAG('f','i','e','l'), mov_read_fiel },
2416 { MKTAG('f','t','y','p'), mov_read_ftyp },
2417 { MKTAG('g','l','b','l'), mov_read_glbl },
2418 { MKTAG('h','d','l','r'), mov_read_hdlr },
2419 { MKTAG('i','l','s','t'), mov_read_ilst },
2420 { MKTAG('j','p','2','h'), mov_read_extradata },
2421 { MKTAG('m','d','a','t'), mov_read_mdat },
2422 { MKTAG('m','d','h','d'), mov_read_mdhd },
2423 { MKTAG('m','d','i','a'), mov_read_default },
2424 { MKTAG('m','e','t','a'), mov_read_meta },
2425 { MKTAG('m','i','n','f'), mov_read_default },
2426 { MKTAG('m','o','o','f'), mov_read_moof },
2427 { MKTAG('m','o','o','v'), mov_read_moov },
2428 { MKTAG('m','v','e','x'), mov_read_default },
2429 { MKTAG('m','v','h','d'), mov_read_mvhd },
2430 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2431 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2432 { MKTAG('a','v','c','C'), mov_read_glbl },
2433 { MKTAG('p','a','s','p'), mov_read_pasp },
2434 { MKTAG('s','t','b','l'), mov_read_default },
2435 { MKTAG('s','t','c','o'), mov_read_stco },
2436 { MKTAG('s','t','p','s'), mov_read_stps },
2437 { MKTAG('s','t','r','f'), mov_read_strf },
2438 { MKTAG('s','t','s','c'), mov_read_stsc },
2439 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2440 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2441 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2442 { MKTAG('s','t','t','s'), mov_read_stts },
2443 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2444 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2445 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2446 { MKTAG('t','r','a','k'), mov_read_trak },
2447 { MKTAG('t','r','a','f'), mov_read_default },
2448 { MKTAG('t','r','e','f'), mov_read_default },
2449 { MKTAG('c','h','a','p'), mov_read_chap },
2450 { MKTAG('t','r','e','x'), mov_read_trex },
2451 { MKTAG('t','r','u','n'), mov_read_trun },
2452 { MKTAG('u','d','t','a'), mov_read_default },
2453 { MKTAG('w','a','v','e'), mov_read_wave },
2454 { MKTAG('e','s','d','s'), mov_read_esds },
2455 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2456 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2457 { MKTAG('w','f','e','x'), mov_read_wfex },
2458 { MKTAG('c','m','o','v'), mov_read_cmov },
2459 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2460 { 0, NULL }
2461 };
2462 
2463 static int mov_probe(AVProbeData *p)
2464 {
2465  unsigned int offset;
2466  uint32_t tag;
2467  int score = 0;
2468 
2469  /* check file header */
2470  offset = 0;
2471  for (;;) {
2472  /* ignore invalid offset */
2473  if ((offset + 8) > (unsigned int)p->buf_size)
2474  return score;
2475  tag = AV_RL32(p->buf + offset + 4);
2476  switch(tag) {
2477  /* check for obvious tags */
2478  case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2479  case MKTAG('m','o','o','v'):
2480  case MKTAG('m','d','a','t'):
2481  case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2482  case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2483  case MKTAG('f','t','y','p'):
2484  return AVPROBE_SCORE_MAX;
2485  /* those are more common words, so rate then a bit less */
2486  case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2487  case MKTAG('w','i','d','e'):
2488  case MKTAG('f','r','e','e'):
2489  case MKTAG('j','u','n','k'):
2490  case MKTAG('p','i','c','t'):
2491  return AVPROBE_SCORE_MAX - 5;
2492  case MKTAG(0x82,0x82,0x7f,0x7d):
2493  case MKTAG('s','k','i','p'):
2494  case MKTAG('u','u','i','d'):
2495  case MKTAG('p','r','f','l'):
2496  offset = AV_RB32(p->buf+offset) + offset;
2497  /* if we only find those cause probedata is too small at least rate them */
2498  score = AVPROBE_SCORE_MAX - 50;
2499  break;
2500  default:
2501  /* unrecognized tag */
2502  return score;
2503  }
2504  }
2505 }
2506 
2507 // must be done after parsing all trak because there's no order requirement
2509 {
2510  MOVContext *mov = s->priv_data;
2511  AVStream *st = NULL;
2512  MOVStreamContext *sc;
2513  int64_t cur_pos;
2514  int i;
2515 
2516  for (i = 0; i < s->nb_streams; i++)
2517  if (s->streams[i]->id == mov->chapter_track) {
2518  st = s->streams[i];
2519  break;
2520  }
2521  if (!st) {
2522  av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2523  return;
2524  }
2525 
2526  st->discard = AVDISCARD_ALL;
2527  sc = st->priv_data;
2528  cur_pos = avio_tell(sc->pb);
2529 
2530  for (i = 0; i < st->nb_index_entries; i++) {
2531  AVIndexEntry *sample = &st->index_entries[i];
2532  int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2533  uint8_t *title;
2534  uint16_t ch;
2535  int len, title_len;
2536 
2537  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2538  av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2539  goto finish;
2540  }
2541 
2542  // the first two bytes are the length of the title
2543  len = avio_rb16(sc->pb);
2544  if (len > sample->size-2)
2545  continue;
2546  title_len = 2*len + 1;
2547  if (!(title = av_mallocz(title_len)))
2548  goto finish;
2549 
2550  // The samples could theoretically be in any encoding if there's an encd
2551  // atom following, but in practice are only utf-8 or utf-16, distinguished
2552  // instead by the presence of a BOM
2553  if (!len) {
2554  title[0] = 0;
2555  } else {
2556  ch = avio_rb16(sc->pb);
2557  if (ch == 0xfeff)
2558  avio_get_str16be(sc->pb, len, title, title_len);
2559  else if (ch == 0xfffe)
2560  avio_get_str16le(sc->pb, len, title, title_len);
2561  else {
2562  AV_WB16(title, ch);
2563  if (len == 1 || len == 2)
2564  title[len] = 0;
2565  else
2566  avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2567  }
2568  }
2569 
2570  avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2571  av_freep(&title);
2572  }
2573 finish:
2574  avio_seek(sc->pb, cur_pos, SEEK_SET);
2575 }
2576 
2578 {
2579  MOVContext *mov = s->priv_data;
2580  AVIOContext *pb = s->pb;
2581  int err;
2582  MOVAtom atom = { AV_RL32("root") };
2583 
2584  mov->fc = s;
2585  /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2586  if (pb->seekable)
2587  atom.size = avio_size(pb);
2588  else
2589  atom.size = INT64_MAX;
2590 
2591  /* check MOV header */
2592  if ((err = mov_read_default(mov, pb, atom)) < 0) {
2593  av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2594  return err;
2595  }
2596  if (!mov->found_moov) {
2597  av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2598  return AVERROR_INVALIDDATA;
2599  }
2600  av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2601 
2602  if (pb->seekable && mov->chapter_track > 0)
2603  mov_read_chapters(s);
2604 
2605  return 0;
2606 }
2607 
2609 {
2610  AVIndexEntry *sample = NULL;
2611  int64_t best_dts = INT64_MAX;
2612  int i;
2613  for (i = 0; i < s->nb_streams; i++) {
2614  AVStream *avst = s->streams[i];
2615  MOVStreamContext *msc = avst->priv_data;
2616  if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2617  AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2618  int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2619  av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2620  if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2621  (s->pb->seekable &&
2622  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2623  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2624  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2625  sample = current_sample;
2626  best_dts = dts;
2627  *st = avst;
2628  }
2629  }
2630  }
2631  return sample;
2632 }
2633 
2635 {
2636  MOVContext *mov = s->priv_data;
2637  MOVStreamContext *sc;
2638  AVIndexEntry *sample;
2639  AVStream *st = NULL;
2640  int ret;
2641  retry:
2642  sample = mov_find_next_sample(s, &st);
2643  if (!sample) {
2644  mov->found_mdat = 0;
2645  if (s->pb->seekable||
2646  mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2647  s->pb->eof_reached)
2648  return AVERROR_EOF;
2649  av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2650  goto retry;
2651  }
2652  sc = st->priv_data;
2653  /* must be done just before reading, to avoid infinite loop on sample */
2654  sc->current_sample++;
2655 
2656  if (st->discard != AVDISCARD_ALL) {
2657  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2658  av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2659  sc->ffindex, sample->pos);
2660  return AVERROR_INVALIDDATA;
2661  }
2662  ret = av_get_packet(sc->pb, pkt, sample->size);
2663  if (ret < 0)
2664  return ret;
2665  if (sc->has_palette) {
2666  uint8_t *pal;
2667 
2669  if (!pal) {
2670  av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2671  } else {
2672  memcpy(pal, sc->palette, AVPALETTE_SIZE);
2673  sc->has_palette = 0;
2674  }
2675  }
2676 #if CONFIG_DV_DEMUXER
2677  if (mov->dv_demux && sc->dv_audio_container) {
2678  avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2679  av_free(pkt->data);
2680  pkt->size = 0;
2681  ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2682  if (ret < 0)
2683  return ret;
2684  }
2685 #endif
2686  }
2687 
2688  pkt->stream_index = sc->ffindex;
2689  pkt->dts = sample->timestamp;
2690  if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2691  pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2692  /* update ctts context */
2693  sc->ctts_sample++;
2694  if (sc->ctts_index < sc->ctts_count &&
2695  sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2696  sc->ctts_index++;
2697  sc->ctts_sample = 0;
2698  }
2699  if (sc->wrong_dts)
2700  pkt->dts = AV_NOPTS_VALUE;
2701  } else {
2702  int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2704  pkt->duration = next_dts - pkt->dts;
2705  pkt->pts = pkt->dts;
2706  }
2707  if (st->discard == AVDISCARD_ALL)
2708  goto retry;
2709  pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2710  pkt->pos = sample->pos;
2711  av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2712  pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2713  return 0;
2714 }
2715 
2716 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2717 {
2718  MOVStreamContext *sc = st->priv_data;
2719  int sample, time_sample;
2720  int i;
2721 
2722  sample = av_index_search_timestamp(st, timestamp, flags);
2723  av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2724  if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2725  sample = 0;
2726  if (sample < 0) /* not sure what to do */
2727  return AVERROR_INVALIDDATA;
2728  sc->current_sample = sample;
2729  av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2730  /* adjust ctts index */
2731  if (sc->ctts_data) {
2732  time_sample = 0;
2733  for (i = 0; i < sc->ctts_count; i++) {
2734  int next = time_sample + sc->ctts_data[i].count;
2735  if (next > sc->current_sample) {
2736  sc->ctts_index = i;
2737  sc->ctts_sample = sc->current_sample - time_sample;
2738  break;
2739  }
2740  time_sample = next;
2741  }
2742  }
2743  return sample;
2744 }
2745 
2746 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2747 {
2748  AVStream *st;
2749  int64_t seek_timestamp, timestamp;
2750  int sample;
2751  int i;
2752 
2753  if (stream_index >= s->nb_streams)
2754  return AVERROR_INVALIDDATA;
2755  if (sample_time < 0)
2756  sample_time = 0;
2757 
2758  st = s->streams[stream_index];
2759  sample = mov_seek_stream(s, st, sample_time, flags);
2760  if (sample < 0)
2761  return sample;
2762 
2763  /* adjust seek timestamp to found sample timestamp */
2764  seek_timestamp = st->index_entries[sample].timestamp;
2765 
2766  for (i = 0; i < s->nb_streams; i++) {
2767  st = s->streams[i];
2768  if (stream_index == i)
2769  continue;
2770 
2771  timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2772  mov_seek_stream(s, st, timestamp, flags);
2773  }
2774  return 0;
2775 }
2776 
2778 {
2779  MOVContext *mov = s->priv_data;
2780  int i, j;
2781 
2782  for (i = 0; i < s->nb_streams; i++) {
2783  AVStream *st = s->streams[i];
2784  MOVStreamContext *sc = st->priv_data;
2785 
2786  av_freep(&sc->ctts_data);
2787  for (j = 0; j < sc->drefs_count; j++) {
2788  av_freep(&sc->drefs[j].path);
2789  av_freep(&sc->drefs[j].dir);
2790  }
2791  av_freep(&sc->drefs);
2792  if (sc->pb && sc->pb != s->pb)
2793  avio_close(sc->pb);
2794  }
2795 
2796  if (mov->dv_demux) {
2797  for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2798  av_freep(&mov->dv_fctx->streams[i]->codec);
2799  av_freep(&mov->dv_fctx->streams[i]);
2800  }
2801  av_freep(&mov->dv_fctx);
2802  av_freep(&mov->dv_demux);
2803  }
2804 
2805  av_freep(&mov->trex_data);
2806 
2807  return 0;
2808 }
2809 
2811  .name = "mov,mp4,m4a,3gp,3g2,mj2",
2812  .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2813  .priv_data_size = sizeof(MOVContext),
2814  .read_probe = mov_probe,
2819 };