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