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