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