FFmpeg  1.2.12
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 FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/attributes.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/timecode.h"
37 #include "libavcodec/ac3tab.h"
38 #include "avformat.h"
39 #include "internal.h"
40 #include "avio_internal.h"
41 #include "riff.h"
42 #include "isom.h"
43 #include "libavcodec/get_bits.h"
44 #include "id3v1.h"
45 #include "mov_chan.h"
46 
47 #if CONFIG_ZLIB
48 #include <zlib.h>
49 #endif
50 
51 /*
52  * First version by Francois Revol revol@free.fr
53  * Seek function by Gael Chardon gael.dev@4now.net
54  */
55 
56 #include "qtpalette.h"
57 
58 
59 #undef NDEBUG
60 #include <assert.h>
61 
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
65  uint32_t type;
66  int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 
72  unsigned len, const char *key)
73 {
74  char buf[16];
75 
76  short current, total = 0;
77  avio_rb16(pb); // unknown
78  current = avio_rb16(pb);
79  if (len >= 6)
80  total = avio_rb16(pb);
81  if (!total)
82  snprintf(buf, sizeof(buf), "%d", current);
83  else
84  snprintf(buf, sizeof(buf), "%d/%d", current, total);
85  av_dict_set(&c->fc->metadata, key, buf, 0);
86 
87  return 0;
88 }
89 
91  unsigned len, const char *key)
92 {
93  char buf[16];
94 
95  /* bypass padding bytes */
96  avio_r8(pb);
97  avio_r8(pb);
98  avio_r8(pb);
99 
100  snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
101  av_dict_set(&c->fc->metadata, key, buf, 0);
102 
103  return 0;
104 }
105 
107  unsigned len, const char *key)
108 {
109  char buf[16];
110 
111  snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
112  av_dict_set(&c->fc->metadata, key, buf, 0);
113 
114  return 0;
115 }
116 
118  unsigned len, const char *key)
119 {
120  short genre;
121  char buf[20];
122 
123  avio_r8(pb); // unknown
124 
125  genre = avio_r8(pb);
126  if (genre < 1 || genre > ID3v1_GENRE_MAX)
127  return 0;
128  snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
129  av_dict_set(&c->fc->metadata, key, buf, 0);
130 
131  return 0;
132 }
133 
135 {
136  char key[1024]={0}, data[1024]={0};
137  int i;
138  AVStream *st;
139  MOVStreamContext *sc;
140 
141  if (c->fc->nb_streams < 1)
142  return 0;
143  st = c->fc->streams[c->fc->nb_streams-1];
144  sc = st->priv_data;
145 
146  if (atom.size <= 8) return 0;
147 
148  for (i = 0; i < 3; i++) { // Parse up to three sub-atoms looking for name and data.
149  int data_size = avio_rb32(pb);
150  int tag = avio_rl32(pb);
151  int str_size = 0, skip_size = 0;
152  char *target = NULL;
153 
154  switch (tag) {
155  case MKTAG('n','a','m','e'):
156  avio_rb32(pb); // version/flags
157  str_size = skip_size = data_size - 12;
158  atom.size -= 12;
159  target = key;
160  break;
161  case MKTAG('d','a','t','a'):
162  avio_rb32(pb); // version/flags
163  avio_rb32(pb); // reserved (zero)
164  str_size = skip_size = data_size - 16;
165  atom.size -= 16;
166  target = data;
167  break;
168  default:
169  skip_size = data_size - 8;
170  str_size = 0;
171  break;
172  }
173 
174  if (target) {
175  str_size = FFMIN3(sizeof(data)-1, str_size, atom.size);
176  avio_read(pb, target, str_size);
177  target[str_size] = 0;
178  }
179  atom.size -= skip_size;
180 
181  // If we didn't read the full data chunk for the sub-atom, skip to the end of it.
182  if (skip_size > str_size) avio_skip(pb, skip_size - str_size);
183  }
184 
185  if (*key && *data) {
186  if (strcmp(key, "iTunSMPB") == 0) {
187  int priming, remainder, samples;
188  if(sscanf(data, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
189  if(priming>0 && priming<16384)
190  sc->start_pad = priming;
191  return 1;
192  }
193  }
194  if (strcmp(key, "cdec") == 0) {
195 // av_dict_set(&st->metadata, key, data, 0);
196  return 1;
197  }
198  }
199  return 0;
200 }
201 
202 static const uint32_t mac_to_unicode[128] = {
203  0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
204  0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
205  0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
206  0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
207  0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
208  0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
209  0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
210  0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
211  0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
212  0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
213  0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
214  0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
215  0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
216  0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
217  0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
218  0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
219 };
220 
222  char *dst, int dstlen)
223 {
224  char *p = dst;
225  char *end = dst+dstlen-1;
226  int i;
227 
228  for (i = 0; i < len; i++) {
229  uint8_t t, c = avio_r8(pb);
230  if (c < 0x80 && p < end)
231  *p++ = c;
232  else if (p < end)
233  PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
234  }
235  *p = 0;
236  return p - dst;
237 }
238 
239 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
240 {
241  AVPacket pkt;
242  AVStream *st;
243  MOVStreamContext *sc;
244  enum AVCodecID id;
245  int ret;
246 
247  switch (type) {
248  case 0xd: id = AV_CODEC_ID_MJPEG; break;
249  case 0xe: id = AV_CODEC_ID_PNG; break;
250  case 0x1b: id = AV_CODEC_ID_BMP; break;
251  default:
252  av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
253  avio_skip(pb, len);
254  return 0;
255  }
256 
257  st = avformat_new_stream(c->fc, NULL);
258  if (!st)
259  return AVERROR(ENOMEM);
260  sc = av_mallocz(sizeof(*sc));
261  if (!sc)
262  return AVERROR(ENOMEM);
263  st->priv_data = sc;
264 
265  ret = av_get_packet(pb, &pkt, len);
266  if (ret < 0)
267  return ret;
268 
270 
271  st->attached_pic = pkt;
272  st->attached_pic.stream_index = st->index;
274 
276  st->codec->codec_id = id;
277 
278  return 0;
279 }
280 
282  unsigned len, const char *key)
283 {
284  char *value;
285  // Check for overflow.
286  if (len >= INT_MAX)
287  return AVERROR(EINVAL);
288  value = av_malloc(len + 1);
289  if (!value)
290  return AVERROR(ENOMEM);
291  avio_read(pb, value, len);
292  value[len] = 0;
293  return av_dict_set(&c->fc->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);
294 }
295 
297 {
298 #ifdef MOV_EXPORT_ALL_METADATA
299  char tmp_key[5];
300 #endif
301  char str[1024], key2[16], language[4] = {0};
302  const char *key = NULL;
303  uint16_t langcode = 0;
304  uint32_t data_type = 0, str_size;
305  int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
306 
307  if (c->itunes_metadata && atom.type == MKTAG('-','-','-','-'))
308  return mov_read_custom_metadata(c, pb, atom);
309 
310  switch (atom.type) {
311  case MKTAG(0xa9,'n','a','m'): key = "title"; break;
312  case MKTAG(0xa9,'a','u','t'):
313  case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
314  case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
315  case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
316  case MKTAG( 'c','p','r','t'):
317  case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
318  case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
319  case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
320  case MKTAG(0xa9,'c','m','t'):
321  case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
322  case MKTAG(0xa9,'a','l','b'): key = "album"; break;
323  case MKTAG(0xa9,'d','a','y'): key = "date"; break;
324  case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
325  case MKTAG( 'g','n','r','e'): key = "genre";
326  parse = mov_metadata_gnre; break;
327  case MKTAG(0xa9,'t','o','o'):
328  case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
329  case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
330  case MKTAG(0xa9,'m','a','k'): key = "make"; break;
331  case MKTAG(0xa9,'m','o','d'): key = "model"; break;
332  case MKTAG(0xa9,'x','y','z'): key = "location"; break;
333  case MKTAG( 'd','e','s','c'): key = "description";break;
334  case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
335  case MKTAG( 't','v','s','h'): key = "show"; break;
336  case MKTAG( 't','v','e','n'): key = "episode_id";break;
337  case MKTAG( 't','v','n','n'): key = "network"; break;
338  case MKTAG( 't','r','k','n'): key = "track";
340  case MKTAG( 'd','i','s','k'): key = "disc";
342  case MKTAG( 't','v','e','s'): key = "episode_sort";
344  case MKTAG( 't','v','s','n'): key = "season_number";
346  case MKTAG( 's','t','i','k'): key = "media_type";
348  case MKTAG( 'h','d','v','d'): key = "hd_video";
350  case MKTAG( 'p','g','a','p'): key = "gapless_playback";
352  case MKTAG( '@','P','R','M'):
353  return mov_metadata_raw(c, pb, atom.size, "premiere_version");
354  case MKTAG( '@','P','R','Q'):
355  return mov_metadata_raw(c, pb, atom.size, "quicktime_version");
356  }
357 
358  if (c->itunes_metadata && atom.size > 8) {
359  int data_size = avio_rb32(pb);
360  int tag = avio_rl32(pb);
361  if (tag == MKTAG('d','a','t','a')) {
362  data_type = avio_rb32(pb); // type
363  avio_rb32(pb); // unknown
364  str_size = data_size - 16;
365  atom.size -= 16;
366 
367  if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
368  int ret = mov_read_covr(c, pb, data_type, str_size);
369  if (ret < 0) {
370  av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
371  return ret;
372  }
373  }
374  } else return 0;
375  } else if (atom.size > 4 && key && !c->itunes_metadata) {
376  str_size = avio_rb16(pb); // string length
377  langcode = avio_rb16(pb);
378  ff_mov_lang_to_iso639(langcode, language);
379  atom.size -= 4;
380  } else
381  str_size = atom.size;
382 
383 #ifdef MOV_EXPORT_ALL_METADATA
384  if (!key) {
385  snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
386  key = tmp_key;
387  }
388 #endif
389 
390  if (!key)
391  return 0;
392  if (atom.size < 0 || str_size >= INT_MAX/2)
393  return AVERROR_INVALIDDATA;
394 
395  str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
396 
397  if (parse)
398  parse(c, pb, str_size, key);
399  else {
400  if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
401  mov_read_mac_string(c, pb, str_size, str, sizeof(str));
402  } else {
403  avio_read(pb, str, str_size);
404  str[str_size] = 0;
405  }
406  av_dict_set(&c->fc->metadata, key, str, 0);
407  if (*language && strcmp(language, "und")) {
408  snprintf(key2, sizeof(key2), "%s-%s", key, language);
409  av_dict_set(&c->fc->metadata, key2, str, 0);
410  }
411  }
412  av_dlog(c->fc, "lang \"%3s\" ", language);
413  av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
414  key, str, (char*)&atom.type, str_size, atom.size);
415 
416  return 0;
417 }
418 
420 {
421  int64_t start;
422  int i, nb_chapters, str_len, version;
423  char str[256+1];
424 
425  if ((atom.size -= 5) < 0)
426  return 0;
427 
428  version = avio_r8(pb);
429  avio_rb24(pb);
430  if (version)
431  avio_rb32(pb); // ???
432  nb_chapters = avio_r8(pb);
433 
434  for (i = 0; i < nb_chapters; i++) {
435  if (atom.size < 9)
436  return 0;
437 
438  start = avio_rb64(pb);
439  str_len = avio_r8(pb);
440 
441  if ((atom.size -= 9+str_len) < 0)
442  return 0;
443 
444  avio_read(pb, str, str_len);
445  str[str_len] = 0;
446  avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
447  }
448  return 0;
449 }
450 
451 #define MIN_DATA_ENTRY_BOX_SIZE 12
453 {
454  AVStream *st;
455  MOVStreamContext *sc;
456  int entries, i, j;
457 
458  if (c->fc->nb_streams < 1)
459  return 0;
460  st = c->fc->streams[c->fc->nb_streams-1];
461  sc = st->priv_data;
462 
463  avio_rb32(pb); // version + flags
464  entries = avio_rb32(pb);
465  if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
466  entries >= UINT_MAX / sizeof(*sc->drefs))
467  return AVERROR_INVALIDDATA;
468  av_free(sc->drefs);
469  sc->drefs_count = 0;
470  sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
471  if (!sc->drefs)
472  return AVERROR(ENOMEM);
473  sc->drefs_count = entries;
474 
475  for (i = 0; i < sc->drefs_count; i++) {
476  MOVDref *dref = &sc->drefs[i];
477  uint32_t size = avio_rb32(pb);
478  int64_t next = avio_tell(pb) + size - 4;
479 
480  if (size < 12)
481  return AVERROR_INVALIDDATA;
482 
483  dref->type = avio_rl32(pb);
484  avio_rb32(pb); // version + flags
485  av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
486 
487  if (dref->type == MKTAG('a','l','i','s') && size > 150) {
488  /* macintosh alias record */
489  uint16_t volume_len, len;
490  int16_t type;
491 
492  avio_skip(pb, 10);
493 
494  volume_len = avio_r8(pb);
495  volume_len = FFMIN(volume_len, 27);
496  avio_read(pb, dref->volume, 27);
497  dref->volume[volume_len] = 0;
498  av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
499 
500  avio_skip(pb, 12);
501 
502  len = avio_r8(pb);
503  len = FFMIN(len, 63);
504  avio_read(pb, dref->filename, 63);
505  dref->filename[len] = 0;
506  av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
507 
508  avio_skip(pb, 16);
509 
510  /* read next level up_from_alias/down_to_target */
511  dref->nlvl_from = avio_rb16(pb);
512  dref->nlvl_to = avio_rb16(pb);
513  av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
514  dref->nlvl_from, dref->nlvl_to);
515 
516  avio_skip(pb, 16);
517 
518  for (type = 0; type != -1 && avio_tell(pb) < next; ) {
519  if(url_feof(pb))
520  return AVERROR_EOF;
521  type = avio_rb16(pb);
522  len = avio_rb16(pb);
523  av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
524  if (len&1)
525  len += 1;
526  if (type == 2) { // absolute path
527  av_free(dref->path);
528  dref->path = av_mallocz(len+1);
529  if (!dref->path)
530  return AVERROR(ENOMEM);
531  avio_read(pb, dref->path, len);
532  if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
533  len -= volume_len;
534  memmove(dref->path, dref->path+volume_len, len);
535  dref->path[len] = 0;
536  }
537  for (j = 0; j < len; j++)
538  if (dref->path[j] == ':')
539  dref->path[j] = '/';
540  av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
541  } else if (type == 0) { // directory name
542  av_free(dref->dir);
543  dref->dir = av_malloc(len+1);
544  if (!dref->dir)
545  return AVERROR(ENOMEM);
546  avio_read(pb, dref->dir, len);
547  dref->dir[len] = 0;
548  for (j = 0; j < len; j++)
549  if (dref->dir[j] == ':')
550  dref->dir[j] = '/';
551  av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
552  } else
553  avio_skip(pb, len);
554  }
555  }
556  avio_seek(pb, next, SEEK_SET);
557  }
558  return 0;
559 }
560 
562 {
563  AVStream *st;
564  uint32_t type;
565  uint32_t av_unused ctype;
566  int title_size;
567  char *title_str;
568 
569  if (c->fc->nb_streams < 1) // meta before first trak
570  return 0;
571 
572  st = c->fc->streams[c->fc->nb_streams-1];
573 
574  avio_r8(pb); /* version */
575  avio_rb24(pb); /* flags */
576 
577  /* component type */
578  ctype = avio_rl32(pb);
579  type = avio_rl32(pb); /* component subtype */
580 
581  av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
582  av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
583 
584  if (type == MKTAG('v','i','d','e'))
586  else if (type == MKTAG('s','o','u','n'))
588  else if (type == MKTAG('m','1','a',' '))
590  else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
592 
593  avio_rb32(pb); /* component manufacture */
594  avio_rb32(pb); /* component flags */
595  avio_rb32(pb); /* component flags mask */
596 
597  title_size = atom.size - 24;
598  if (title_size > 0) {
599  title_str = av_malloc(title_size + 1); /* Add null terminator */
600  if (!title_str)
601  return AVERROR(ENOMEM);
602  avio_read(pb, title_str, title_size);
603  title_str[title_size] = 0;
604  if (title_str[0])
605  av_dict_set(&st->metadata, "handler_name", title_str +
606  (!c->isom && title_str[0] == title_size - 1), 0);
607  av_freep(&title_str);
608  }
609 
610  return 0;
611 }
612 
614 {
615  AVStream *st;
616  int tag;
617 
618  if (fc->nb_streams < 1)
619  return 0;
620  st = fc->streams[fc->nb_streams-1];
621 
622  avio_rb32(pb); /* version + flags */
623  ff_mp4_read_descr(fc, pb, &tag);
624  if (tag == MP4ESDescrTag) {
626  } else
627  avio_rb16(pb); /* ID */
628 
629  ff_mp4_read_descr(fc, pb, &tag);
630  if (tag == MP4DecConfigDescrTag)
631  ff_mp4_read_dec_config_descr(fc, st, pb);
632  return 0;
633 }
634 
636 {
637  return ff_mov_read_esds(c->fc, pb, atom);
638 }
639 
641 {
642  AVStream *st;
643  int ac3info, acmod, lfeon, bsmod;
644 
645  if (c->fc->nb_streams < 1)
646  return 0;
647  st = c->fc->streams[c->fc->nb_streams-1];
648 
649  ac3info = avio_rb24(pb);
650  bsmod = (ac3info >> 14) & 0x7;
651  acmod = (ac3info >> 11) & 0x7;
652  lfeon = (ac3info >> 10) & 0x1;
653  st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
655  if (lfeon)
657  st->codec->audio_service_type = bsmod;
658  if (st->codec->channels > 1 && bsmod == 0x7)
660 
661  return 0;
662 }
663 
665 {
666  AVStream *st;
667  int eac3info, acmod, lfeon, bsmod;
668 
669  if (c->fc->nb_streams < 1)
670  return 0;
671  st = c->fc->streams[c->fc->nb_streams-1];
672 
673  /* No need to parse fields for additional independent substreams and its
674  * associated dependent substreams since libavcodec's E-AC-3 decoder
675  * does not support them yet. */
676  avio_rb16(pb); /* data_rate and num_ind_sub */
677  eac3info = avio_rb24(pb);
678  bsmod = (eac3info >> 12) & 0x1f;
679  acmod = (eac3info >> 9) & 0x7;
680  lfeon = (eac3info >> 8) & 0x1;
682  if (lfeon)
685  st->codec->audio_service_type = bsmod;
686  if (st->codec->channels > 1 && bsmod == 0x7)
688 
689  return 0;
690 }
691 
693 {
694  AVStream *st;
695 
696  if (c->fc->nb_streams < 1)
697  return 0;
698  st = c->fc->streams[c->fc->nb_streams-1];
699 
700  if (atom.size < 16)
701  return 0;
702 
703  /* skip version and flags */
704  avio_skip(pb, 4);
705 
706  ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
707 
708  return 0;
709 }
710 
712 {
713  AVStream *st;
714 
715  if (c->fc->nb_streams < 1)
716  return 0;
717  st = c->fc->streams[c->fc->nb_streams-1];
718 
719  if (ff_get_wav_header(pb, st->codec, atom.size) < 0) {
720  av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
721  }
722 
723  return 0;
724 }
725 
727 {
728  const int num = avio_rb32(pb);
729  const int den = avio_rb32(pb);
730  AVStream *st;
731 
732  if (c->fc->nb_streams < 1)
733  return 0;
734  st = c->fc->streams[c->fc->nb_streams-1];
735 
736  if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
737  (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
739  "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
741  num, den);
742  } else if (den != 0) {
743  st->sample_aspect_ratio.num = num;
744  st->sample_aspect_ratio.den = den;
745  }
746  return 0;
747 }
748 
749 /* this atom contains actual media data */
751 {
752  if (atom.size == 0) /* wrong one (MP4) */
753  return 0;
754  c->found_mdat=1;
755  return 0; /* now go for moov */
756 }
757 
758 /* read major brand, minor version and compatible brands and store them as metadata */
760 {
761  uint32_t minor_ver;
762  int comp_brand_size;
763  char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
764  char* comp_brands_str;
765  uint8_t type[5] = {0};
766 
767  avio_read(pb, type, 4);
768  if (strcmp(type, "qt "))
769  c->isom = 1;
770  av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
771  av_dict_set(&c->fc->metadata, "major_brand", type, 0);
772  minor_ver = avio_rb32(pb); /* minor version */
773  snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
774  av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
775 
776  comp_brand_size = atom.size - 8;
777  if (comp_brand_size < 0)
778  return AVERROR_INVALIDDATA;
779  comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
780  if (!comp_brands_str)
781  return AVERROR(ENOMEM);
782  avio_read(pb, comp_brands_str, comp_brand_size);
783  comp_brands_str[comp_brand_size] = 0;
784  av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
785  av_freep(&comp_brands_str);
786 
787  return 0;
788 }
789 
790 /* this atom should contain all header atoms */
792 {
793  int ret;
794 
795  if ((ret = mov_read_default(c, pb, atom)) < 0)
796  return ret;
797  /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
798  /* so we don't parse the whole file if over a network */
799  c->found_moov=1;
800  return 0; /* now go for mdat */
801 }
802 
804 {
805  c->fragment.moof_offset = avio_tell(pb) - 8;
806  av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
807  return mov_read_default(c, pb, atom);
808 }
809 
810 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
811 {
812  char buffer[32];
813  if (time) {
814  struct tm *ptm;
815  time_t timet;
816  if(time >= 2082844800)
817  time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
818  timet = time;
819  ptm = gmtime(&timet);
820  if (!ptm) return;
821  strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
822  av_dict_set(metadata, "creation_time", buffer, 0);
823  }
824 }
825 
827 {
828  AVStream *st;
829  MOVStreamContext *sc;
830  int version;
831  char language[4] = {0};
832  unsigned lang;
833  int64_t creation_time;
834 
835  if (c->fc->nb_streams < 1)
836  return 0;
837  st = c->fc->streams[c->fc->nb_streams-1];
838  sc = st->priv_data;
839 
840  version = avio_r8(pb);
841  if (version > 1) {
842  av_log_ask_for_sample(c->fc, "unsupported version %d\n", version);
843  return AVERROR_PATCHWELCOME;
844  }
845  avio_rb24(pb); /* flags */
846  if (version == 1) {
847  creation_time = avio_rb64(pb);
848  avio_rb64(pb);
849  } else {
850  creation_time = avio_rb32(pb);
851  avio_rb32(pb); /* modification time */
852  }
853  mov_metadata_creation_time(&st->metadata, creation_time);
854 
855  sc->time_scale = avio_rb32(pb);
856  st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
857 
858  lang = avio_rb16(pb); /* language */
859  if (ff_mov_lang_to_iso639(lang, language))
860  av_dict_set(&st->metadata, "language", language, 0);
861  avio_rb16(pb); /* quality */
862 
863  return 0;
864 }
865 
867 {
868  int64_t creation_time;
869  int version = avio_r8(pb); /* version */
870  avio_rb24(pb); /* flags */
871 
872  if (version == 1) {
873  creation_time = avio_rb64(pb);
874  avio_rb64(pb);
875  } else {
876  creation_time = avio_rb32(pb);
877  avio_rb32(pb); /* modification time */
878  }
879  mov_metadata_creation_time(&c->fc->metadata, creation_time);
880  c->time_scale = avio_rb32(pb); /* time scale */
881 
882  av_dlog(c->fc, "time scale = %i\n", c->time_scale);
883 
884  c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
885  // set the AVCodecContext duration because the duration of individual tracks
886  // may be inaccurate
887  if (c->time_scale > 0 && !c->trex_data)
889  avio_rb32(pb); /* preferred scale */
890 
891  avio_rb16(pb); /* preferred volume */
892 
893  avio_skip(pb, 10); /* reserved */
894 
895  avio_skip(pb, 36); /* display matrix */
896 
897  avio_rb32(pb); /* preview time */
898  avio_rb32(pb); /* preview duration */
899  avio_rb32(pb); /* poster time */
900  avio_rb32(pb); /* selection time */
901  avio_rb32(pb); /* selection duration */
902  avio_rb32(pb); /* current time */
903  avio_rb32(pb); /* next track ID */
904  return 0;
905 }
906 
908 {
909  AVStream *st;
910  int little_endian;
911 
912  if (c->fc->nb_streams < 1)
913  return 0;
914  st = c->fc->streams[c->fc->nb_streams-1];
915 
916  little_endian = avio_rb16(pb) & 0xFF;
917  av_dlog(c->fc, "enda %d\n", little_endian);
918  if (little_endian == 1) {
919  switch (st->codec->codec_id) {
922  break;
925  break;
928  break;
931  break;
932  default:
933  break;
934  }
935  }
936  return 0;
937 }
938 
940 {
941  AVStream *st;
942  unsigned mov_field_order;
943  enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
944 
945  if (c->fc->nb_streams < 1) // will happen with jp2 files
946  return 0;
947  st = c->fc->streams[c->fc->nb_streams-1];
948  if (atom.size < 2)
949  return AVERROR_INVALIDDATA;
950  mov_field_order = avio_rb16(pb);
951  if ((mov_field_order & 0xFF00) == 0x0100)
952  decoded_field_order = AV_FIELD_PROGRESSIVE;
953  else if ((mov_field_order & 0xFF00) == 0x0200) {
954  switch (mov_field_order & 0xFF) {
955  case 0x01: decoded_field_order = AV_FIELD_TT;
956  break;
957  case 0x06: decoded_field_order = AV_FIELD_BB;
958  break;
959  case 0x09: decoded_field_order = AV_FIELD_TB;
960  break;
961  case 0x0E: decoded_field_order = AV_FIELD_BT;
962  break;
963  }
964  }
965  if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
966  av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
967  }
968  st->codec->field_order = decoded_field_order;
969 
970  return 0;
971 }
972 
973 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
975  enum AVCodecID codec_id)
976 {
977  AVStream *st;
978  uint64_t size;
979  uint8_t *buf;
980 
981  if (c->fc->nb_streams < 1) // will happen with jp2 files
982  return 0;
983  st= c->fc->streams[c->fc->nb_streams-1];
984 
985  if (st->codec->codec_id != codec_id)
986  return 0; /* unexpected codec_id - don't mess with extradata */
987 
988  size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
989  if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
990  return AVERROR_INVALIDDATA;
991  buf= av_realloc(st->codec->extradata, size);
992  if (!buf)
993  return AVERROR(ENOMEM);
994  st->codec->extradata= buf;
995  buf+= st->codec->extradata_size;
997  AV_WB32( buf , atom.size + 8);
998  AV_WL32( buf + 4, atom.type);
999  avio_read(pb, buf + 8, atom.size);
1000  return 0;
1001 }
1002 
1003 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1005 {
1006  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1007 }
1008 
1010 {
1011  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1012 }
1013 
1015 {
1016  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1017 }
1018 
1020 {
1021  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1022 }
1023 
1025 {
1026  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1027 }
1028 
1030 {
1031  AVStream *st;
1032 
1033  if (c->fc->nb_streams < 1)
1034  return 0;
1035  st = c->fc->streams[c->fc->nb_streams-1];
1036 
1037  if ((uint64_t)atom.size > (1<<30))
1038  return AVERROR_INVALIDDATA;
1039 
1040  if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
1041  // pass all frma atom to codec, needed at least for QDMC and QDM2
1042  av_free(st->codec->extradata);
1043  st->codec->extradata_size = 0;
1045  if (!st->codec->extradata)
1046  return AVERROR(ENOMEM);
1047  st->codec->extradata_size = atom.size;
1048  avio_read(pb, st->codec->extradata, atom.size);
1049  } else if (atom.size > 8) { /* to read frma, esds atoms */
1050  int ret;
1051  if ((ret = mov_read_default(c, pb, atom)) < 0)
1052  return ret;
1053  } else
1054  avio_skip(pb, atom.size);
1055  return 0;
1056 }
1057 
1063 {
1064  AVStream *st;
1065 
1066  if (c->fc->nb_streams < 1)
1067  return 0;
1068  st = c->fc->streams[c->fc->nb_streams-1];
1069 
1070  if ((uint64_t)atom.size > (1<<30))
1071  return AVERROR_INVALIDDATA;
1072 
1073  if (atom.size >= 10) {
1074  // Broken files created by legacy versions of libavformat will
1075  // wrap a whole fiel atom inside of a glbl atom.
1076  unsigned size = avio_rb32(pb);
1077  unsigned type = avio_rl32(pb);
1078  avio_seek(pb, -8, SEEK_CUR);
1079  if (type == MKTAG('f','i','e','l') && size == atom.size)
1080  return mov_read_default(c, pb, atom);
1081  }
1082  av_free(st->codec->extradata);
1083  st->codec->extradata_size = 0;
1085  if (!st->codec->extradata)
1086  return AVERROR(ENOMEM);
1087  st->codec->extradata_size = atom.size;
1088  avio_read(pb, st->codec->extradata, atom.size);
1089  return 0;
1090 }
1091 
1093 {
1094  AVStream *st;
1095  uint8_t profile_level;
1096 
1097  if (c->fc->nb_streams < 1)
1098  return 0;
1099  st = c->fc->streams[c->fc->nb_streams-1];
1100 
1101  if (atom.size >= (1<<28) || atom.size < 7)
1102  return AVERROR_INVALIDDATA;
1103 
1104  profile_level = avio_r8(pb);
1105  if ((profile_level & 0xf0) != 0xc0)
1106  return 0;
1107 
1108  av_free(st->codec->extradata);
1109  st->codec->extradata_size = 0;
1111  if (!st->codec->extradata)
1112  return AVERROR(ENOMEM);
1113  st->codec->extradata_size = atom.size - 7;
1114  avio_seek(pb, 6, SEEK_CUR);
1115  avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1116  return 0;
1117 }
1118 
1125 {
1126  AVStream *st;
1127 
1128  if (c->fc->nb_streams < 1)
1129  return 0;
1130  if (atom.size <= 40)
1131  return 0;
1132  st = c->fc->streams[c->fc->nb_streams-1];
1133 
1134  if ((uint64_t)atom.size > (1<<30))
1135  return AVERROR_INVALIDDATA;
1136 
1137  av_free(st->codec->extradata);
1138  st->codec->extradata_size = 0;
1140  if (!st->codec->extradata)
1141  return AVERROR(ENOMEM);
1142  st->codec->extradata_size = atom.size - 40;
1143  avio_skip(pb, 40);
1144  avio_read(pb, st->codec->extradata, atom.size - 40);
1145  return 0;
1146 }
1147 
1149 {
1150  AVStream *st;
1151  MOVStreamContext *sc;
1152  unsigned int i, entries;
1153 
1154  if (c->fc->nb_streams < 1)
1155  return 0;
1156  st = c->fc->streams[c->fc->nb_streams-1];
1157  sc = st->priv_data;
1158 
1159  avio_r8(pb); /* version */
1160  avio_rb24(pb); /* flags */
1161 
1162  entries = avio_rb32(pb);
1163 
1164  if (!entries)
1165  return 0;
1166  if (entries >= UINT_MAX/sizeof(int64_t))
1167  return AVERROR_INVALIDDATA;
1168 
1169  if (sc->chunk_offsets)
1170  av_log(c->fc, AV_LOG_WARNING, "Duplicate STCO atom\n");
1171  av_free(sc->chunk_offsets);
1172  sc->chunk_count = 0;
1173  sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1174  if (!sc->chunk_offsets)
1175  return AVERROR(ENOMEM);
1176  sc->chunk_count = entries;
1177 
1178  if (atom.type == MKTAG('s','t','c','o'))
1179  for (i = 0; i < entries && !pb->eof_reached; i++)
1180  sc->chunk_offsets[i] = avio_rb32(pb);
1181  else if (atom.type == MKTAG('c','o','6','4'))
1182  for (i = 0; i < entries && !pb->eof_reached; i++)
1183  sc->chunk_offsets[i] = avio_rb64(pb);
1184  else
1185  return AVERROR_INVALIDDATA;
1186 
1187  sc->chunk_count = i;
1188 
1189  if (pb->eof_reached)
1190  return AVERROR_EOF;
1191 
1192  return 0;
1193 }
1194 
1200 {
1201  /* lpcm flags:
1202  * 0x1 = float
1203  * 0x2 = big-endian
1204  * 0x4 = signed
1205  */
1206  return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1207 }
1208 
1210 {
1211  AVStream *st;
1212  MOVStreamContext *sc;
1213  int j, pseudo_stream_id;
1214 
1215  if (c->fc->nb_streams < 1)
1216  return 0;
1217  st = c->fc->streams[c->fc->nb_streams-1];
1218  sc = st->priv_data;
1219 
1220  for (pseudo_stream_id = 0;
1221  pseudo_stream_id < entries && !pb->eof_reached;
1222  pseudo_stream_id++) {
1223  //Parsing Sample description table
1224  enum AVCodecID id;
1225  int dref_id = 1;
1226  MOVAtom a = { AV_RL32("stsd") };
1227  int64_t start_pos = avio_tell(pb);
1228  int64_t size = avio_rb32(pb); /* size */
1229  uint32_t format = avio_rl32(pb); /* data format */
1230 
1231  if (size >= 16) {
1232  avio_rb32(pb); /* reserved */
1233  avio_rb16(pb); /* reserved */
1234  dref_id = avio_rb16(pb);
1235  }else if (size <= 7){
1236  av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1237  return AVERROR_INVALIDDATA;
1238  }
1239 
1240  if (st->codec->codec_tag &&
1241  st->codec->codec_tag != format &&
1243  : st->codec->codec_tag != MKTAG('j','p','e','g'))
1244  ){
1245  /* Multiple fourcc, we skip JPEG. This is not correct, we should
1246  * export it as a separate AVStream but this needs a few changes
1247  * in the MOV demuxer, patch welcome. */
1248  av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1249  avio_skip(pb, size - (avio_tell(pb) - start_pos));
1250  continue;
1251  }
1252  /* we cannot demux concatenated h264 streams because of different extradata */
1253  if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1254  av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1255  sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1256  sc->dref_id= dref_id;
1257 
1258  st->codec->codec_tag = format;
1260  if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1261  id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1262 
1263  if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1265  } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1266  format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1268  if (id <= 0)
1269  id = ff_codec_get_id(ff_codec_bmp_tags, format);
1270  if (id > 0)
1272  else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1274  st->codec->codec_id == AV_CODEC_ID_NONE)){
1276  if (id > 0)
1278  }
1279  }
1280 
1281  av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1282  (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1283  (format >> 24) & 0xff, st->codec->codec_type);
1284 
1285  if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1286  unsigned int color_depth, len;
1287  int color_greyscale;
1288  int color_table_id;
1289 
1290  st->codec->codec_id = id;
1291  avio_rb16(pb); /* version */
1292  avio_rb16(pb); /* revision level */
1293  avio_rb32(pb); /* vendor */
1294  avio_rb32(pb); /* temporal quality */
1295  avio_rb32(pb); /* spatial quality */
1296 
1297  st->codec->width = avio_rb16(pb); /* width */
1298  st->codec->height = avio_rb16(pb); /* height */
1299 
1300  avio_rb32(pb); /* horiz resolution */
1301  avio_rb32(pb); /* vert resolution */
1302  avio_rb32(pb); /* data size, always 0 */
1303  avio_rb16(pb); /* frames per samples */
1304 
1305  len = avio_r8(pb); /* codec name, pascal string */
1306  if (len > 31)
1307  len = 31;
1308  mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1309  if (len < 31)
1310  avio_skip(pb, 31 - len);
1311  /* codec_tag YV12 triggers an UV swap in rawdec.c */
1312  if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)){
1313  st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1314  st->codec->width &= ~1;
1315  st->codec->height &= ~1;
1316  }
1317  /* Flash Media Server uses tag H263 with Sorenson Spark */
1318  if (format == MKTAG('H','2','6','3') &&
1319  !memcmp(st->codec->codec_name, "Sorenson H263", 13))
1321 
1322  st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1323  color_table_id = avio_rb16(pb); /* colortable id */
1324  av_dlog(c->fc, "depth %d, ctab id %d\n",
1325  st->codec->bits_per_coded_sample, color_table_id);
1326  /* figure out the palette situation */
1327  color_depth = st->codec->bits_per_coded_sample & 0x1F;
1328  color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1329 
1330  /* if the depth is 2, 4, or 8 bpp, file is palettized */
1331  if ((color_depth == 2) || (color_depth == 4) ||
1332  (color_depth == 8)) {
1333  /* for palette traversal */
1334  unsigned int color_start, color_count, color_end;
1335  unsigned char a, r, g, b;
1336 
1337  if (color_greyscale) {
1338  int color_index, color_dec;
1339  /* compute the greyscale palette */
1340  st->codec->bits_per_coded_sample = color_depth;
1341  color_count = 1 << color_depth;
1342  color_index = 255;
1343  color_dec = 256 / (color_count - 1);
1344  for (j = 0; j < color_count; j++) {
1345  if (id == AV_CODEC_ID_CINEPAK){
1346  r = g = b = color_count - 1 - color_index;
1347  }else
1348  r = g = b = color_index;
1349  sc->palette[j] =
1350  (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1351  color_index -= color_dec;
1352  if (color_index < 0)
1353  color_index = 0;
1354  }
1355  } else if (color_table_id) {
1356  const uint8_t *color_table;
1357  /* if flag bit 3 is set, use the default palette */
1358  color_count = 1 << color_depth;
1359  if (color_depth == 2)
1360  color_table = ff_qt_default_palette_4;
1361  else if (color_depth == 4)
1362  color_table = ff_qt_default_palette_16;
1363  else
1364  color_table = ff_qt_default_palette_256;
1365 
1366  for (j = 0; j < color_count; j++) {
1367  r = color_table[j * 3 + 0];
1368  g = color_table[j * 3 + 1];
1369  b = color_table[j * 3 + 2];
1370  sc->palette[j] =
1371  (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1372  }
1373  } else {
1374  /* load the palette from the file */
1375  color_start = avio_rb32(pb);
1376  color_count = avio_rb16(pb);
1377  color_end = avio_rb16(pb);
1378  if ((color_start <= 255) &&
1379  (color_end <= 255)) {
1380  for (j = color_start; j <= color_end; j++) {
1381  /* each A, R, G, or B component is 16 bits;
1382  * only use the top 8 bits */
1383  a = avio_r8(pb);
1384  avio_r8(pb);
1385  r = avio_r8(pb);
1386  avio_r8(pb);
1387  g = avio_r8(pb);
1388  avio_r8(pb);
1389  b = avio_r8(pb);
1390  avio_r8(pb);
1391  sc->palette[j] =
1392  (a << 24 ) | (r << 16) | (g << 8) | (b);
1393  }
1394  }
1395  }
1396  sc->has_palette = 1;
1397  }
1398  } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1399  int bits_per_sample, flags;
1400  uint16_t version = avio_rb16(pb);
1401  AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1402 
1403  st->codec->codec_id = id;
1404  avio_rb16(pb); /* revision level */
1405  avio_rb32(pb); /* vendor */
1406 
1407  st->codec->channels = avio_rb16(pb); /* channel count */
1408  av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1409  st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1410 
1411  sc->audio_cid = avio_rb16(pb);
1412  avio_rb16(pb); /* packet size = 0 */
1413 
1414  st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1415 
1416  //Read QT version 1 fields. In version 0 these do not exist.
1417  av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1418  if (!c->isom ||
1419  (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1420  if (version==1) {
1421  sc->samples_per_frame = avio_rb32(pb);
1422  avio_rb32(pb); /* bytes per packet */
1423  sc->bytes_per_frame = avio_rb32(pb);
1424  avio_rb32(pb); /* bytes per sample */
1425  } else if (version==2) {
1426  avio_rb32(pb); /* sizeof struct only */
1427  st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1428  st->codec->channels = avio_rb32(pb);
1429  avio_rb32(pb); /* always 0x7F000000 */
1430  st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1431  flags = avio_rb32(pb); /* lpcm format specific flag */
1432  sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1433  sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1434  if (format == MKTAG('l','p','c','m'))
1436  }
1437  }
1438 
1439  switch (st->codec->codec_id) {
1440  case AV_CODEC_ID_PCM_S8:
1441  case AV_CODEC_ID_PCM_U8:
1442  if (st->codec->bits_per_coded_sample == 16)
1444  break;
1445  case AV_CODEC_ID_PCM_S16LE:
1446  case AV_CODEC_ID_PCM_S16BE:
1447  if (st->codec->bits_per_coded_sample == 8)
1449  else if (st->codec->bits_per_coded_sample == 24)
1450  st->codec->codec_id =
1453  break;
1454  /* set values for old format before stsd version 1 appeared */
1455  case AV_CODEC_ID_MACE3:
1456  sc->samples_per_frame = 6;
1457  sc->bytes_per_frame = 2*st->codec->channels;
1458  break;
1459  case AV_CODEC_ID_MACE6:
1460  sc->samples_per_frame = 6;
1461  sc->bytes_per_frame = 1*st->codec->channels;
1462  break;
1464  sc->samples_per_frame = 64;
1465  sc->bytes_per_frame = 34*st->codec->channels;
1466  break;
1467  case AV_CODEC_ID_GSM:
1468  sc->samples_per_frame = 160;
1469  sc->bytes_per_frame = 33;
1470  break;
1471  default:
1472  break;
1473  }
1474 
1475  bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1476  if (bits_per_sample) {
1477  st->codec->bits_per_coded_sample = bits_per_sample;
1478  sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1479  }
1480  } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1481  // ttxt stsd contains display flags, justification, background
1482  // color, fonts, and default styles, so fake an atom to read it
1483  MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1484  if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1485  mov_read_glbl(c, pb, fake_atom);
1486  st->codec->codec_id= id;
1487  st->codec->width = sc->width;
1488  st->codec->height = sc->height;
1489  } else {
1490  if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1491  MOVStreamContext *tmcd_ctx = st->priv_data;
1492  int val;
1493  avio_rb32(pb); /* reserved */
1494  val = avio_rb32(pb); /* flags */
1495  tmcd_ctx->tmcd_flags = val;
1496  if (val & 1)
1498  avio_rb32(pb); /* time scale */
1499  avio_rb32(pb); /* frame duration */
1500  st->codec->time_base.den = avio_r8(pb); /* number of frame */
1501  st->codec->time_base.num = 1;
1502  }
1503  /* other codec type, just skip (rtp, mp4s, ...) */
1504  avio_skip(pb, size - (avio_tell(pb) - start_pos));
1505  }
1506  /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1507  a.size = size - (avio_tell(pb) - start_pos);
1508  if (a.size > 8) {
1509  int ret;
1510  if ((ret = mov_read_default(c, pb, a)) < 0)
1511  return ret;
1512  } else if (a.size > 0)
1513  avio_skip(pb, a.size);
1514  }
1515 
1516  if (pb->eof_reached)
1517  return AVERROR_EOF;
1518 
1519  if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1520  st->codec->sample_rate= sc->time_scale;
1521 
1522  /* special codec parameters handling */
1523  switch (st->codec->codec_id) {
1524 #if CONFIG_DV_DEMUXER
1525  case AV_CODEC_ID_DVAUDIO:
1528  if (!c->dv_demux) {
1529  av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1530  return AVERROR(ENOMEM);
1531  }
1532  sc->dv_audio_container = 1;
1534  break;
1535 #endif
1536  /* no ifdef since parameters are always those */
1537  case AV_CODEC_ID_QCELP:
1538  // force sample rate for qcelp when not stored in mov
1539  if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1540  st->codec->sample_rate = 8000;
1541  st->codec->channels= 1; /* really needed */
1542  break;
1543  case AV_CODEC_ID_AMR_NB:
1544  st->codec->channels= 1; /* really needed */
1545  /* force sample rate for amr, stsd in 3gp does not store sample rate */
1546  st->codec->sample_rate = 8000;
1547  break;
1548  case AV_CODEC_ID_AMR_WB:
1549  st->codec->channels = 1;
1550  st->codec->sample_rate = 16000;
1551  break;
1552  case AV_CODEC_ID_MP2:
1553  case AV_CODEC_ID_MP3:
1554  st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1556  break;
1557  case AV_CODEC_ID_GSM:
1558  case AV_CODEC_ID_ADPCM_MS:
1560  case AV_CODEC_ID_ILBC:
1561  st->codec->block_align = sc->bytes_per_frame;
1562  break;
1563  case AV_CODEC_ID_ALAC:
1564  if (st->codec->extradata_size == 36) {
1565  st->codec->channels = AV_RB8 (st->codec->extradata+21);
1566  st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1567  }
1568  break;
1569  case AV_CODEC_ID_AC3:
1571  break;
1574  break;
1575  case AV_CODEC_ID_VC1:
1577  break;
1578  default:
1579  break;
1580  }
1581 
1582  return 0;
1583 }
1584 
1585 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1586 {
1587  int entries;
1588 
1589  avio_r8(pb); /* version */
1590  avio_rb24(pb); /* flags */
1591  entries = avio_rb32(pb);
1592 
1593  return ff_mov_read_stsd_entries(c, pb, entries);
1594 }
1595 
1596 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1597 {
1598  AVStream *st;
1599  MOVStreamContext *sc;
1600  unsigned int i, entries;
1601 
1602  if (c->fc->nb_streams < 1)
1603  return 0;
1604  st = c->fc->streams[c->fc->nb_streams-1];
1605  sc = st->priv_data;
1606 
1607  avio_r8(pb); /* version */
1608  avio_rb24(pb); /* flags */
1609 
1610  entries = avio_rb32(pb);
1611 
1612  av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1613 
1614  if (!entries)
1615  return 0;
1616  if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1617  return AVERROR_INVALIDDATA;
1618  if (sc->stsc_data)
1619  av_log(c->fc, AV_LOG_WARNING, "Duplicate STSC atom\n");
1620  av_free(sc->stsc_data);
1621  sc->stsc_count = 0;
1622  sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1623  if (!sc->stsc_data)
1624  return AVERROR(ENOMEM);
1625 
1626  for (i = 0; i < entries && !pb->eof_reached; i++) {
1627  sc->stsc_data[i].first = avio_rb32(pb);
1628  sc->stsc_data[i].count = avio_rb32(pb);
1629  sc->stsc_data[i].id = avio_rb32(pb);
1630  }
1631 
1632  sc->stsc_count = i;
1633 
1634  if (pb->eof_reached)
1635  return AVERROR_EOF;
1636 
1637  return 0;
1638 }
1639 
1640 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1641 {
1642  AVStream *st;
1643  MOVStreamContext *sc;
1644  unsigned i, entries;
1645 
1646  if (c->fc->nb_streams < 1)
1647  return 0;
1648  st = c->fc->streams[c->fc->nb_streams-1];
1649  sc = st->priv_data;
1650 
1651  avio_rb32(pb); // version + flags
1652 
1653  entries = avio_rb32(pb);
1654  if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1655  return AVERROR_INVALIDDATA;
1656  sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1657  if (!sc->stps_data)
1658  return AVERROR(ENOMEM);
1659 
1660  for (i = 0; i < entries && !pb->eof_reached; i++) {
1661  sc->stps_data[i] = avio_rb32(pb);
1662  //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1663  }
1664 
1665  sc->stps_count = i;
1666 
1667  if (pb->eof_reached)
1668  return AVERROR_EOF;
1669 
1670  return 0;
1671 }
1672 
1673 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1674 {
1675  AVStream *st;
1676  MOVStreamContext *sc;
1677  unsigned int i, entries;
1678 
1679  if (c->fc->nb_streams < 1)
1680  return 0;
1681  st = c->fc->streams[c->fc->nb_streams-1];
1682  sc = st->priv_data;
1683 
1684  avio_r8(pb); /* version */
1685  avio_rb24(pb); /* flags */
1686 
1687  entries = avio_rb32(pb);
1688 
1689  av_dlog(c->fc, "keyframe_count = %d\n", entries);
1690 
1691  if (!entries)
1692  {
1693  sc->keyframe_absent = 1;
1694  if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
1696  return 0;
1697  }
1698  if (entries >= UINT_MAX / sizeof(int))
1699  return AVERROR_INVALIDDATA;
1700  sc->keyframes = av_malloc(entries * sizeof(int));
1701  if (!sc->keyframes)
1702  return AVERROR(ENOMEM);
1703 
1704  for (i = 0; i < entries && !pb->eof_reached; i++) {
1705  sc->keyframes[i] = avio_rb32(pb);
1706  //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1707  }
1708 
1709  sc->keyframe_count = i;
1710 
1711  if (pb->eof_reached)
1712  return AVERROR_EOF;
1713 
1714  return 0;
1715 }
1716 
1717 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1718 {
1719  AVStream *st;
1720  MOVStreamContext *sc;
1721  unsigned int i, entries, sample_size, field_size, num_bytes;
1722  GetBitContext gb;
1723  unsigned char* buf;
1724 
1725  if (c->fc->nb_streams < 1)
1726  return 0;
1727  st = c->fc->streams[c->fc->nb_streams-1];
1728  sc = st->priv_data;
1729 
1730  avio_r8(pb); /* version */
1731  avio_rb24(pb); /* flags */
1732 
1733  if (atom.type == MKTAG('s','t','s','z')) {
1734  sample_size = avio_rb32(pb);
1735  if (!sc->sample_size) /* do not overwrite value computed in stsd */
1736  sc->sample_size = sample_size;
1737  sc->alt_sample_size = sample_size;
1738  field_size = 32;
1739  } else {
1740  sample_size = 0;
1741  avio_rb24(pb); /* reserved */
1742  field_size = avio_r8(pb);
1743  }
1744  entries = avio_rb32(pb);
1745 
1746  av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1747 
1748  sc->sample_count = entries;
1749  if (sample_size)
1750  return 0;
1751 
1752  if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1753  av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1754  return AVERROR_INVALIDDATA;
1755  }
1756 
1757  if (!entries)
1758  return 0;
1759  if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1760  return AVERROR_INVALIDDATA;
1761  sc->sample_sizes = av_malloc(entries * sizeof(int));
1762  if (!sc->sample_sizes)
1763  return AVERROR(ENOMEM);
1764 
1765  num_bytes = (entries*field_size+4)>>3;
1766 
1767  buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1768  if (!buf) {
1769  av_freep(&sc->sample_sizes);
1770  return AVERROR(ENOMEM);
1771  }
1772 
1773  if (avio_read(pb, buf, num_bytes) < num_bytes) {
1774  av_freep(&sc->sample_sizes);
1775  av_free(buf);
1776  return AVERROR_INVALIDDATA;
1777  }
1778 
1779  init_get_bits(&gb, buf, 8*num_bytes);
1780 
1781  for (i = 0; i < entries && !pb->eof_reached; i++) {
1782  sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1783  sc->data_size += sc->sample_sizes[i];
1784  }
1785 
1786  sc->sample_count = i;
1787 
1788  if (pb->eof_reached)
1789  return AVERROR_EOF;
1790 
1791  av_free(buf);
1792  return 0;
1793 }
1794 
1795 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1796 {
1797  AVStream *st;
1798  MOVStreamContext *sc;
1799  unsigned int i, entries;
1800  int64_t duration=0;
1801  int64_t total_sample_count=0;
1802 
1803  if (c->fc->nb_streams < 1)
1804  return 0;
1805  st = c->fc->streams[c->fc->nb_streams-1];
1806  sc = st->priv_data;
1807 
1808  avio_r8(pb); /* version */
1809  avio_rb24(pb); /* flags */
1810  entries = avio_rb32(pb);
1811 
1812  av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1813  c->fc->nb_streams-1, entries);
1814 
1815  if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1816  return -1;
1817 
1818  sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1819  if (!sc->stts_data)
1820  return AVERROR(ENOMEM);
1821 
1822  for (i = 0; i < entries && !pb->eof_reached; i++) {
1823  int sample_duration;
1824  int sample_count;
1825 
1826  sample_count=avio_rb32(pb);
1827  sample_duration = avio_rb32(pb);
1828  /* sample_duration < 0 is invalid based on the spec */
1829  if (sample_duration < 0) {
1830  av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1831  sample_duration = 1;
1832  }
1833  sc->stts_data[i].count= sample_count;
1834  sc->stts_data[i].duration= sample_duration;
1835 
1836  av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1837  sample_count, sample_duration);
1838 
1839  duration+=(int64_t)sample_duration*sample_count;
1840  total_sample_count+=sample_count;
1841  }
1842 
1843  sc->stts_count = i;
1844 
1845  if (pb->eof_reached)
1846  return AVERROR_EOF;
1847 
1848  st->nb_frames= total_sample_count;
1849  if (duration)
1850  st->duration= duration;
1851  sc->track_end = duration;
1852  return 0;
1853 }
1854 
1855 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1856 {
1857  AVStream *st;
1858  MOVStreamContext *sc;
1859  unsigned int i, entries;
1860 
1861  if (c->fc->nb_streams < 1)
1862  return 0;
1863  st = c->fc->streams[c->fc->nb_streams-1];
1864  sc = st->priv_data;
1865 
1866  avio_r8(pb); /* version */
1867  avio_rb24(pb); /* flags */
1868  entries = avio_rb32(pb);
1869 
1870  av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1871 
1872  if (!entries)
1873  return 0;
1874  if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1875  return AVERROR_INVALIDDATA;
1876  sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1877  if (!sc->ctts_data)
1878  return AVERROR(ENOMEM);
1879 
1880  for (i = 0; i < entries && !pb->eof_reached; i++) {
1881  int count =avio_rb32(pb);
1882  int duration =avio_rb32(pb);
1883 
1884  sc->ctts_data[i].count = count;
1885  sc->ctts_data[i].duration= duration;
1886 
1887  av_dlog(c->fc, "count=%d, duration=%d\n",
1888  count, duration);
1889 
1890  if (FFABS(duration) > (1<<28) && i+2<entries) {
1891  av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1892  av_freep(&sc->ctts_data);
1893  sc->ctts_count = 0;
1894  return 0;
1895  }
1896 
1897  if (duration < 0 && i+2<entries)
1898  sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1899  }
1900 
1901  sc->ctts_count = i;
1902 
1903  if (pb->eof_reached)
1904  return AVERROR_EOF;
1905 
1906  av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1907 
1908  return 0;
1909 }
1910 
1911 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1912 {
1913  AVStream *st;
1914  MOVStreamContext *sc;
1915  unsigned int i, entries;
1916  uint8_t version;
1917  uint32_t grouping_type;
1918 
1919  if (c->fc->nb_streams < 1)
1920  return 0;
1921  st = c->fc->streams[c->fc->nb_streams-1];
1922  sc = st->priv_data;
1923 
1924  version = avio_r8(pb); /* version */
1925  avio_rb24(pb); /* flags */
1926  grouping_type = avio_rl32(pb);
1927  if (grouping_type != MKTAG( 'r','a','p',' '))
1928  return 0; /* only support 'rap ' grouping */
1929  if (version == 1)
1930  avio_rb32(pb); /* grouping_type_parameter */
1931 
1932  entries = avio_rb32(pb);
1933  if (!entries)
1934  return 0;
1935  if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1936  return AVERROR_INVALIDDATA;
1937  sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1938  if (!sc->rap_group)
1939  return AVERROR(ENOMEM);
1940 
1941  for (i = 0; i < entries && !pb->eof_reached; i++) {
1942  sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1943  sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1944  }
1945 
1946  sc->rap_group_count = i;
1947 
1948  return pb->eof_reached ? AVERROR_EOF : 0;
1949 }
1950 
1951 static void mov_build_index(MOVContext *mov, AVStream *st)
1952 {
1953  MOVStreamContext *sc = st->priv_data;
1954  int64_t current_offset;
1955  int64_t current_dts = 0;
1956  unsigned int stts_index = 0;
1957  unsigned int stsc_index = 0;
1958  unsigned int stss_index = 0;
1959  unsigned int stps_index = 0;
1960  unsigned int i, j;
1961  uint64_t stream_size = 0;
1962  AVIndexEntry *mem;
1963 
1964  /* adjust first dts according to edit list */
1965  if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1966  if (sc->empty_duration)
1968  sc->time_offset = sc->start_time - sc->empty_duration;
1969  current_dts = -sc->time_offset;
1970  if (sc->ctts_count>0 && sc->stts_count>0 &&
1971  sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1972  /* more than 16 frames delay, dts are likely wrong
1973  this happens with files created by iMovie */
1974  sc->wrong_dts = 1;
1975  st->codec->has_b_frames = 1;
1976  }
1977  }
1978 
1979  /* only use old uncompressed audio chunk demuxing when stts specifies it */
1980  if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1981  sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1982  unsigned int current_sample = 0;
1983  unsigned int stts_sample = 0;
1984  unsigned int sample_size;
1985  unsigned int distance = 0;
1986  unsigned int rap_group_index = 0;
1987  unsigned int rap_group_sample = 0;
1988  int rap_group_present = sc->rap_group_count && sc->rap_group;
1989  int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
1990 
1991  current_dts -= sc->dts_shift;
1992 
1993  if (!sc->sample_count || st->nb_index_entries)
1994  return;
1995  if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1996  return;
1997  mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1998  if (!mem)
1999  return;
2000  st->index_entries = mem;
2002 
2003  for (i = 0; i < sc->chunk_count; i++) {
2004  current_offset = sc->chunk_offsets[i];
2005  while (stsc_index + 1 < sc->stsc_count &&
2006  i + 1 == sc->stsc_data[stsc_index + 1].first)
2007  stsc_index++;
2008  for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2009  int keyframe = 0;
2010  if (current_sample >= sc->sample_count) {
2011  av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2012  return;
2013  }
2014 
2015  if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2016  keyframe = 1;
2017  if (stss_index + 1 < sc->keyframe_count)
2018  stss_index++;
2019  } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2020  keyframe = 1;
2021  if (stps_index + 1 < sc->stps_count)
2022  stps_index++;
2023  }
2024  if (rap_group_present && rap_group_index < sc->rap_group_count) {
2025  if (sc->rap_group[rap_group_index].index > 0)
2026  keyframe = 1;
2027  if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2028  rap_group_sample = 0;
2029  rap_group_index++;
2030  }
2031  }
2032  if (sc->keyframe_absent
2033  && !sc->stps_count
2034  && !rap_group_present
2035  && st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2036  keyframe = 1;
2037  if (keyframe)
2038  distance = 0;
2039  sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
2040  if (sc->pseudo_stream_id == -1 ||
2041  sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2042  AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2043  e->pos = current_offset;
2044  e->timestamp = current_dts;
2045  e->size = sample_size;
2046  e->min_distance = distance;
2047  e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2048  av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2049  "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2050  current_offset, current_dts, sample_size, distance, keyframe);
2051  }
2052 
2053  current_offset += sample_size;
2054  stream_size += sample_size;
2055  current_dts += sc->stts_data[stts_index].duration;
2056  distance++;
2057  stts_sample++;
2058  current_sample++;
2059  if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2060  stts_sample = 0;
2061  stts_index++;
2062  }
2063  }
2064  }
2065  if (st->duration > 0)
2066  st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2067  } else {
2068  unsigned chunk_samples, total = 0;
2069 
2070  // compute total chunk count
2071  for (i = 0; i < sc->stsc_count; i++) {
2072  unsigned count, chunk_count;
2073 
2074  chunk_samples = sc->stsc_data[i].count;
2075  if (i != sc->stsc_count - 1 &&
2076  sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2077  av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2078  return;
2079  }
2080 
2081  if (sc->samples_per_frame >= 160) { // gsm
2082  count = chunk_samples / sc->samples_per_frame;
2083  } else if (sc->samples_per_frame > 1) {
2084  unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2085  count = (chunk_samples+samples-1) / samples;
2086  } else {
2087  count = (chunk_samples+1023) / 1024;
2088  }
2089 
2090  if (i < sc->stsc_count - 1)
2091  chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2092  else
2093  chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2094  total += chunk_count * count;
2095  }
2096 
2097  av_dlog(mov->fc, "chunk count %d\n", total);
2098  if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2099  return;
2100  mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
2101  if (!mem)
2102  return;
2103  st->index_entries = mem;
2104  st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2105 
2106  // populate index
2107  for (i = 0; i < sc->chunk_count; i++) {
2108  current_offset = sc->chunk_offsets[i];
2109  if (stsc_index + 1 < sc->stsc_count &&
2110  i + 1 == sc->stsc_data[stsc_index + 1].first)
2111  stsc_index++;
2112  chunk_samples = sc->stsc_data[stsc_index].count;
2113 
2114  while (chunk_samples > 0) {
2115  AVIndexEntry *e;
2116  unsigned size, samples;
2117 
2118  if (sc->samples_per_frame >= 160) { // gsm
2119  samples = sc->samples_per_frame;
2120  size = sc->bytes_per_frame;
2121  } else {
2122  if (sc->samples_per_frame > 1) {
2123  samples = FFMIN((1024 / sc->samples_per_frame)*
2124  sc->samples_per_frame, chunk_samples);
2125  size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2126  } else {
2127  samples = FFMIN(1024, chunk_samples);
2128  size = samples * sc->sample_size;
2129  }
2130  }
2131 
2132  if (st->nb_index_entries >= total) {
2133  av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2134  return;
2135  }
2136  e = &st->index_entries[st->nb_index_entries++];
2137  e->pos = current_offset;
2138  e->timestamp = current_dts;
2139  e->size = size;
2140  e->min_distance = 0;
2141  e->flags = AVINDEX_KEYFRAME;
2142  av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2143  "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2144  size, samples);
2145 
2146  current_offset += size;
2147  current_dts += samples;
2148  chunk_samples -= samples;
2149  }
2150  }
2151  }
2152 }
2153 
2154 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2155  AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2156 {
2157  /* try relative path, we do not try the absolute because it can leak information about our
2158  system to an attacker */
2159  if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2160  char filename[1024];
2161  const char *src_path;
2162  int i, l;
2163 
2164  /* find a source dir */
2165  src_path = strrchr(src, '/');
2166  if (src_path)
2167  src_path++;
2168  else
2169  src_path = src;
2170 
2171  /* find a next level down to target */
2172  for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2173  if (ref->path[l] == '/') {
2174  if (i == ref->nlvl_to - 1)
2175  break;
2176  else
2177  i++;
2178  }
2179 
2180  /* compose filename if next level down to target was found */
2181  if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
2182  memcpy(filename, src, src_path - src);
2183  filename[src_path - src] = 0;
2184 
2185  for (i = 1; i < ref->nlvl_from; i++)
2186  av_strlcat(filename, "../", 1024);
2187 
2188  av_strlcat(filename, ref->path + l + 1, 1024);
2189 
2190  if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2191  return 0;
2192  }
2193  } else if (use_absolute_path) {
2194  av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2195  "this is a possible security issue\n");
2196  if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2197  return 0;
2198  }
2199 
2200  return AVERROR(ENOENT);
2201 }
2202 
2204 {
2205  if (sc->time_scale <= 0) {
2206  av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2207  sc->time_scale = c->time_scale;
2208  if (sc->time_scale <= 0)
2209  sc->time_scale = 1;
2210  }
2211 }
2212 
2213 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2214 {
2215  AVStream *st;
2216  MOVStreamContext *sc;
2217  int ret;
2218 
2219  st = avformat_new_stream(c->fc, NULL);
2220  if (!st) return AVERROR(ENOMEM);
2221  st->id = c->fc->nb_streams;
2222  sc = av_mallocz(sizeof(MOVStreamContext));
2223  if (!sc) return AVERROR(ENOMEM);
2224 
2225  st->priv_data = sc;
2227  sc->ffindex = st->index;
2228 
2229  if ((ret = mov_read_default(c, pb, atom)) < 0)
2230  return ret;
2231 
2232  /* sanity checks */
2233  if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2234  (!sc->sample_size && !sc->sample_count))) {
2235  av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2236  st->index);
2237  return 0;
2238  }
2239 
2240  fix_timescale(c, sc);
2241 
2242  avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2243 
2244  mov_build_index(c, st);
2245 
2246  if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2247  MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2248  if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2249  c->use_absolute_path, c->fc) < 0)
2250  av_log(c->fc, AV_LOG_ERROR,
2251  "stream %d, error opening alias: path='%s', dir='%s', "
2252  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2253  st->index, dref->path, dref->dir, dref->filename,
2254  dref->volume, dref->nlvl_from, dref->nlvl_to);
2255  } else {
2256  sc->pb = c->fc->pb;
2257  sc->pb_is_copied = 1;
2258  }
2259 
2260  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2261  if (!st->sample_aspect_ratio.num &&
2262  (st->codec->width != sc->width || st->codec->height != sc->height)) {
2263  st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2264  ((double)st->codec->width * sc->height), INT_MAX);
2265  }
2266 
2267  if (st->duration > 0)
2269  sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2270 
2271 #if FF_API_R_FRAME_RATE
2272  if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2273  av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2274  sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2275 #endif
2276  }
2277 
2278  // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2279  if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
2280  st->codec->codec_tag != MKTAG('a', 'v', 'c', '1')) {
2282  }
2283 
2284  switch (st->codec->codec_id) {
2285 #if CONFIG_H261_DECODER
2286  case AV_CODEC_ID_H261:
2287 #endif
2288 #if CONFIG_H263_DECODER
2289  case AV_CODEC_ID_H263:
2290 #endif
2291 #if CONFIG_MPEG4_DECODER
2292  case AV_CODEC_ID_MPEG4:
2293 #endif
2294  st->codec->width = 0; /* let decoder init width/height */
2295  st->codec->height= 0;
2296  break;
2297  }
2298 
2299  /* Do not need those anymore. */
2300  av_freep(&sc->chunk_offsets);
2301  av_freep(&sc->stsc_data);
2302  av_freep(&sc->sample_sizes);
2303  av_freep(&sc->keyframes);
2304  av_freep(&sc->stts_data);
2305  av_freep(&sc->stps_data);
2306  av_freep(&sc->rap_group);
2307 
2308  return 0;
2309 }
2310 
2311 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2312 {
2313  int ret;
2314  c->itunes_metadata = 1;
2315  ret = mov_read_default(c, pb, atom);
2316  c->itunes_metadata = 0;
2317  return ret;
2318 }
2319 
2320 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2321 {
2322  while (atom.size > 8) {
2323  uint32_t tag = avio_rl32(pb);
2324  atom.size -= 4;
2325  if (tag == MKTAG('h','d','l','r')) {
2326  avio_seek(pb, -8, SEEK_CUR);
2327  atom.size += 8;
2328  return mov_read_default(c, pb, atom);
2329  }
2330  }
2331  return 0;
2332 }
2333 
2334 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2335 {
2336  int i;
2337  int width;
2338  int height;
2339  int64_t disp_transform[2];
2340  int display_matrix[3][2];
2341  AVStream *st;
2342  MOVStreamContext *sc;
2343  int version;
2344 
2345  if (c->fc->nb_streams < 1)
2346  return 0;
2347  st = c->fc->streams[c->fc->nb_streams-1];
2348  sc = st->priv_data;
2349 
2350  version = avio_r8(pb);
2351  avio_rb24(pb); /* flags */
2352  /*
2353  MOV_TRACK_ENABLED 0x0001
2354  MOV_TRACK_IN_MOVIE 0x0002
2355  MOV_TRACK_IN_PREVIEW 0x0004
2356  MOV_TRACK_IN_POSTER 0x0008
2357  */
2358 
2359  if (version == 1) {
2360  avio_rb64(pb);
2361  avio_rb64(pb);
2362  } else {
2363  avio_rb32(pb); /* creation time */
2364  avio_rb32(pb); /* modification time */
2365  }
2366  st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2367  avio_rb32(pb); /* reserved */
2368 
2369  /* highlevel (considering edits) duration in movie timebase */
2370  (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2371  avio_rb32(pb); /* reserved */
2372  avio_rb32(pb); /* reserved */
2373 
2374  avio_rb16(pb); /* layer */
2375  avio_rb16(pb); /* alternate group */
2376  avio_rb16(pb); /* volume */
2377  avio_rb16(pb); /* reserved */
2378 
2379  //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2380  // they're kept in fixed point format through all calculations
2381  // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2382  for (i = 0; i < 3; i++) {
2383  display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
2384  display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
2385  avio_rb32(pb); // 2.30 fixed point (not used)
2386  }
2387 
2388  width = avio_rb32(pb); // 16.16 fixed point track width
2389  height = avio_rb32(pb); // 16.16 fixed point track height
2390  sc->width = width >> 16;
2391  sc->height = height >> 16;
2392 
2393  //Assign clockwise rotate values based on transform matrix so that
2394  //we can compensate for iPhone orientation during capture.
2395 
2396  if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2397  av_dict_set(&st->metadata, "rotate", "90", 0);
2398  }
2399 
2400  if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2401  av_dict_set(&st->metadata, "rotate", "180", 0);
2402  }
2403 
2404  if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2405  av_dict_set(&st->metadata, "rotate", "270", 0);
2406  }
2407 
2408  // transform the display width/height according to the matrix
2409  // skip this if the display matrix is the default identity matrix
2410  // or if it is rotating the picture, ex iPhone 3GS
2411  // to keep the same scale, use [width height 1<<16]
2412  if (width && height &&
2413  ((display_matrix[0][0] != 65536 ||
2414  display_matrix[1][1] != 65536) &&
2415  !display_matrix[0][1] &&
2416  !display_matrix[1][0] &&
2417  !display_matrix[2][0] && !display_matrix[2][1])) {
2418  for (i = 0; i < 2; i++)
2419  disp_transform[i] =
2420  (int64_t) width * display_matrix[0][i] +
2421  (int64_t) height * display_matrix[1][i] +
2422  ((int64_t) display_matrix[2][i] << 16);
2423 
2424  //sample aspect ratio is new width/height divided by old width/height
2426  ((double) disp_transform[0] * height) /
2427  ((double) disp_transform[1] * width), INT_MAX);
2428  }
2429  return 0;
2430 }
2431 
2432 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2433 {
2434  MOVFragment *frag = &c->fragment;
2435  MOVTrackExt *trex = NULL;
2436  int flags, track_id, i;
2437 
2438  avio_r8(pb); /* version */
2439  flags = avio_rb24(pb);
2440 
2441  track_id = avio_rb32(pb);
2442  if (!track_id)
2443  return AVERROR_INVALIDDATA;
2444  frag->track_id = track_id;
2445  for (i = 0; i < c->trex_count; i++)
2446  if (c->trex_data[i].track_id == frag->track_id) {
2447  trex = &c->trex_data[i];
2448  break;
2449  }
2450  if (!trex) {
2451  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2452  return AVERROR_INVALIDDATA;
2453  }
2454 
2456  avio_rb64(pb) : frag->moof_offset;
2457  frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2458 
2459  frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2460  avio_rb32(pb) : trex->duration;
2461  frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
2462  avio_rb32(pb) : trex->size;
2463  frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
2464  avio_rb32(pb) : trex->flags;
2465  av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2466  return 0;
2467 }
2468 
2469 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2470 {
2471  c->chapter_track = avio_rb32(pb);
2472  return 0;
2473 }
2474 
2475 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2476 {
2477  MOVTrackExt *trex;
2478 
2479  if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2480  return AVERROR_INVALIDDATA;
2481  trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2482  if (!trex)
2483  return AVERROR(ENOMEM);
2484 
2485  c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2486 
2487  c->trex_data = trex;
2488  trex = &c->trex_data[c->trex_count++];
2489  avio_r8(pb); /* version */
2490  avio_rb24(pb); /* flags */
2491  trex->track_id = avio_rb32(pb);
2492  trex->stsd_id = avio_rb32(pb);
2493  trex->duration = avio_rb32(pb);
2494  trex->size = avio_rb32(pb);
2495  trex->flags = avio_rb32(pb);
2496  return 0;
2497 }
2498 
2499 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2500 {
2501  MOVFragment *frag = &c->fragment;
2502  AVStream *st = NULL;
2503  MOVStreamContext *sc;
2504  MOVStts *ctts_data;
2505  uint64_t offset;
2506  int64_t dts;
2507  int data_offset = 0;
2508  unsigned entries, first_sample_flags = frag->flags;
2509  int flags, distance, i, found_keyframe = 0;
2510 
2511  for (i = 0; i < c->fc->nb_streams; i++) {
2512  if (c->fc->streams[i]->id == frag->track_id) {
2513  st = c->fc->streams[i];
2514  break;
2515  }
2516  }
2517  if (!st) {
2518  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2519  return AVERROR_INVALIDDATA;
2520  }
2521  sc = st->priv_data;
2522  if (sc->pseudo_stream_id+1 != frag->stsd_id)
2523  return 0;
2524  avio_r8(pb); /* version */
2525  flags = avio_rb24(pb);
2526  entries = avio_rb32(pb);
2527  av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2528 
2529  /* Always assume the presence of composition time offsets.
2530  * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2531  * 1) in the initial movie, there are no samples.
2532  * 2) in the first movie fragment, there is only one sample without composition time offset.
2533  * 3) in the subsequent movie fragments, there are samples with composition time offset. */
2534  if (!sc->ctts_count && sc->sample_count)
2535  {
2536  /* Complement ctts table if moov atom doesn't have ctts atom. */
2537  ctts_data = av_malloc(sizeof(*sc->ctts_data));
2538  if (!ctts_data)
2539  return AVERROR(ENOMEM);
2540  sc->ctts_data = ctts_data;
2541  sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2542  sc->ctts_data[sc->ctts_count].duration = 0;
2543  sc->ctts_count++;
2544  }
2545  if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2546  return AVERROR_INVALIDDATA;
2547  ctts_data = av_realloc(sc->ctts_data,
2548  (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2549  if (!ctts_data)
2550  return AVERROR(ENOMEM);
2551  sc->ctts_data = ctts_data;
2552 
2553  if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
2554  if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2555  dts = sc->track_end - sc->time_offset;
2556  offset = frag->base_data_offset + data_offset;
2557  distance = 0;
2558  av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2559  for (i = 0; i < entries && !pb->eof_reached; i++) {
2560  unsigned sample_size = frag->size;
2561  int sample_flags = i ? frag->flags : first_sample_flags;
2562  unsigned sample_duration = frag->duration;
2563  int keyframe = 0;
2564 
2565  if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2566  if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
2567  if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
2568  sc->ctts_data[sc->ctts_count].count = 1;
2569  sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2570  avio_rb32(pb) : 0;
2571  sc->ctts_count++;
2572  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2573  keyframe = 1;
2574  else if (!found_keyframe)
2575  keyframe = found_keyframe =
2576  !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2578  if (keyframe)
2579  distance = 0;
2580  av_add_index_entry(st, offset, dts, sample_size, distance,
2581  keyframe ? AVINDEX_KEYFRAME : 0);
2582  av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2583  "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2584  offset, dts, sample_size, distance, keyframe);
2585  distance++;
2586  dts += sample_duration;
2587  offset += sample_size;
2588  sc->data_size += sample_size;
2589  }
2590 
2591  if (pb->eof_reached)
2592  return AVERROR_EOF;
2593 
2594  frag->moof_offset = offset;
2595  st->duration = sc->track_end = dts + sc->time_offset;
2596  return 0;
2597 }
2598 
2599 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2600 /* like the files created with Adobe Premiere 5.0, for samples see */
2601 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2602 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2603 {
2604  int err;
2605 
2606  if (atom.size < 8)
2607  return 0; /* continue */
2608  if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2609  avio_skip(pb, atom.size - 4);
2610  return 0;
2611  }
2612  atom.type = avio_rl32(pb);
2613  atom.size -= 8;
2614  if (atom.type != MKTAG('m','d','a','t')) {
2615  avio_skip(pb, atom.size);
2616  return 0;
2617  }
2618  err = mov_read_mdat(c, pb, atom);
2619  return err;
2620 }
2621 
2622 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2623 {
2624 #if CONFIG_ZLIB
2625  AVIOContext ctx;
2626  uint8_t *cmov_data;
2627  uint8_t *moov_data; /* uncompressed data */
2628  long cmov_len, moov_len;
2629  int ret = -1;
2630 
2631  avio_rb32(pb); /* dcom atom */
2632  if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2633  return AVERROR_INVALIDDATA;
2634  if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2635  av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2636  return AVERROR_INVALIDDATA;
2637  }
2638  avio_rb32(pb); /* cmvd atom */
2639  if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2640  return AVERROR_INVALIDDATA;
2641  moov_len = avio_rb32(pb); /* uncompressed size */
2642  cmov_len = atom.size - 6 * 4;
2643 
2644  cmov_data = av_malloc(cmov_len);
2645  if (!cmov_data)
2646  return AVERROR(ENOMEM);
2647  moov_data = av_malloc(moov_len);
2648  if (!moov_data) {
2649  av_free(cmov_data);
2650  return AVERROR(ENOMEM);
2651  }
2652  avio_read(pb, cmov_data, cmov_len);
2653  if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2654  goto free_and_return;
2655  if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2656  goto free_and_return;
2657  atom.type = MKTAG('m','o','o','v');
2658  atom.size = moov_len;
2659  ret = mov_read_default(c, &ctx, atom);
2660 free_and_return:
2661  av_free(moov_data);
2662  av_free(cmov_data);
2663  return ret;
2664 #else
2665  av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2666  return AVERROR(ENOSYS);
2667 #endif
2668 }
2669 
2670 /* edit list atom */
2671 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2672 {
2673  MOVStreamContext *sc;
2674  int i, edit_count, version, edit_start_index = 0;
2675  int unsupported = 0;
2676 
2677  if (c->fc->nb_streams < 1 || c->ignore_editlist)
2678  return 0;
2679  sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2680 
2681  version = avio_r8(pb); /* version */
2682  avio_rb24(pb); /* flags */
2683  edit_count = avio_rb32(pb); /* entries */
2684 
2685  if ((uint64_t)edit_count*12+8 > atom.size)
2686  return AVERROR_INVALIDDATA;
2687 
2688  av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2689  for (i=0; i<edit_count; i++){
2690  int64_t time;
2691  int64_t duration;
2692  int rate;
2693  if (version == 1) {
2694  duration = avio_rb64(pb);
2695  time = avio_rb64(pb);
2696  } else {
2697  duration = avio_rb32(pb); /* segment duration */
2698  time = (int32_t)avio_rb32(pb); /* media time */
2699  }
2700  rate = avio_rb32(pb);
2701  if (i == 0 && time == -1) {
2702  sc->empty_duration = duration;
2703  edit_start_index = 1;
2704  } else if (i == edit_start_index && time >= 0)
2705  sc->start_time = time;
2706  else
2707  unsupported = 1;
2708 
2709  av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2710  duration, time, rate / 65536.0);
2711  }
2712 
2713  if (unsupported)
2714  av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2715  "a/v desync might occur, patch welcome\n");
2716 
2717  return 0;
2718 }
2719 
2720 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2721 {
2722  MOVStreamContext *sc;
2723 
2724  if (c->fc->nb_streams < 1)
2725  return AVERROR_INVALIDDATA;
2726  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2727  sc->timecode_track = avio_rb32(pb);
2728  return 0;
2729 }
2730 
2732 { MKTAG('A','C','L','R'), mov_read_avid },
2733 { MKTAG('A','P','R','G'), mov_read_avid },
2734 { MKTAG('A','A','L','P'), mov_read_avid },
2735 { MKTAG('A','R','E','S'), mov_read_avid },
2736 { MKTAG('a','v','s','s'), mov_read_avss },
2737 { MKTAG('c','h','p','l'), mov_read_chpl },
2738 { MKTAG('c','o','6','4'), mov_read_stco },
2739 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2740 { MKTAG('d','i','n','f'), mov_read_default },
2741 { MKTAG('d','r','e','f'), mov_read_dref },
2742 { MKTAG('e','d','t','s'), mov_read_default },
2743 { MKTAG('e','l','s','t'), mov_read_elst },
2744 { MKTAG('e','n','d','a'), mov_read_enda },
2745 { MKTAG('f','i','e','l'), mov_read_fiel },
2746 { MKTAG('f','t','y','p'), mov_read_ftyp },
2747 { MKTAG('g','l','b','l'), mov_read_glbl },
2748 { MKTAG('h','d','l','r'), mov_read_hdlr },
2749 { MKTAG('i','l','s','t'), mov_read_ilst },
2750 { MKTAG('j','p','2','h'), mov_read_jp2h },
2751 { MKTAG('m','d','a','t'), mov_read_mdat },
2752 { MKTAG('m','d','h','d'), mov_read_mdhd },
2753 { MKTAG('m','d','i','a'), mov_read_default },
2754 { MKTAG('m','e','t','a'), mov_read_meta },
2755 { MKTAG('m','i','n','f'), mov_read_default },
2756 { MKTAG('m','o','o','f'), mov_read_moof },
2757 { MKTAG('m','o','o','v'), mov_read_moov },
2758 { MKTAG('m','v','e','x'), mov_read_default },
2759 { MKTAG('m','v','h','d'), mov_read_mvhd },
2760 { MKTAG('S','M','I',' '), mov_read_svq3 },
2761 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2762 { MKTAG('a','v','c','C'), mov_read_glbl },
2763 { MKTAG('p','a','s','p'), mov_read_pasp },
2764 { MKTAG('s','t','b','l'), mov_read_default },
2765 { MKTAG('s','t','c','o'), mov_read_stco },
2766 { MKTAG('s','t','p','s'), mov_read_stps },
2767 { MKTAG('s','t','r','f'), mov_read_strf },
2768 { MKTAG('s','t','s','c'), mov_read_stsc },
2769 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2770 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2771 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2772 { MKTAG('s','t','t','s'), mov_read_stts },
2773 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2774 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2775 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2776 { MKTAG('t','r','a','k'), mov_read_trak },
2777 { MKTAG('t','r','a','f'), mov_read_default },
2778 { MKTAG('t','r','e','f'), mov_read_default },
2779 { MKTAG('t','m','c','d'), mov_read_tmcd },
2780 { MKTAG('c','h','a','p'), mov_read_chap },
2781 { MKTAG('t','r','e','x'), mov_read_trex },
2782 { MKTAG('t','r','u','n'), mov_read_trun },
2783 { MKTAG('u','d','t','a'), mov_read_default },
2784 { MKTAG('w','a','v','e'), mov_read_wave },
2785 { MKTAG('e','s','d','s'), mov_read_esds },
2786 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2787 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2788 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2789 { MKTAG('w','f','e','x'), mov_read_wfex },
2790 { MKTAG('c','m','o','v'), mov_read_cmov },
2791 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2792 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2793 { MKTAG('s','b','g','p'), mov_read_sbgp },
2794 { 0, NULL }
2795 };
2796 
2798 {
2799  int64_t total_size = 0;
2800  MOVAtom a;
2801  int i;
2802 
2803  if (c->atom_depth > 10) {
2804  av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
2805  return AVERROR_INVALIDDATA;
2806  }
2807  c->atom_depth ++;
2808 
2809  if (atom.size < 0)
2810  atom.size = INT64_MAX;
2811  while (total_size + 8 <= atom.size && !url_feof(pb)) {
2812  int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2813  a.size = atom.size;
2814  a.type=0;
2815  if (atom.size >= 8) {
2816  a.size = avio_rb32(pb);
2817  a.type = avio_rl32(pb);
2818  if (atom.type != MKTAG('r','o','o','t') &&
2819  atom.type != MKTAG('m','o','o','v'))
2820  {
2821  if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
2822  {
2823  av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
2824  avio_skip(pb, -8);
2825  c->atom_depth --;
2826  return 0;
2827  }
2828  }
2829  total_size += 8;
2830  if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
2831  a.size = avio_rb64(pb) - 8;
2832  total_size += 8;
2833  }
2834  }
2835  av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2836  a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2837  if (a.size == 0) {
2838  a.size = atom.size - total_size + 8;
2839  }
2840  a.size -= 8;
2841  if (a.size < 0)
2842  break;
2843  a.size = FFMIN(a.size, atom.size - total_size);
2844 
2845  for (i = 0; mov_default_parse_table[i].type; i++)
2846  if (mov_default_parse_table[i].type == a.type) {
2847  parse = mov_default_parse_table[i].parse;
2848  break;
2849  }
2850 
2851  // container is user data
2852  if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2853  atom.type == MKTAG('i','l','s','t')))
2855 
2856  if (!parse) { /* skip leaf atoms data */
2857  avio_skip(pb, a.size);
2858  } else {
2859  int64_t start_pos = avio_tell(pb);
2860  int64_t left;
2861  int err = parse(c, pb, a);
2862  if (err < 0) {
2863  c->atom_depth --;
2864  return err;
2865  }
2866  if (c->found_moov && c->found_mdat &&
2867  ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2868  start_pos + a.size == avio_size(pb))) {
2869  if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2870  c->next_root_atom = start_pos + a.size;
2871  c->atom_depth --;
2872  return 0;
2873  }
2874  left = a.size - avio_tell(pb) + start_pos;
2875  if (left > 0) /* skip garbage at atom end */
2876  avio_skip(pb, left);
2877  else if(left < 0) {
2878  av_log(c->fc, AV_LOG_DEBUG, "undoing overread of %"PRId64" in '%.4s'\n", -left, (char*)&a.type);
2879  avio_seek(pb, left, SEEK_CUR);
2880  }
2881  }
2882 
2883  total_size += a.size;
2884  }
2885 
2886  if (total_size < atom.size && atom.size < 0x7ffff)
2887  avio_skip(pb, atom.size - total_size);
2888 
2889  c->atom_depth --;
2890  return 0;
2891 }
2892 
2893 static int mov_probe(AVProbeData *p)
2894 {
2895  int64_t offset;
2896  uint32_t tag;
2897  int score = 0;
2898  int moov_offset = -1;
2899 
2900  /* check file header */
2901  offset = 0;
2902  for (;;) {
2903  /* ignore invalid offset */
2904  if ((offset + 8) > (unsigned int)p->buf_size)
2905  break;
2906  tag = AV_RL32(p->buf + offset + 4);
2907  switch(tag) {
2908  /* check for obvious tags */
2909  case MKTAG('m','o','o','v'):
2910  moov_offset = offset + 4;
2911  case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2912  case MKTAG('m','d','a','t'):
2913  case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2914  case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2915  case MKTAG('f','t','y','p'):
2916  if (AV_RB32(p->buf+offset) < 8 &&
2917  (AV_RB32(p->buf+offset) != 1 ||
2918  offset + 12 > (unsigned int)p->buf_size ||
2919  AV_RB64(p->buf+offset + 8) == 0)) {
2920  score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2921  } else {
2922  score = AVPROBE_SCORE_MAX;
2923  }
2924  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2925  break;
2926  /* those are more common words, so rate then a bit less */
2927  case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2928  case MKTAG('w','i','d','e'):
2929  case MKTAG('f','r','e','e'):
2930  case MKTAG('j','u','n','k'):
2931  case MKTAG('p','i','c','t'):
2932  score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
2933  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2934  break;
2935  case MKTAG(0x82,0x82,0x7f,0x7d):
2936  case MKTAG('s','k','i','p'):
2937  case MKTAG('u','u','i','d'):
2938  case MKTAG('p','r','f','l'):
2939  /* if we only find those cause probedata is too small at least rate them */
2940  score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2941  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2942  break;
2943  default:
2944  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2945  }
2946  }
2947  if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
2948  /* moov atom in the header - we should make sure that this is not a
2949  * MOV-packed MPEG-PS */
2950  offset = moov_offset;
2951 
2952  while(offset < (p->buf_size - 16)){ /* Sufficient space */
2953  /* We found an actual hdlr atom */
2954  if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
2955  AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
2956  AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
2957  av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
2958  /* We found a media handler reference atom describing an
2959  * MPEG-PS-in-MOV, return a
2960  * low score to force expanding the probe window until
2961  * mpegps_probe finds what it needs */
2962  return 5;
2963  }else
2964  /* Keep looking */
2965  offset+=2;
2966  }
2967  }
2968 
2969  return score;
2970 }
2971 
2972 // must be done after parsing all trak because there's no order requirement
2974 {
2975  MOVContext *mov = s->priv_data;
2976  AVStream *st = NULL;
2977  MOVStreamContext *sc;
2978  int64_t cur_pos;
2979  int i;
2980 
2981  for (i = 0; i < s->nb_streams; i++)
2982  if (s->streams[i]->id == mov->chapter_track) {
2983  st = s->streams[i];
2984  break;
2985  }
2986  if (!st) {
2987  av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2988  return;
2989  }
2990 
2991  st->discard = AVDISCARD_ALL;
2992  sc = st->priv_data;
2993  cur_pos = avio_tell(sc->pb);
2994 
2995  for (i = 0; i < st->nb_index_entries; i++) {
2996  AVIndexEntry *sample = &st->index_entries[i];
2997  int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2998  uint8_t *title;
2999  uint16_t ch;
3000  int len, title_len;
3001 
3002  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3003  av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3004  goto finish;
3005  }
3006 
3007  // the first two bytes are the length of the title
3008  len = avio_rb16(sc->pb);
3009  if (len > sample->size-2)
3010  continue;
3011  title_len = 2*len + 1;
3012  if (!(title = av_mallocz(title_len)))
3013  goto finish;
3014 
3015  // The samples could theoretically be in any encoding if there's an encd
3016  // atom following, but in practice are only utf-8 or utf-16, distinguished
3017  // instead by the presence of a BOM
3018  if (!len) {
3019  title[0] = 0;
3020  } else {
3021  ch = avio_rb16(sc->pb);
3022  if (ch == 0xfeff)
3023  avio_get_str16be(sc->pb, len, title, title_len);
3024  else if (ch == 0xfffe)
3025  avio_get_str16le(sc->pb, len, title, title_len);
3026  else {
3027  AV_WB16(title, ch);
3028  if (len == 1 || len == 2)
3029  title[len] = 0;
3030  else
3031  avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3032  }
3033  }
3034 
3035  avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3036  av_freep(&title);
3037  }
3038 finish:
3039  avio_seek(sc->pb, cur_pos, SEEK_SET);
3040 }
3041 
3043  uint32_t value, int flags)
3044 {
3045  AVTimecode tc;
3046  char buf[AV_TIMECODE_STR_SIZE];
3047  AVRational rate = {st->codec->time_base.den,
3048  st->codec->time_base.num};
3049  int ret = av_timecode_init(&tc, rate, flags, 0, s);
3050  if (ret < 0)
3051  return ret;
3052  av_dict_set(&st->metadata, "timecode",
3053  av_timecode_make_string(&tc, buf, value), 0);
3054  return 0;
3055 }
3056 
3058 {
3059  MOVStreamContext *sc = st->priv_data;
3060  int flags = 0;
3061  int64_t cur_pos = avio_tell(sc->pb);
3062  uint32_t value;
3063 
3064  if (!st->nb_index_entries)
3065  return -1;
3066 
3067  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3068  value = avio_rb32(s->pb);
3069 
3070  if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3071  if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3072  if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3073 
3074  /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3075  * not the case) and thus assume "frame number format" instead of QT one.
3076  * No sample with tmcd track can be found with a QT timecode at the moment,
3077  * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3078  * format). */
3079  parse_timecode_in_framenum_format(s, st, value, flags);
3080 
3081  avio_seek(sc->pb, cur_pos, SEEK_SET);
3082  return 0;
3083 }
3084 
3086 {
3087  MOVContext *mov = s->priv_data;
3088  int i, j;
3089 
3090  for (i = 0; i < s->nb_streams; i++) {
3091  AVStream *st = s->streams[i];
3092  MOVStreamContext *sc = st->priv_data;
3093 
3094  av_freep(&sc->ctts_data);
3095  for (j = 0; j < sc->drefs_count; j++) {
3096  av_freep(&sc->drefs[j].path);
3097  av_freep(&sc->drefs[j].dir);
3098  }
3099  av_freep(&sc->drefs);
3100  if (!sc->pb_is_copied)
3101  avio_close(sc->pb);
3102  sc->pb = NULL;
3103  av_freep(&sc->chunk_offsets);
3104  av_freep(&sc->keyframes);
3105  av_freep(&sc->sample_sizes);
3106  av_freep(&sc->stps_data);
3107  av_freep(&sc->stsc_data);
3108  av_freep(&sc->stts_data);
3109  }
3110 
3111  if (mov->dv_demux) {
3112  for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3113  av_freep(&mov->dv_fctx->streams[i]->codec);
3114  av_freep(&mov->dv_fctx->streams[i]);
3115  }
3116  av_freep(&mov->dv_fctx);
3117  av_freep(&mov->dv_demux);
3118  }
3119 
3120  av_freep(&mov->trex_data);
3121 
3122  return 0;
3123 }
3124 
3125 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3126 {
3127  int i;
3128 
3129  for (i = 0; i < s->nb_streams; i++) {
3130  AVStream *st = s->streams[i];
3131  MOVStreamContext *sc = st->priv_data;
3132 
3133  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
3134  sc->timecode_track == tmcd_id)
3135  return 1;
3136  }
3137  return 0;
3138 }
3139 
3140 /* look for a tmcd track not referenced by any video track, and export it globally */
3142 {
3143  int i;
3144 
3145  for (i = 0; i < s->nb_streams; i++) {
3146  AVStream *st = s->streams[i];
3147 
3148  if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
3149  !tmcd_is_referenced(s, i + 1)) {
3150  AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3151  if (tcr) {
3152  av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3153  break;
3154  }
3155  }
3156  }
3157 }
3158 
3160 {
3161  MOVContext *mov = s->priv_data;
3162  AVIOContext *pb = s->pb;
3163  int i, j, err;
3164  MOVAtom atom = { AV_RL32("root") };
3165 
3166  mov->fc = s;
3167  /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3168  if (pb->seekable)
3169  atom.size = avio_size(pb);
3170  else
3171  atom.size = INT64_MAX;
3172 
3173  /* check MOV header */
3174  if ((err = mov_read_default(mov, pb, atom)) < 0) {
3175  av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3176  mov_read_close(s);
3177  return err;
3178  }
3179  if (!mov->found_moov) {
3180  av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3181  mov_read_close(s);
3182  return AVERROR_INVALIDDATA;
3183  }
3184  av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3185 
3186  if (pb->seekable) {
3187  if (mov->chapter_track > 0)
3188  mov_read_chapters(s);
3189  for (i = 0; i < s->nb_streams; i++)
3190  if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3191  mov_read_timecode_track(s, s->streams[i]);
3192  }
3193 
3194  /* copy timecode metadata from tmcd tracks to the related video streams */
3195  for (i = 0; i < s->nb_streams; i++) {
3196  AVStream *st = s->streams[i];
3197  MOVStreamContext *sc = st->priv_data;
3198  if (sc->timecode_track > 0) {
3199  AVDictionaryEntry *tcr;
3200  int tmcd_st_id = -1;
3201 
3202  for (j = 0; j < s->nb_streams; j++)
3203  if (s->streams[j]->id == sc->timecode_track)
3204  tmcd_st_id = j;
3205 
3206  if (tmcd_st_id < 0 || tmcd_st_id == i)
3207  continue;
3208  tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3209  if (tcr)
3210  av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3211  }
3212  }
3214 
3215  for (i = 0; i < s->nb_streams; i++) {
3216  AVStream *st = s->streams[i];
3217  MOVStreamContext *sc = st->priv_data;
3218  fix_timescale(mov, sc);
3220  st->skip_samples = sc->start_pad;
3221  }
3222  }
3223 
3224  if (mov->trex_data) {
3225  for (i = 0; i < s->nb_streams; i++) {
3226  AVStream *st = s->streams[i];
3227  MOVStreamContext *sc = st->priv_data;
3228  if (st->duration)
3229  st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3230  }
3231  }
3232 
3233  return 0;
3234 }
3235 
3237 {
3239  int64_t best_dts = INT64_MAX;
3240  int i;
3241  for (i = 0; i < s->nb_streams; i++) {
3242  AVStream *avst = s->streams[i];
3243  MOVStreamContext *msc = avst->priv_data;
3244  if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3245  AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3246  int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3247  av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3248  if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3249  (s->pb->seekable &&
3250  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3251  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3252  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3253  sample = current_sample;
3254  best_dts = dts;
3255  *st = avst;
3256  }
3257  }
3258  }
3259  return sample;
3260 }
3261 
3263 {
3264  MOVContext *mov = s->priv_data;
3265  MOVStreamContext *sc;
3267  AVStream *st = NULL;
3268  int ret;
3269  mov->fc = s;
3270  retry:
3271  sample = mov_find_next_sample(s, &st);
3272  if (!sample) {
3273  mov->found_mdat = 0;
3274  if (!mov->next_root_atom)
3275  return AVERROR_EOF;
3276  avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3277  mov->next_root_atom = 0;
3278  if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3279  url_feof(s->pb))
3280  return AVERROR_EOF;
3281  av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3282  goto retry;
3283  }
3284  sc = st->priv_data;
3285  /* must be done just before reading, to avoid infinite loop on sample */
3286  sc->current_sample++;
3287 
3288  if (st->discard != AVDISCARD_ALL) {
3289  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3290  av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3291  sc->ffindex, sample->pos);
3292  return AVERROR_INVALIDDATA;
3293  }
3294  ret = av_get_packet(sc->pb, pkt, sample->size);
3295  if (ret < 0)
3296  return ret;
3297  if (sc->has_palette) {
3298  uint8_t *pal;
3299 
3301  if (!pal) {
3302  av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3303  } else {
3304  memcpy(pal, sc->palette, AVPALETTE_SIZE);
3305  sc->has_palette = 0;
3306  }
3307  }
3308 #if CONFIG_DV_DEMUXER
3309  if (mov->dv_demux && sc->dv_audio_container) {
3310  avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3311  av_free(pkt->data);
3312  pkt->size = 0;
3313  ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3314  if (ret < 0)
3315  return ret;
3316  }
3317 #endif
3318  }
3319 
3320  pkt->stream_index = sc->ffindex;
3321  pkt->dts = sample->timestamp;
3322  if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3323  pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3324  /* update ctts context */
3325  sc->ctts_sample++;
3326  if (sc->ctts_index < sc->ctts_count &&
3327  sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3328  sc->ctts_index++;
3329  sc->ctts_sample = 0;
3330  }
3331  if (sc->wrong_dts)
3332  pkt->dts = AV_NOPTS_VALUE;
3333  } else {
3334  int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3336  pkt->duration = next_dts - pkt->dts;
3337  pkt->pts = pkt->dts;
3338  }
3339  if (st->discard == AVDISCARD_ALL)
3340  goto retry;
3341  pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3342  pkt->pos = sample->pos;
3343  av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3344  pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3345  return 0;
3346 }
3347 
3348 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3349 {
3350  MOVStreamContext *sc = st->priv_data;
3351  int sample, time_sample;
3352  int i;
3353 
3354  sample = av_index_search_timestamp(st, timestamp, flags);
3355  av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3356  if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3357  sample = 0;
3358  if (sample < 0) /* not sure what to do */
3359  return AVERROR_INVALIDDATA;
3360  sc->current_sample = sample;
3361  av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3362  /* adjust ctts index */
3363  if (sc->ctts_data) {
3364  time_sample = 0;
3365  for (i = 0; i < sc->ctts_count; i++) {
3366  int next = time_sample + sc->ctts_data[i].count;
3367  if (next > sc->current_sample) {
3368  sc->ctts_index = i;
3369  sc->ctts_sample = sc->current_sample - time_sample;
3370  break;
3371  }
3372  time_sample = next;
3373  }
3374  }
3375  return sample;
3376 }
3377 
3378 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3379 {
3380  AVStream *st;
3381  int64_t seek_timestamp, timestamp;
3382  int sample;
3383  int i;
3384 
3385  if (stream_index >= s->nb_streams)
3386  return AVERROR_INVALIDDATA;
3387 
3388  st = s->streams[stream_index];
3389  sample = mov_seek_stream(s, st, sample_time, flags);
3390  if (sample < 0)
3391  return sample;
3392 
3393  /* adjust seek timestamp to found sample timestamp */
3394  seek_timestamp = st->index_entries[sample].timestamp;
3395 
3396  for (i = 0; i < s->nb_streams; i++) {
3397  MOVStreamContext *sc = s->streams[i]->priv_data;
3398  st = s->streams[i];
3399  st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3400 
3401  if (stream_index == i)
3402  continue;
3403 
3404  timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3405  mov_seek_stream(s, st, timestamp, flags);
3406  }
3407  return 0;
3408 }
3409 
3410 static const AVOption options[] = {
3411  {"use_absolute_path",
3412  "allow using absolute path when opening alias, this is a possible security issue",
3413  offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3415  {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3417  {NULL}
3418 };
3419 
3420 static const AVClass class = {
3421  .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3422  .item_name = av_default_item_name,
3423  .option = options,
3425 };
3426 
3428  .name = "mov,mp4,m4a,3gp,3g2,mj2",
3429  .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3430  .priv_data_size = sizeof(MOVContext),
3431  .read_probe = mov_probe,
3436  .priv_class = &class,
3438 };