FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 FFmpeg.
10  *
11  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 #include "libavutil/attributes.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
52 #include "avformat.h"
53 #include "internal.h"
54 #include "avio_internal.h"
55 #include "riff.h"
56 #include "isom.h"
57 #include "libavcodec/get_bits.h"
58 #include "id3v1.h"
59 #include "mov_chan.h"
60 #include "replaygain.h"
61 
62 #if CONFIG_ZLIB
63 #include <zlib.h>
64 #endif
65 
66 #include "qtpalette.h"
67 
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
71  uint32_t type;
74 
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 
79  unsigned len, const char *key)
80 {
81  char buf[16];
82 
83  short current, total = 0;
84  avio_rb16(pb); // unknown
85  current = avio_rb16(pb);
86  if (len >= 6)
87  total = avio_rb16(pb);
88  if (!total)
89  snprintf(buf, sizeof(buf), "%d", current);
90  else
91  snprintf(buf, sizeof(buf), "%d/%d", current, total);
93  av_dict_set(&c->fc->metadata, key, buf, 0);
94 
95  return 0;
96 }
97 
99  unsigned len, const char *key)
100 {
101  /* bypass padding bytes */
102  avio_r8(pb);
103  avio_r8(pb);
104  avio_r8(pb);
105 
107  av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
108 
109  return 0;
110 }
111 
113  unsigned len, const char *key)
114 {
116  av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
117 
118  return 0;
119 }
120 
122  unsigned len, const char *key)
123 {
124  short genre;
125 
126  avio_r8(pb); // unknown
127 
128  genre = avio_r8(pb);
129  if (genre < 1 || genre > ID3v1_GENRE_MAX)
130  return 0;
132  av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
133 
134  return 0;
135 }
136 
137 static const uint32_t mac_to_unicode[128] = {
138  0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
139  0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
140  0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
141  0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
142  0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
143  0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
144  0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
145  0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
146  0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
147  0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
148  0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
149  0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
150  0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
151  0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
152  0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
153  0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
154 };
155 
157  char *dst, int dstlen)
158 {
159  char *p = dst;
160  char *end = dst+dstlen-1;
161  int i;
162 
163  for (i = 0; i < len; i++) {
164  uint8_t t, c = avio_r8(pb);
165  if (c < 0x80 && p < end)
166  *p++ = c;
167  else if (p < end)
168  PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
169  }
170  *p = 0;
171  return p - dst;
172 }
173 
174 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
175 {
176  AVPacket pkt;
177  AVStream *st;
178  MOVStreamContext *sc;
179  enum AVCodecID id;
180  int ret;
181 
182  switch (type) {
183  case 0xd: id = AV_CODEC_ID_MJPEG; break;
184  case 0xe: id = AV_CODEC_ID_PNG; break;
185  case 0x1b: id = AV_CODEC_ID_BMP; break;
186  default:
187  av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
188  avio_skip(pb, len);
189  return 0;
190  }
191 
192  st = avformat_new_stream(c->fc, NULL);
193  if (!st)
194  return AVERROR(ENOMEM);
195  sc = av_mallocz(sizeof(*sc));
196  if (!sc)
197  return AVERROR(ENOMEM);
198  st->priv_data = sc;
199 
200  ret = av_get_packet(pb, &pkt, len);
201  if (ret < 0)
202  return ret;
203 
204  if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
205  if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
206  id = AV_CODEC_ID_PNG;
207  } else {
208  id = AV_CODEC_ID_MJPEG;
209  }
210  }
211 
213 
214  st->attached_pic = pkt;
215  st->attached_pic.stream_index = st->index;
217 
219  st->codecpar->codec_id = id;
220 
221  return 0;
222 }
223 
224 // 3GPP TS 26.244
225 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
226 {
227  char language[4] = { 0 };
228  char buf[200], place[100];
229  uint16_t langcode = 0;
230  double longitude, latitude, altitude;
231  const char *key = "location";
232 
233  if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
234  av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
235  return AVERROR_INVALIDDATA;
236  }
237 
238  avio_skip(pb, 4); // version+flags
239  langcode = avio_rb16(pb);
240  ff_mov_lang_to_iso639(langcode, language);
241  len -= 6;
242 
243  len -= avio_get_str(pb, len, place, sizeof(place));
244  if (len < 1) {
245  av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
246  return AVERROR_INVALIDDATA;
247  }
248  avio_skip(pb, 1); // role
249  len -= 1;
250 
251  if (len < 12) {
252  av_log(c->fc, AV_LOG_ERROR,
253  "loci too short (%u bytes left, need at least %d)\n", len, 12);
254  return AVERROR_INVALIDDATA;
255  }
256  longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
257  latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
258  altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
259 
260  // Try to output in the same format as the ?xyz field
261  snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
262  if (altitude)
263  av_strlcatf(buf, sizeof(buf), "%+f", altitude);
264  av_strlcatf(buf, sizeof(buf), "/%s", place);
265 
266  if (*language && strcmp(language, "und")) {
267  char key2[16];
268  snprintf(key2, sizeof(key2), "%s-%s", key, language);
269  av_dict_set(&c->fc->metadata, key2, buf, 0);
270  }
272  return av_dict_set(&c->fc->metadata, key, buf, 0);
273 }
274 
275 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
276 {
277  int i, n_hmmt;
278 
279  if (len < 2)
280  return 0;
281  if (c->ignore_chapters)
282  return 0;
283 
284  n_hmmt = avio_rb32(pb);
285  for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
286  int moment_time = avio_rb32(pb);
287  avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
288  }
289  return 0;
290 }
291 
293 {
294  char tmp_key[5];
295  char key2[32], language[4] = {0};
296  char *str = NULL;
297  const char *key = NULL;
298  uint16_t langcode = 0;
299  uint32_t data_type = 0, str_size, str_size_alloc;
300  int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
301  int raw = 0;
302  int num = 0;
303 
304  switch (atom.type) {
305  case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
306  case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
307  case MKTAG( 'X','M','P','_'):
308  if (c->export_xmp) { key = "xmp"; raw = 1; } break;
309  case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
310  case MKTAG( 'a','k','I','D'): key = "account_type";
312  case MKTAG( 'a','p','I','D'): key = "account_id"; break;
313  case MKTAG( 'c','a','t','g'): key = "category"; break;
314  case MKTAG( 'c','p','i','l'): key = "compilation";
316  case MKTAG( 'c','p','r','t'): key = "copyright"; break;
317  case MKTAG( 'd','e','s','c'): key = "description"; break;
318  case MKTAG( 'd','i','s','k'): key = "disc";
320  case MKTAG( 'e','g','i','d'): key = "episode_uid";
322  case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
323  case MKTAG( 'g','n','r','e'): key = "genre";
324  parse = mov_metadata_gnre; break;
325  case MKTAG( 'h','d','v','d'): key = "hd_video";
327  case MKTAG( 'H','M','M','T'):
328  return mov_metadata_hmmt(c, pb, atom.size);
329  case MKTAG( 'k','e','y','w'): key = "keywords"; break;
330  case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
331  case MKTAG( 'l','o','c','i'):
332  return mov_metadata_loci(c, pb, atom.size);
333  case MKTAG( 'p','c','s','t'): key = "podcast";
335  case MKTAG( 'p','g','a','p'): key = "gapless_playback";
337  case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
338  case MKTAG( 'r','t','n','g'): key = "rating";
340  case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
341  case MKTAG( 's','o','a','l'): key = "sort_album"; break;
342  case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
343  case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
344  case MKTAG( 's','o','n','m'): key = "sort_name"; break;
345  case MKTAG( 's','o','s','n'): key = "sort_show"; break;
346  case MKTAG( 's','t','i','k'): key = "media_type";
348  case MKTAG( 't','r','k','n'): key = "track";
350  case MKTAG( 't','v','e','n'): key = "episode_id"; break;
351  case MKTAG( 't','v','e','s'): key = "episode_sort";
353  case MKTAG( 't','v','n','n'): key = "network"; break;
354  case MKTAG( 't','v','s','h'): key = "show"; break;
355  case MKTAG( 't','v','s','n'): key = "season_number";
357  case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
358  case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
359  case MKTAG(0xa9,'a','l','b'): key = "album"; break;
360  case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
361  case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
362  case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
363  case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
364  case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
365  case MKTAG(0xa9,'d','a','y'): key = "date"; break;
366  case MKTAG(0xa9,'d','i','r'): key = "director"; break;
367  case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
368  case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
369  case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
370  case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
371  case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
372  case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
373  case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
374  case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
375  case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
376  case MKTAG(0xa9,'m','a','k'): key = "make"; break;
377  case MKTAG(0xa9,'m','o','d'): key = "model"; break;
378  case MKTAG(0xa9,'n','a','m'): key = "title"; break;
379  case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
380  case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
381  case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
382  case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
383  case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
384  case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
385  case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
386  case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
387  case MKTAG(0xa9,'t','r','k'): key = "track"; break;
388  case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
389  case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
390  case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
391  case MKTAG(0xa9,'x','y','z'): key = "location"; break;
392  }
393 retry:
394  if (c->itunes_metadata && atom.size > 8) {
395  int data_size = avio_rb32(pb);
396  int tag = avio_rl32(pb);
397  if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
398  data_type = avio_rb32(pb); // type
399  avio_rb32(pb); // unknown
400  str_size = data_size - 16;
401  atom.size -= 16;
402 
403  if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
404  int ret = mov_read_covr(c, pb, data_type, str_size);
405  if (ret < 0) {
406  av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
407  }
408  return ret;
409  } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
410  uint32_t index = AV_RB32(&atom.type);
411  if (index < c->meta_keys_count && index > 0) {
412  key = c->meta_keys[index];
413  } else {
415  "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
416  index, c->meta_keys_count);
417  }
418  }
419  } else return 0;
420  } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
421  str_size = avio_rb16(pb); // string length
422  if (str_size > atom.size) {
423  raw = 1;
424  avio_seek(pb, -2, SEEK_CUR);
425  av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
426  goto retry;
427  }
428  langcode = avio_rb16(pb);
429  ff_mov_lang_to_iso639(langcode, language);
430  atom.size -= 4;
431  } else
432  str_size = atom.size;
433 
434  if (c->export_all && !key) {
435  snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
436  key = tmp_key;
437  }
438 
439  if (!key)
440  return 0;
441  if (atom.size < 0 || str_size >= INT_MAX/2)
442  return AVERROR_INVALIDDATA;
443 
444  // Allocates enough space if data_type is a int32 or float32 number, otherwise
445  // worst-case requirement for output string in case of utf8 coded input
446  num = (data_type >= 21 && data_type <= 23);
447  str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
448  str = av_mallocz(str_size_alloc);
449  if (!str)
450  return AVERROR(ENOMEM);
451 
452  if (parse)
453  parse(c, pb, str_size, key);
454  else {
455  if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
456  mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
457  } else if (data_type == 21) { // BE signed integer, variable size
458  int val = 0;
459  if (str_size == 1)
460  val = (int8_t)avio_r8(pb);
461  else if (str_size == 2)
462  val = (int16_t)avio_rb16(pb);
463  else if (str_size == 3)
464  val = ((int32_t)(avio_rb24(pb)<<8))>>8;
465  else if (str_size == 4)
466  val = (int32_t)avio_rb32(pb);
467  if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
468  av_log(c->fc, AV_LOG_ERROR,
469  "Failed to store the number (%d) in string.\n", val);
470  av_free(str);
471  return AVERROR_INVALIDDATA;
472  }
473  } else if (data_type == 22) { // BE unsigned integer, variable size
474  unsigned int val = 0;
475  if (str_size == 1)
476  val = avio_r8(pb);
477  else if (str_size == 2)
478  val = avio_rb16(pb);
479  else if (str_size == 3)
480  val = avio_rb24(pb);
481  else if (str_size == 4)
482  val = avio_rb32(pb);
483  if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
484  av_log(c->fc, AV_LOG_ERROR,
485  "Failed to store the number (%u) in string.\n", val);
486  av_free(str);
487  return AVERROR_INVALIDDATA;
488  }
489  } else if (data_type == 23 && str_size >= 4) { // BE float32
490  float val = av_int2float(avio_rb32(pb));
491  if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
492  av_log(c->fc, AV_LOG_ERROR,
493  "Failed to store the float32 number (%f) in string.\n", val);
494  av_free(str);
495  return AVERROR_INVALIDDATA;
496  }
497  } else {
498  int ret = ffio_read_size(pb, str, str_size);
499  if (ret < 0) {
500  av_free(str);
501  return ret;
502  }
503  str[str_size] = 0;
504  }
506  av_dict_set(&c->fc->metadata, key, str, 0);
507  if (*language && strcmp(language, "und")) {
508  snprintf(key2, sizeof(key2), "%s-%s", key, language);
509  av_dict_set(&c->fc->metadata, key2, str, 0);
510  }
511  if (!strcmp(key, "encoder")) {
512  int major, minor, micro;
513  if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
514  c->handbrake_version = 1000000*major + 1000*minor + micro;
515  }
516  }
517  }
518 
519  av_freep(&str);
520  return 0;
521 }
522 
524 {
525  int64_t start;
526  int i, nb_chapters, str_len, version;
527  char str[256+1];
528  int ret;
529 
530  if (c->ignore_chapters)
531  return 0;
532 
533  if ((atom.size -= 5) < 0)
534  return 0;
535 
536  version = avio_r8(pb);
537  avio_rb24(pb);
538  if (version)
539  avio_rb32(pb); // ???
540  nb_chapters = avio_r8(pb);
541 
542  for (i = 0; i < nb_chapters; i++) {
543  if (atom.size < 9)
544  return 0;
545 
546  start = avio_rb64(pb);
547  str_len = avio_r8(pb);
548 
549  if ((atom.size -= 9+str_len) < 0)
550  return 0;
551 
552  ret = ffio_read_size(pb, str, str_len);
553  if (ret < 0)
554  return ret;
555  str[str_len] = 0;
556  avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
557  }
558  return 0;
559 }
560 
561 #define MIN_DATA_ENTRY_BOX_SIZE 12
563 {
564  AVStream *st;
565  MOVStreamContext *sc;
566  int entries, i, j;
567 
568  if (c->fc->nb_streams < 1)
569  return 0;
570  st = c->fc->streams[c->fc->nb_streams-1];
571  sc = st->priv_data;
572 
573  avio_rb32(pb); // version + flags
574  entries = avio_rb32(pb);
575  if (!entries ||
576  entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
577  entries >= UINT_MAX / sizeof(*sc->drefs))
578  return AVERROR_INVALIDDATA;
579  sc->drefs_count = 0;
580  av_free(sc->drefs);
581  sc->drefs_count = 0;
582  sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
583  if (!sc->drefs)
584  return AVERROR(ENOMEM);
585  sc->drefs_count = entries;
586 
587  for (i = 0; i < entries; i++) {
588  MOVDref *dref = &sc->drefs[i];
589  uint32_t size = avio_rb32(pb);
590  int64_t next = avio_tell(pb) + size - 4;
591 
592  if (size < 12)
593  return AVERROR_INVALIDDATA;
594 
595  dref->type = avio_rl32(pb);
596  avio_rb32(pb); // version + flags
597 
598  if (dref->type == MKTAG('a','l','i','s') && size > 150) {
599  /* macintosh alias record */
600  uint16_t volume_len, len;
601  int16_t type;
602  int ret;
603 
604  avio_skip(pb, 10);
605 
606  volume_len = avio_r8(pb);
607  volume_len = FFMIN(volume_len, 27);
608  ret = ffio_read_size(pb, dref->volume, 27);
609  if (ret < 0)
610  return ret;
611  dref->volume[volume_len] = 0;
612  av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
613 
614  avio_skip(pb, 12);
615 
616  len = avio_r8(pb);
617  len = FFMIN(len, 63);
618  ret = ffio_read_size(pb, dref->filename, 63);
619  if (ret < 0)
620  return ret;
621  dref->filename[len] = 0;
622  av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
623 
624  avio_skip(pb, 16);
625 
626  /* read next level up_from_alias/down_to_target */
627  dref->nlvl_from = avio_rb16(pb);
628  dref->nlvl_to = avio_rb16(pb);
629  av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
630  dref->nlvl_from, dref->nlvl_to);
631 
632  avio_skip(pb, 16);
633 
634  for (type = 0; type != -1 && avio_tell(pb) < next; ) {
635  if(avio_feof(pb))
636  return AVERROR_EOF;
637  type = avio_rb16(pb);
638  len = avio_rb16(pb);
639  av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
640  if (len&1)
641  len += 1;
642  if (type == 2) { // absolute path
643  av_free(dref->path);
644  dref->path = av_mallocz(len+1);
645  if (!dref->path)
646  return AVERROR(ENOMEM);
647 
648  ret = ffio_read_size(pb, dref->path, len);
649  if (ret < 0) {
650  av_freep(&dref->path);
651  return ret;
652  }
653  if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
654  len -= volume_len;
655  memmove(dref->path, dref->path+volume_len, len);
656  dref->path[len] = 0;
657  }
658  // trim string of any ending zeros
659  for (j = len - 1; j >= 0; j--) {
660  if (dref->path[j] == 0)
661  len--;
662  else
663  break;
664  }
665  for (j = 0; j < len; j++)
666  if (dref->path[j] == ':' || dref->path[j] == 0)
667  dref->path[j] = '/';
668  av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
669  } else if (type == 0) { // directory name
670  av_free(dref->dir);
671  dref->dir = av_malloc(len+1);
672  if (!dref->dir)
673  return AVERROR(ENOMEM);
674 
675  ret = ffio_read_size(pb, dref->dir, len);
676  if (ret < 0) {
677  av_freep(&dref->dir);
678  return ret;
679  }
680  dref->dir[len] = 0;
681  for (j = 0; j < len; j++)
682  if (dref->dir[j] == ':')
683  dref->dir[j] = '/';
684  av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
685  } else
686  avio_skip(pb, len);
687  }
688  } else {
689  av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
690  dref->type, size);
691  entries--;
692  i--;
693  }
694  avio_seek(pb, next, SEEK_SET);
695  }
696  return 0;
697 }
698 
700 {
701  AVStream *st;
702  uint32_t type;
703  uint32_t ctype;
704  int64_t title_size;
705  char *title_str;
706  int ret;
707 
708  avio_r8(pb); /* version */
709  avio_rb24(pb); /* flags */
710 
711  /* component type */
712  ctype = avio_rl32(pb);
713  type = avio_rl32(pb); /* component subtype */
714 
715  av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
716  av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
717 
718  if (c->trak_index < 0) { // meta not inside a trak
719  if (type == MKTAG('m','d','t','a')) {
720  c->found_hdlr_mdta = 1;
721  }
722  return 0;
723  }
724 
725  st = c->fc->streams[c->fc->nb_streams-1];
726 
727  if (type == MKTAG('v','i','d','e'))
729  else if (type == MKTAG('s','o','u','n'))
731  else if (type == MKTAG('m','1','a',' '))
733  else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
735 
736  avio_rb32(pb); /* component manufacture */
737  avio_rb32(pb); /* component flags */
738  avio_rb32(pb); /* component flags mask */
739 
740  title_size = atom.size - 24;
741  if (title_size > 0) {
742  if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
743  return AVERROR_INVALIDDATA;
744  title_str = av_malloc(title_size + 1); /* Add null terminator */
745  if (!title_str)
746  return AVERROR(ENOMEM);
747 
748  ret = ffio_read_size(pb, title_str, title_size);
749  if (ret < 0) {
750  av_freep(&title_str);
751  return ret;
752  }
753  title_str[title_size] = 0;
754  if (title_str[0]) {
755  int off = (!c->isom && title_str[0] == title_size - 1);
756  av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
757  }
758  av_freep(&title_str);
759  }
760 
761  return 0;
762 }
763 
765 {
766  AVStream *st;
767  int tag;
768 
769  if (fc->nb_streams < 1)
770  return 0;
771  st = fc->streams[fc->nb_streams-1];
772 
773  avio_rb32(pb); /* version + flags */
774  ff_mp4_read_descr(fc, pb, &tag);
775  if (tag == MP4ESDescrTag) {
777  } else
778  avio_rb16(pb); /* ID */
779 
780  ff_mp4_read_descr(fc, pb, &tag);
781  if (tag == MP4DecConfigDescrTag)
782  ff_mp4_read_dec_config_descr(fc, st, pb);
783  return 0;
784 }
785 
787 {
788  return ff_mov_read_esds(c->fc, pb);
789 }
790 
792 {
793  AVStream *st;
794  enum AVAudioServiceType *ast;
795  int ac3info, acmod, lfeon, bsmod;
796 
797  if (c->fc->nb_streams < 1)
798  return 0;
799  st = c->fc->streams[c->fc->nb_streams-1];
800 
802  sizeof(*ast));
803  if (!ast)
804  return AVERROR(ENOMEM);
805 
806  ac3info = avio_rb24(pb);
807  bsmod = (ac3info >> 14) & 0x7;
808  acmod = (ac3info >> 11) & 0x7;
809  lfeon = (ac3info >> 10) & 0x1;
810  st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
812  if (lfeon)
814  *ast = bsmod;
815  if (st->codecpar->channels > 1 && bsmod == 0x7)
817 
818 #if FF_API_LAVF_AVCTX
820  st->codec->audio_service_type = *ast;
822 #endif
823 
824  return 0;
825 }
826 
828 {
829  AVStream *st;
830  enum AVAudioServiceType *ast;
831  int eac3info, acmod, lfeon, bsmod;
832 
833  if (c->fc->nb_streams < 1)
834  return 0;
835  st = c->fc->streams[c->fc->nb_streams-1];
836 
838  sizeof(*ast));
839  if (!ast)
840  return AVERROR(ENOMEM);
841 
842  /* No need to parse fields for additional independent substreams and its
843  * associated dependent substreams since libavcodec's E-AC-3 decoder
844  * does not support them yet. */
845  avio_rb16(pb); /* data_rate and num_ind_sub */
846  eac3info = avio_rb24(pb);
847  bsmod = (eac3info >> 12) & 0x1f;
848  acmod = (eac3info >> 9) & 0x7;
849  lfeon = (eac3info >> 8) & 0x1;
851  if (lfeon)
854  *ast = bsmod;
855  if (st->codecpar->channels > 1 && bsmod == 0x7)
857 
858 #if FF_API_LAVF_AVCTX
860  st->codec->audio_service_type = *ast;
862 #endif
863 
864  return 0;
865 }
866 
868 {
869  const uint32_t ddts_size = 20;
870  AVStream *st = NULL;
871  uint8_t *buf = NULL;
872  uint32_t frame_duration_code = 0;
873  uint32_t channel_layout_code = 0;
874  GetBitContext gb;
875 
876  buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
877  if (!buf) {
878  return AVERROR(ENOMEM);
879  }
880  if (avio_read(pb, buf, ddts_size) < ddts_size) {
881  av_free(buf);
882  return AVERROR_INVALIDDATA;
883  }
884 
885  init_get_bits(&gb, buf, 8*ddts_size);
886 
887  if (c->fc->nb_streams < 1) {
888  return 0;
889  }
890  st = c->fc->streams[c->fc->nb_streams-1];
891 
892  st->codecpar->sample_rate = get_bits_long(&gb, 32);
893  if (st->codecpar->sample_rate <= 0) {
894  av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
895  return AVERROR_INVALIDDATA;
896  }
897  skip_bits_long(&gb, 32); /* max bitrate */
898  st->codecpar->bit_rate = get_bits_long(&gb, 32);
899  st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
900  frame_duration_code = get_bits(&gb, 2);
901  skip_bits(&gb, 30); /* various fields */
902  channel_layout_code = get_bits(&gb, 16);
903 
904  st->codecpar->frame_size =
905  (frame_duration_code == 0) ? 512 :
906  (frame_duration_code == 1) ? 1024 :
907  (frame_duration_code == 2) ? 2048 :
908  (frame_duration_code == 3) ? 4096 : 0;
909 
910  if (channel_layout_code > 0xff) {
911  av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
912  }
913  st->codecpar->channel_layout =
914  ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
915  ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
916  ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
917  ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
918  ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
919  ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
920 
922 
923  return 0;
924 }
925 
927 {
928  AVStream *st;
929 
930  if (c->fc->nb_streams < 1)
931  return 0;
932  st = c->fc->streams[c->fc->nb_streams-1];
933 
934  if (atom.size < 16)
935  return 0;
936 
937  /* skip version and flags */
938  avio_skip(pb, 4);
939 
940  ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
941 
942  return 0;
943 }
944 
946 {
947  AVStream *st;
948  int ret;
949 
950  if (c->fc->nb_streams < 1)
951  return 0;
952  st = c->fc->streams[c->fc->nb_streams-1];
953 
954  if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
955  av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
956 
957  return ret;
958 }
959 
961 {
962  const int num = avio_rb32(pb);
963  const int den = avio_rb32(pb);
964  AVStream *st;
965 
966  if (c->fc->nb_streams < 1)
967  return 0;
968  st = c->fc->streams[c->fc->nb_streams-1];
969 
970  if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
971  (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
973  "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
975  num, den);
976  } else if (den != 0) {
978  num, den, 32767);
979  }
980  return 0;
981 }
982 
983 /* this atom contains actual media data */
985 {
986  if (atom.size == 0) /* wrong one (MP4) */
987  return 0;
988  c->found_mdat=1;
989  return 0; /* now go for moov */
990 }
991 
992 #define DRM_BLOB_SIZE 56
993 
995 {
996  uint8_t intermediate_key[20];
997  uint8_t intermediate_iv[20];
998  uint8_t input[64];
999  uint8_t output[64];
1000  uint8_t file_checksum[20];
1001  uint8_t calculated_checksum[20];
1002  struct AVSHA *sha;
1003  int i;
1004  int ret = 0;
1005  uint8_t *activation_bytes = c->activation_bytes;
1006  uint8_t *fixed_key = c->audible_fixed_key;
1007 
1008  c->aax_mode = 1;
1009 
1010  sha = av_sha_alloc();
1011  if (!sha)
1012  return AVERROR(ENOMEM);
1013  c->aes_decrypt = av_aes_alloc();
1014  if (!c->aes_decrypt) {
1015  ret = AVERROR(ENOMEM);
1016  goto fail;
1017  }
1018 
1019  /* drm blob processing */
1020  avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1021  avio_read(pb, input, DRM_BLOB_SIZE);
1022  avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1023  avio_read(pb, file_checksum, 20);
1024 
1025  av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1026  for (i = 0; i < 20; i++)
1027  av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1028  av_log(c->fc, AV_LOG_INFO, "\n");
1029 
1030  /* verify activation data */
1031  if (!activation_bytes) {
1032  av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1033  ret = 0; /* allow ffprobe to continue working on .aax files */
1034  goto fail;
1035  }
1036  if (c->activation_bytes_size != 4) {
1037  av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1038  ret = AVERROR(EINVAL);
1039  goto fail;
1040  }
1041 
1042  /* verify fixed key */
1043  if (c->audible_fixed_key_size != 16) {
1044  av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1045  ret = AVERROR(EINVAL);
1046  goto fail;
1047  }
1048 
1049  /* AAX (and AAX+) key derivation */
1050  av_sha_init(sha, 160);
1051  av_sha_update(sha, fixed_key, 16);
1052  av_sha_update(sha, activation_bytes, 4);
1053  av_sha_final(sha, intermediate_key);
1054  av_sha_init(sha, 160);
1055  av_sha_update(sha, fixed_key, 16);
1056  av_sha_update(sha, intermediate_key, 20);
1057  av_sha_update(sha, activation_bytes, 4);
1058  av_sha_final(sha, intermediate_iv);
1059  av_sha_init(sha, 160);
1060  av_sha_update(sha, intermediate_key, 16);
1061  av_sha_update(sha, intermediate_iv, 16);
1062  av_sha_final(sha, calculated_checksum);
1063  if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1064  av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1065  ret = AVERROR_INVALIDDATA;
1066  goto fail;
1067  }
1068  av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1069  av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1070  for (i = 0; i < 4; i++) {
1071  // file data (in output) is stored in big-endian mode
1072  if (activation_bytes[i] != output[3 - i]) { // critical error
1073  av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1074  ret = AVERROR_INVALIDDATA;
1075  goto fail;
1076  }
1077  }
1078  memcpy(c->file_key, output + 8, 16);
1079  memcpy(input, output + 26, 16);
1080  av_sha_init(sha, 160);
1081  av_sha_update(sha, input, 16);
1082  av_sha_update(sha, c->file_key, 16);
1083  av_sha_update(sha, fixed_key, 16);
1084  av_sha_final(sha, c->file_iv);
1085 
1086 fail:
1087  av_free(sha);
1088 
1089  return ret;
1090 }
1091 
1092 // Audible AAX (and AAX+) bytestream decryption
1093 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1094 {
1095  int blocks = 0;
1096  unsigned char iv[16];
1097 
1098  memcpy(iv, c->file_iv, 16); // iv is overwritten
1099  blocks = size >> 4; // trailing bytes are not encrypted!
1100  av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1101  av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1102 
1103  return 0;
1104 }
1105 
1106 /* read major brand, minor version and compatible brands and store them as metadata */
1108 {
1109  uint32_t minor_ver;
1110  int comp_brand_size;
1111  char* comp_brands_str;
1112  uint8_t type[5] = {0};
1113  int ret = ffio_read_size(pb, type, 4);
1114  if (ret < 0)
1115  return ret;
1116 
1117  if (strcmp(type, "qt "))
1118  c->isom = 1;
1119  av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1120  av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1121  minor_ver = avio_rb32(pb); /* minor version */
1122  av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1123 
1124  comp_brand_size = atom.size - 8;
1125  if (comp_brand_size < 0)
1126  return AVERROR_INVALIDDATA;
1127  comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1128  if (!comp_brands_str)
1129  return AVERROR(ENOMEM);
1130 
1131  ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1132  if (ret < 0) {
1133  av_freep(&comp_brands_str);
1134  return ret;
1135  }
1136  comp_brands_str[comp_brand_size] = 0;
1137  av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1138  av_freep(&comp_brands_str);
1139 
1140  return 0;
1141 }
1142 
1143 /* this atom should contain all header atoms */
1145 {
1146  int ret;
1147 
1148  if (c->found_moov) {
1149  av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1150  avio_skip(pb, atom.size);
1151  return 0;
1152  }
1153 
1154  if ((ret = mov_read_default(c, pb, atom)) < 0)
1155  return ret;
1156  /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1157  /* so we don't parse the whole file if over a network */
1158  c->found_moov=1;
1159  return 0; /* now go for mdat */
1160 }
1161 
1163 {
1164  if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1165  c->has_looked_for_mfra = 1;
1166  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1167  int ret;
1168  av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1169  "for a mfra\n");
1170  if ((ret = mov_read_mfra(c, pb)) < 0) {
1171  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1172  "read the mfra (may be a live ismv)\n");
1173  }
1174  } else {
1175  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1176  "seekable, can not look for mfra\n");
1177  }
1178  }
1180  av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1181  return mov_read_default(c, pb, atom);
1182 }
1183 
1184 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1185 {
1186  if (time) {
1187  if(time >= 2082844800)
1188  time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1189 
1190  if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1191  av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1192  return;
1193  }
1194 
1195  avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1196  }
1197 }
1198 
1200 {
1201  AVStream *st;
1202  MOVStreamContext *sc;
1203  int version;
1204  char language[4] = {0};
1205  unsigned lang;
1206  int64_t creation_time;
1207 
1208  if (c->fc->nb_streams < 1)
1209  return 0;
1210  st = c->fc->streams[c->fc->nb_streams-1];
1211  sc = st->priv_data;
1212 
1213  if (sc->time_scale) {
1214  av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1215  return AVERROR_INVALIDDATA;
1216  }
1217 
1218  version = avio_r8(pb);
1219  if (version > 1) {
1220  avpriv_request_sample(c->fc, "Version %d", version);
1221  return AVERROR_PATCHWELCOME;
1222  }
1223  avio_rb24(pb); /* flags */
1224  if (version == 1) {
1225  creation_time = avio_rb64(pb);
1226  avio_rb64(pb);
1227  } else {
1228  creation_time = avio_rb32(pb);
1229  avio_rb32(pb); /* modification time */
1230  }
1231  mov_metadata_creation_time(&st->metadata, creation_time);
1232 
1233  sc->time_scale = avio_rb32(pb);
1234  if (sc->time_scale <= 0) {
1235  av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d\n", sc->time_scale);
1236  return AVERROR_INVALIDDATA;
1237  }
1238  st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1239 
1240  lang = avio_rb16(pb); /* language */
1241  if (ff_mov_lang_to_iso639(lang, language))
1242  av_dict_set(&st->metadata, "language", language, 0);
1243  avio_rb16(pb); /* quality */
1244 
1245  return 0;
1246 }
1247 
1249 {
1250  int i;
1251  int64_t creation_time;
1252  int version = avio_r8(pb); /* version */
1253  avio_rb24(pb); /* flags */
1254 
1255  if (version == 1) {
1256  creation_time = avio_rb64(pb);
1257  avio_rb64(pb);
1258  } else {
1259  creation_time = avio_rb32(pb);
1260  avio_rb32(pb); /* modification time */
1261  }
1262  mov_metadata_creation_time(&c->fc->metadata, creation_time);
1263  c->time_scale = avio_rb32(pb); /* time scale */
1264  if (c->time_scale <= 0) {
1265  av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d\n", c->time_scale);
1266  return AVERROR_INVALIDDATA;
1267  }
1268  av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1269 
1270  c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1271  // set the AVCodecContext duration because the duration of individual tracks
1272  // may be inaccurate
1273  if (c->time_scale > 0 && !c->trex_data)
1275  avio_rb32(pb); /* preferred scale */
1276 
1277  avio_rb16(pb); /* preferred volume */
1278 
1279  avio_skip(pb, 10); /* reserved */
1280 
1281  /* movie display matrix, store it in main context and use it later on */
1282  for (i = 0; i < 3; i++) {
1283  c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1284  c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1285  c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1286  }
1287 
1288  avio_rb32(pb); /* preview time */
1289  avio_rb32(pb); /* preview duration */
1290  avio_rb32(pb); /* poster time */
1291  avio_rb32(pb); /* selection time */
1292  avio_rb32(pb); /* selection duration */
1293  avio_rb32(pb); /* current time */
1294  avio_rb32(pb); /* next track ID */
1295 
1296  return 0;
1297 }
1298 
1300 {
1301  AVStream *st;
1302  int little_endian;
1303 
1304  if (c->fc->nb_streams < 1)
1305  return 0;
1306  st = c->fc->streams[c->fc->nb_streams-1];
1307 
1308  little_endian = avio_rb16(pb) & 0xFF;
1309  av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1310  if (little_endian == 1) {
1311  switch (st->codecpar->codec_id) {
1312  case AV_CODEC_ID_PCM_S24BE:
1314  break;
1315  case AV_CODEC_ID_PCM_S32BE:
1317  break;
1318  case AV_CODEC_ID_PCM_F32BE:
1320  break;
1321  case AV_CODEC_ID_PCM_F64BE:
1323  break;
1324  default:
1325  break;
1326  }
1327  }
1328  return 0;
1329 }
1330 
1332 {
1333  AVStream *st;
1334  char color_parameter_type[5] = { 0 };
1335  uint16_t color_primaries, color_trc, color_matrix;
1336  int ret;
1337 
1338  if (c->fc->nb_streams < 1)
1339  return 0;
1340  st = c->fc->streams[c->fc->nb_streams - 1];
1341 
1342  ret = ffio_read_size(pb, color_parameter_type, 4);
1343  if (ret < 0)
1344  return ret;
1345  if (strncmp(color_parameter_type, "nclx", 4) &&
1346  strncmp(color_parameter_type, "nclc", 4)) {
1347  av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1348  color_parameter_type);
1349  return 0;
1350  }
1351 
1352  color_primaries = avio_rb16(pb);
1353  color_trc = avio_rb16(pb);
1354  color_matrix = avio_rb16(pb);
1355 
1356  av_log(c->fc, AV_LOG_TRACE,
1357  "%s: pri %d trc %d matrix %d",
1358  color_parameter_type, color_primaries, color_trc, color_matrix);
1359 
1360  if (!strncmp(color_parameter_type, "nclx", 4)) {
1361  uint8_t color_range = avio_r8(pb) >> 7;
1362  av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1363  if (color_range)
1365  else
1367  }
1368 
1369  if (!av_color_primaries_name(color_primaries))
1370  color_primaries = AVCOL_PRI_UNSPECIFIED;
1371  if (!av_color_transfer_name(color_trc))
1372  color_trc = AVCOL_TRC_UNSPECIFIED;
1373  if (!av_color_space_name(color_matrix))
1374  color_matrix = AVCOL_SPC_UNSPECIFIED;
1375 
1377  st->codecpar->color_trc = color_trc;
1378  st->codecpar->color_space = color_matrix;
1379  av_log(c->fc, AV_LOG_TRACE, "\n");
1380 
1381  return 0;
1382 }
1383 
1385 {
1386  AVStream *st;
1387  unsigned mov_field_order;
1388  enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1389 
1390  if (c->fc->nb_streams < 1) // will happen with jp2 files
1391  return 0;
1392  st = c->fc->streams[c->fc->nb_streams-1];
1393  if (atom.size < 2)
1394  return AVERROR_INVALIDDATA;
1395  mov_field_order = avio_rb16(pb);
1396  if ((mov_field_order & 0xFF00) == 0x0100)
1397  decoded_field_order = AV_FIELD_PROGRESSIVE;
1398  else if ((mov_field_order & 0xFF00) == 0x0200) {
1399  switch (mov_field_order & 0xFF) {
1400  case 0x01: decoded_field_order = AV_FIELD_TT;
1401  break;
1402  case 0x06: decoded_field_order = AV_FIELD_BB;
1403  break;
1404  case 0x09: decoded_field_order = AV_FIELD_TB;
1405  break;
1406  case 0x0E: decoded_field_order = AV_FIELD_BT;
1407  break;
1408  }
1409  }
1410  if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1411  av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1412  }
1413  st->codecpar->field_order = decoded_field_order;
1414 
1415  return 0;
1416 }
1417 
1419 {
1420  int err = 0;
1421  uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1422  if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1423  return AVERROR_INVALIDDATA;
1424  if ((err = av_reallocp(&par->extradata, size)) < 0) {
1425  par->extradata_size = 0;
1426  return err;
1427  }
1429  return 0;
1430 }
1431 
1432 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1434  AVCodecParameters *par, uint8_t *buf)
1435 {
1436  int64_t result = atom.size;
1437  int err;
1438 
1439  AV_WB32(buf , atom.size + 8);
1440  AV_WL32(buf + 4, atom.type);
1441  err = ffio_read_size(pb, buf + 8, atom.size);
1442  if (err < 0) {
1443  par->extradata_size -= atom.size;
1444  return err;
1445  } else if (err < atom.size) {
1446  av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1447  par->extradata_size -= atom.size - err;
1448  result = err;
1449  }
1450  memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1451  return result;
1452 }
1453 
1454 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1456  enum AVCodecID codec_id)
1457 {
1458  AVStream *st;
1459  uint64_t original_size;
1460  int err;
1461 
1462  if (c->fc->nb_streams < 1) // will happen with jp2 files
1463  return 0;
1464  st = c->fc->streams[c->fc->nb_streams-1];
1465 
1466  if (st->codecpar->codec_id != codec_id)
1467  return 0; /* unexpected codec_id - don't mess with extradata */
1468 
1469  original_size = st->codecpar->extradata_size;
1470  err = mov_realloc_extradata(st->codecpar, atom);
1471  if (err)
1472  return err;
1473 
1474  err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1475  if (err < 0)
1476  return err;
1477  return 0; // Note: this is the original behavior to ignore truncation.
1478 }
1479 
1480 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1482 {
1483  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1484 }
1485 
1487 {
1488  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1489 }
1490 
1492 {
1493  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1494 }
1495 
1497 {
1498  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1499 }
1500 
1502 {
1503  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1504  if(ret == 0)
1505  ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1506  return ret;
1507 }
1508 
1510 {
1511  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1512 
1513  if (!ret && c->fc->nb_streams >= 1) {
1514  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1515  if (par->extradata_size >= 40) {
1516  par->height = AV_RB16(&par->extradata[36]);
1517  par->width = AV_RB16(&par->extradata[38]);
1518  }
1519  }
1520  return ret;
1521 }
1522 
1524 {
1525  if (c->fc->nb_streams >= 1) {
1526  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1527  if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1528  par->codec_id == AV_CODEC_ID_H264 &&
1529  atom.size > 11) {
1530  int cid;
1531  avio_skip(pb, 10);
1532  cid = avio_rb16(pb);
1533  /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1534  if (cid == 0xd4d || cid == 0xd4e)
1535  par->width = 1440;
1536  return 0;
1537  } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1538  par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1539  atom.size >= 24) {
1540  int num, den;
1541  avio_skip(pb, 12);
1542  num = avio_rb32(pb);
1543  den = avio_rb32(pb);
1544  if (num <= 0 || den <= 0)
1545  return 0;
1546  switch (avio_rb32(pb)) {
1547  case 2:
1548  if (den >= INT_MAX / 2)
1549  return 0;
1550  den *= 2;
1551  case 1:
1552  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1553  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1554  default:
1555  return 0;
1556  }
1557  }
1558  }
1559 
1560  return mov_read_avid(c, pb, atom);
1561 }
1562 
1564 {
1565  int ret = 0;
1566  int length = 0;
1567  uint64_t original_size;
1568  if (c->fc->nb_streams >= 1) {
1569  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1570  if (par->codec_id == AV_CODEC_ID_H264)
1571  return 0;
1572  if (atom.size == 16) {
1573  original_size = par->extradata_size;
1574  ret = mov_realloc_extradata(par, atom);
1575  if (!ret) {
1576  length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1577  if (length == atom.size) {
1578  const uint8_t range_value = par->extradata[original_size + 19];
1579  switch (range_value) {
1580  case 1:
1582  break;
1583  case 2:
1585  break;
1586  default:
1587  av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1588  break;
1589  }
1590  ff_dlog(c, "color_range: %d\n", par->color_range);
1591  } else {
1592  /* For some reason the whole atom was not added to the extradata */
1593  av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1594  }
1595  } else {
1596  av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1597  }
1598  } else {
1599  av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1600  }
1601  }
1602 
1603  return ret;
1604 }
1605 
1607 {
1608  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1609 }
1610 
1612 {
1613  AVStream *st;
1614  int ret;
1615 
1616  if (c->fc->nb_streams < 1)
1617  return 0;
1618  st = c->fc->streams[c->fc->nb_streams-1];
1619 
1620  if ((uint64_t)atom.size > (1<<30))
1621  return AVERROR_INVALIDDATA;
1622 
1623  if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1626  // pass all frma atom to codec, needed at least for QDMC and QDM2
1627  av_freep(&st->codecpar->extradata);
1628  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1629  if (ret < 0)
1630  return ret;
1631  } else if (atom.size > 8) { /* to read frma, esds atoms */
1632  if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1633  uint64_t buffer;
1634  ret = ffio_ensure_seekback(pb, 8);
1635  if (ret < 0)
1636  return ret;
1637  buffer = avio_rb64(pb);
1638  atom.size -= 8;
1639  if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1640  && buffer >> 32 <= atom.size
1641  && buffer >> 32 >= 8) {
1642  avio_skip(pb, -8);
1643  atom.size += 8;
1644  } else if (!st->codecpar->extradata_size) {
1645 #define ALAC_EXTRADATA_SIZE 36
1647  if (!st->codecpar->extradata)
1648  return AVERROR(ENOMEM);
1651  AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1652  AV_WB64(st->codecpar->extradata + 12, buffer);
1653  avio_read(pb, st->codecpar->extradata + 20, 16);
1654  avio_skip(pb, atom.size - 24);
1655  return 0;
1656  }
1657  }
1658  if ((ret = mov_read_default(c, pb, atom)) < 0)
1659  return ret;
1660  } else
1661  avio_skip(pb, atom.size);
1662  return 0;
1663 }
1664 
1665 /**
1666  * This function reads atom content and puts data in extradata without tag
1667  * nor size unlike mov_read_extradata.
1668  */
1670 {
1671  AVStream *st;
1672  int ret;
1673 
1674  if (c->fc->nb_streams < 1)
1675  return 0;
1676  st = c->fc->streams[c->fc->nb_streams-1];
1677 
1678  if ((uint64_t)atom.size > (1<<30))
1679  return AVERROR_INVALIDDATA;
1680 
1681  if (atom.size >= 10) {
1682  // Broken files created by legacy versions of libavformat will
1683  // wrap a whole fiel atom inside of a glbl atom.
1684  unsigned size = avio_rb32(pb);
1685  unsigned type = avio_rl32(pb);
1686  avio_seek(pb, -8, SEEK_CUR);
1687  if (type == MKTAG('f','i','e','l') && size == atom.size)
1688  return mov_read_default(c, pb, atom);
1689  }
1690  if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1691  av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1692  return 0;
1693  }
1694  av_freep(&st->codecpar->extradata);
1695  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1696  if (ret < 0)
1697  return ret;
1698 
1699  return 0;
1700 }
1701 
1703 {
1704  AVStream *st;
1705  uint8_t profile_level;
1706  int ret;
1707 
1708  if (c->fc->nb_streams < 1)
1709  return 0;
1710  st = c->fc->streams[c->fc->nb_streams-1];
1711 
1712  if (atom.size >= (1<<28) || atom.size < 7)
1713  return AVERROR_INVALIDDATA;
1714 
1715  profile_level = avio_r8(pb);
1716  if ((profile_level & 0xf0) != 0xc0)
1717  return 0;
1718 
1719  avio_seek(pb, 6, SEEK_CUR);
1720  av_freep(&st->codecpar->extradata);
1721  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1722  if (ret < 0)
1723  return ret;
1724 
1725  return 0;
1726 }
1727 
1728 /**
1729  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1730  * but can have extradata appended at the end after the 40 bytes belonging
1731  * to the struct.
1732  */
1734 {
1735  AVStream *st;
1736  int ret;
1737 
1738  if (c->fc->nb_streams < 1)
1739  return 0;
1740  if (atom.size <= 40)
1741  return 0;
1742  st = c->fc->streams[c->fc->nb_streams-1];
1743 
1744  if ((uint64_t)atom.size > (1<<30))
1745  return AVERROR_INVALIDDATA;
1746 
1747  avio_skip(pb, 40);
1748  av_freep(&st->codecpar->extradata);
1749  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1750  if (ret < 0)
1751  return ret;
1752 
1753  return 0;
1754 }
1755 
1757 {
1758  AVStream *st;
1759  MOVStreamContext *sc;
1760  unsigned int i, entries;
1761 
1762  if (c->fc->nb_streams < 1)
1763  return 0;
1764  st = c->fc->streams[c->fc->nb_streams-1];
1765  sc = st->priv_data;
1766 
1767  avio_r8(pb); /* version */
1768  avio_rb24(pb); /* flags */
1769 
1770  entries = avio_rb32(pb);
1771 
1772  if (!entries)
1773  return 0;
1774 
1775  if (sc->chunk_offsets)
1776  av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1777  av_free(sc->chunk_offsets);
1778  sc->chunk_count = 0;
1779  sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1780  if (!sc->chunk_offsets)
1781  return AVERROR(ENOMEM);
1782  sc->chunk_count = entries;
1783 
1784  if (atom.type == MKTAG('s','t','c','o'))
1785  for (i = 0; i < entries && !pb->eof_reached; i++)
1786  sc->chunk_offsets[i] = avio_rb32(pb);
1787  else if (atom.type == MKTAG('c','o','6','4'))
1788  for (i = 0; i < entries && !pb->eof_reached; i++)
1789  sc->chunk_offsets[i] = avio_rb64(pb);
1790  else
1791  return AVERROR_INVALIDDATA;
1792 
1793  sc->chunk_count = i;
1794 
1795  if (pb->eof_reached)
1796  return AVERROR_EOF;
1797 
1798  return 0;
1799 }
1800 
1801 /**
1802  * Compute codec id for 'lpcm' tag.
1803  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1804  */
1806 {
1807  /* lpcm flags:
1808  * 0x1 = float
1809  * 0x2 = big-endian
1810  * 0x4 = signed
1811  */
1812  return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1813 }
1814 
1815 static int mov_codec_id(AVStream *st, uint32_t format)
1816 {
1817  int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1818 
1819  if (id <= 0 &&
1820  ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1821  (format & 0xFFFF) == 'T' + ('S' << 8)))
1822  id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1823 
1824  if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1826  } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1827  /* skip old ASF MPEG-4 tag */
1828  format && format != MKTAG('m','p','4','s')) {
1830  if (id <= 0)
1831  id = ff_codec_get_id(ff_codec_bmp_tags, format);
1832  if (id > 0)
1834  else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
1836  st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
1838  if (id > 0)
1840  }
1841  }
1842 
1843  st->codecpar->codec_tag = format;
1844 
1845  return id;
1846 }
1847 
1849  AVStream *st, MOVStreamContext *sc)
1850 {
1851  uint8_t codec_name[32] = { 0 };
1852  int64_t stsd_start;
1853  unsigned int len;
1854 
1855  /* The first 16 bytes of the video sample description are already
1856  * read in ff_mov_read_stsd_entries() */
1857  stsd_start = avio_tell(pb) - 16;
1858 
1859  avio_rb16(pb); /* version */
1860  avio_rb16(pb); /* revision level */
1861  avio_rb32(pb); /* vendor */
1862  avio_rb32(pb); /* temporal quality */
1863  avio_rb32(pb); /* spatial quality */
1864 
1865  st->codecpar->width = avio_rb16(pb); /* width */
1866  st->codecpar->height = avio_rb16(pb); /* height */
1867 
1868  avio_rb32(pb); /* horiz resolution */
1869  avio_rb32(pb); /* vert resolution */
1870  avio_rb32(pb); /* data size, always 0 */
1871  avio_rb16(pb); /* frames per samples */
1872 
1873  len = avio_r8(pb); /* codec name, pascal string */
1874  if (len > 31)
1875  len = 31;
1876  mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1877  if (len < 31)
1878  avio_skip(pb, 31 - len);
1879 
1880  if (codec_name[0])
1881  av_dict_set(&st->metadata, "encoder", codec_name, 0);
1882 
1883  /* codec_tag YV12 triggers an UV swap in rawdec.c */
1884  if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1885  st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1886  st->codecpar->width &= ~1;
1887  st->codecpar->height &= ~1;
1888  }
1889  /* Flash Media Server uses tag H.263 with Sorenson Spark */
1890  if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1891  !memcmp(codec_name, "Sorenson H263", 13))
1893 
1894  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1895 
1896  avio_seek(pb, stsd_start, SEEK_SET);
1897 
1898  if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
1899  st->codecpar->bits_per_coded_sample &= 0x1F;
1900  sc->has_palette = 1;
1901  }
1902 }
1903 
1905  AVStream *st, MOVStreamContext *sc)
1906 {
1907  int bits_per_sample, flags;
1908  uint16_t version = avio_rb16(pb);
1909  AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1910 
1911  avio_rb16(pb); /* revision level */
1912  avio_rb32(pb); /* vendor */
1913 
1914  st->codecpar->channels = avio_rb16(pb); /* channel count */
1915  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1916  av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1917 
1918  sc->audio_cid = avio_rb16(pb);
1919  avio_rb16(pb); /* packet size = 0 */
1920 
1921  st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1922 
1923  // Read QT version 1 fields. In version 0 these do not exist.
1924  av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1925  if (!c->isom ||
1926  (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1927 
1928  if (version == 1) {
1929  sc->samples_per_frame = avio_rb32(pb);
1930  avio_rb32(pb); /* bytes per packet */
1931  sc->bytes_per_frame = avio_rb32(pb);
1932  avio_rb32(pb); /* bytes per sample */
1933  } else if (version == 2) {
1934  avio_rb32(pb); /* sizeof struct only */
1936  st->codecpar->channels = avio_rb32(pb);
1937  avio_rb32(pb); /* always 0x7F000000 */
1939 
1940  flags = avio_rb32(pb); /* lpcm format specific flag */
1941  sc->bytes_per_frame = avio_rb32(pb);
1942  sc->samples_per_frame = avio_rb32(pb);
1943  if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1944  st->codecpar->codec_id =
1946  flags);
1947  }
1948  if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1949  /* can't correctly handle variable sized packet as audio unit */
1950  switch (st->codecpar->codec_id) {
1951  case AV_CODEC_ID_MP2:
1952  case AV_CODEC_ID_MP3:
1954  break;
1955  }
1956  }
1957  }
1958 
1959  if (sc->format == 0) {
1960  if (st->codecpar->bits_per_coded_sample == 8)
1961  st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1962  else if (st->codecpar->bits_per_coded_sample == 16)
1963  st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1964  }
1965 
1966  switch (st->codecpar->codec_id) {
1967  case AV_CODEC_ID_PCM_S8:
1968  case AV_CODEC_ID_PCM_U8:
1969  if (st->codecpar->bits_per_coded_sample == 16)
1971  break;
1972  case AV_CODEC_ID_PCM_S16LE:
1973  case AV_CODEC_ID_PCM_S16BE:
1974  if (st->codecpar->bits_per_coded_sample == 8)
1976  else if (st->codecpar->bits_per_coded_sample == 24)
1977  st->codecpar->codec_id =
1980  else if (st->codecpar->bits_per_coded_sample == 32)
1981  st->codecpar->codec_id =
1984  break;
1985  /* set values for old format before stsd version 1 appeared */
1986  case AV_CODEC_ID_MACE3:
1987  sc->samples_per_frame = 6;
1988  sc->bytes_per_frame = 2 * st->codecpar->channels;
1989  break;
1990  case AV_CODEC_ID_MACE6:
1991  sc->samples_per_frame = 6;
1992  sc->bytes_per_frame = 1 * st->codecpar->channels;
1993  break;
1995  sc->samples_per_frame = 64;
1996  sc->bytes_per_frame = 34 * st->codecpar->channels;
1997  break;
1998  case AV_CODEC_ID_GSM:
1999  sc->samples_per_frame = 160;
2000  sc->bytes_per_frame = 33;
2001  break;
2002  default:
2003  break;
2004  }
2005 
2006  bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2007  if (bits_per_sample) {
2008  st->codecpar->bits_per_coded_sample = bits_per_sample;
2009  sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2010  }
2011 }
2012 
2014  AVStream *st, MOVStreamContext *sc,
2015  int64_t size)
2016 {
2017  // ttxt stsd contains display flags, justification, background
2018  // color, fonts, and default styles, so fake an atom to read it
2019  MOVAtom fake_atom = { .size = size };
2020  // mp4s contains a regular esds atom
2021  if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2022  mov_read_glbl(c, pb, fake_atom);
2023  st->codecpar->width = sc->width;
2024  st->codecpar->height = sc->height;
2025 }
2026 
2027 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2028 {
2029  uint8_t r, g, b;
2030  int y, cb, cr;
2031 
2032  y = (ycbcr >> 16) & 0xFF;
2033  cr = (ycbcr >> 8) & 0xFF;
2034  cb = ycbcr & 0xFF;
2035 
2036  b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2037  g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2038  r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2039 
2040  return (r << 16) | (g << 8) | b;
2041 }
2042 
2044 {
2045  char buf[256] = {0};
2046  uint8_t *src = st->codecpar->extradata;
2047  int i;
2048 
2049  if (st->codecpar->extradata_size != 64)
2050  return 0;
2051 
2052  if (st->codecpar->width > 0 && st->codecpar->height > 0)
2053  snprintf(buf, sizeof(buf), "size: %dx%d\n",
2054  st->codecpar->width, st->codecpar->height);
2055  av_strlcat(buf, "palette: ", sizeof(buf));
2056 
2057  for (i = 0; i < 16; i++) {
2058  uint32_t yuv = AV_RB32(src + i * 4);
2059  uint32_t rgba = yuv_to_rgba(yuv);
2060 
2061  av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2062  }
2063 
2064  if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2065  return 0;
2066 
2067  av_freep(&st->codecpar->extradata);
2068  st->codecpar->extradata_size = 0;
2070  if (!st->codecpar->extradata)
2071  return AVERROR(ENOMEM);
2072  st->codecpar->extradata_size = strlen(buf);
2073  memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2074 
2075  return 0;
2076 }
2077 
2079  AVStream *st, MOVStreamContext *sc,
2080  int64_t size)
2081 {
2082  int ret;
2083 
2084  if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2085  if ((int)size != size)
2086  return AVERROR(ENOMEM);
2087 
2088  ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2089  if (ret < 0)
2090  return ret;
2091  if (size > 16) {
2092  MOVStreamContext *tmcd_ctx = st->priv_data;
2093  int val;
2094  val = AV_RB32(st->codecpar->extradata + 4);
2095  tmcd_ctx->tmcd_flags = val;
2096  st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2097  st->avg_frame_rate.den = 1;
2098 #if FF_API_LAVF_AVCTX
2100  st->codec->time_base = av_inv_q(st->avg_frame_rate);
2102 #endif
2103  /* adjust for per frame dur in counter mode */
2104  if (tmcd_ctx->tmcd_flags & 0x0008) {
2105  int timescale = AV_RB32(st->codecpar->extradata + 8);
2106  int framedur = AV_RB32(st->codecpar->extradata + 12);
2107  st->avg_frame_rate.num *= timescale;
2108  st->avg_frame_rate.den *= framedur;
2109 #if FF_API_LAVF_AVCTX
2111  st->codec->time_base.den *= timescale;
2112  st->codec->time_base.num *= framedur;
2114 #endif
2115  }
2116  if (size > 30) {
2117  uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2118  uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2119  if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2120  uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2121  if (str_size > 0 && size >= (int)str_size + 26) {
2122  char *reel_name = av_malloc(str_size + 1);
2123  if (!reel_name)
2124  return AVERROR(ENOMEM);
2125  memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2126  reel_name[str_size] = 0; /* Add null terminator */
2127  /* don't add reel_name if emtpy string */
2128  if (*reel_name == 0) {
2129  av_free(reel_name);
2130  } else {
2131  av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2132  }
2133  }
2134  }
2135  }
2136  }
2137  } else {
2138  /* other codec type, just skip (rtp, mp4s ...) */
2139  avio_skip(pb, size);
2140  }
2141  return 0;
2142 }
2143 
2145  AVStream *st, MOVStreamContext *sc)
2146 {
2147  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2148  !st->codecpar->sample_rate && sc->time_scale > 1)
2149  st->codecpar->sample_rate = sc->time_scale;
2150 
2151  /* special codec parameters handling */
2152  switch (st->codecpar->codec_id) {
2153 #if CONFIG_DV_DEMUXER
2154  case AV_CODEC_ID_DVAUDIO:
2156  if (!c->dv_fctx) {
2157  av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2158  return AVERROR(ENOMEM);
2159  }
2161  if (!c->dv_demux) {
2162  av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2163  return AVERROR(ENOMEM);
2164  }
2165  sc->dv_audio_container = 1;
2167  break;
2168 #endif
2169  /* no ifdef since parameters are always those */
2170  case AV_CODEC_ID_QCELP:
2171  st->codecpar->channels = 1;
2172  // force sample rate for qcelp when not stored in mov
2173  if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2174  st->codecpar->sample_rate = 8000;
2175  // FIXME: Why is the following needed for some files?
2176  sc->samples_per_frame = 160;
2177  if (!sc->bytes_per_frame)
2178  sc->bytes_per_frame = 35;
2179  break;
2180  case AV_CODEC_ID_AMR_NB:
2181  st->codecpar->channels = 1;
2182  /* force sample rate for amr, stsd in 3gp does not store sample rate */
2183  st->codecpar->sample_rate = 8000;
2184  break;
2185  case AV_CODEC_ID_AMR_WB:
2186  st->codecpar->channels = 1;
2187  st->codecpar->sample_rate = 16000;
2188  break;
2189  case AV_CODEC_ID_MP2:
2190  case AV_CODEC_ID_MP3:
2191  /* force type after stsd for m1a hdlr */
2193  break;
2194  case AV_CODEC_ID_GSM:
2195  case AV_CODEC_ID_ADPCM_MS:
2197  case AV_CODEC_ID_ILBC:
2198  case AV_CODEC_ID_MACE3:
2199  case AV_CODEC_ID_MACE6:
2200  case AV_CODEC_ID_QDM2:
2202  break;
2203  case AV_CODEC_ID_ALAC:
2204  if (st->codecpar->extradata_size == 36) {
2205  st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2206  st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2207  }
2208  break;
2209  case AV_CODEC_ID_AC3:
2210  case AV_CODEC_ID_EAC3:
2212  case AV_CODEC_ID_VC1:
2213  case AV_CODEC_ID_VP9:
2215  break;
2216  default:
2217  break;
2218  }
2219  return 0;
2220 }
2221 
2223  int codec_tag, int format,
2224  int64_t size)
2225 {
2226  int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2227 
2228  if (codec_tag &&
2229  (codec_tag != format &&
2230  // AVID 1:1 samples with differing data format and codec tag exist
2231  (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2232  // prores is allowed to have differing data format and codec tag
2233  codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2234  // so is dv (sigh)
2235  codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2236  (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2237  : codec_tag != MKTAG('j','p','e','g')))) {
2238  /* Multiple fourcc, we skip JPEG. This is not correct, we should
2239  * export it as a separate AVStream but this needs a few changes
2240  * in the MOV demuxer, patch welcome. */
2241 
2242  av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2243  avio_skip(pb, size);
2244  return 1;
2245  }
2246 
2247  return 0;
2248 }
2249 
2251 {
2252  AVStream *st;
2253  MOVStreamContext *sc;
2254  int pseudo_stream_id;
2255 
2256  if (c->fc->nb_streams < 1)
2257  return 0;
2258  st = c->fc->streams[c->fc->nb_streams-1];
2259  sc = st->priv_data;
2260 
2261  for (pseudo_stream_id = 0;
2262  pseudo_stream_id < entries && !pb->eof_reached;
2263  pseudo_stream_id++) {
2264  //Parsing Sample description table
2265  enum AVCodecID id;
2266  int ret, dref_id = 1;
2267  MOVAtom a = { AV_RL32("stsd") };
2268  int64_t start_pos = avio_tell(pb);
2269  int64_t size = avio_rb32(pb); /* size */
2270  uint32_t format = avio_rl32(pb); /* data format */
2271 
2272  if (size >= 16) {
2273  avio_rb32(pb); /* reserved */
2274  avio_rb16(pb); /* reserved */
2275  dref_id = avio_rb16(pb);
2276  } else if (size <= 7) {
2277  av_log(c->fc, AV_LOG_ERROR,
2278  "invalid size %"PRId64" in stsd\n", size);
2279  return AVERROR_INVALIDDATA;
2280  }
2281 
2282  if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2283  size - (avio_tell(pb) - start_pos)))
2284  continue;
2285 
2286  sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2287  sc->dref_id= dref_id;
2288  sc->format = format;
2289 
2290  id = mov_codec_id(st, format);
2291 
2292  av_log(c->fc, AV_LOG_TRACE,
2293  "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2294  av_fourcc2str(format), st->codecpar->codec_type);
2295 
2297  st->codecpar->codec_id = id;
2298  mov_parse_stsd_video(c, pb, st, sc);
2299  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2300  st->codecpar->codec_id = id;
2301  mov_parse_stsd_audio(c, pb, st, sc);
2302  if (st->codecpar->sample_rate < 0) {
2303  av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2304  return AVERROR_INVALIDDATA;
2305  }
2306  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2307  st->codecpar->codec_id = id;
2308  mov_parse_stsd_subtitle(c, pb, st, sc,
2309  size - (avio_tell(pb) - start_pos));
2310  } else {
2311  ret = mov_parse_stsd_data(c, pb, st, sc,
2312  size - (avio_tell(pb) - start_pos));
2313  if (ret < 0)
2314  return ret;
2315  }
2316  /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2317  a.size = size - (avio_tell(pb) - start_pos);
2318  if (a.size > 8) {
2319  if ((ret = mov_read_default(c, pb, a)) < 0)
2320  return ret;
2321  } else if (a.size > 0)
2322  avio_skip(pb, a.size);
2323 
2324  if (sc->extradata && st->codecpar->extradata) {
2325  int extra_size = st->codecpar->extradata_size;
2326 
2327  /* Move the current stream extradata to the stream context one. */
2328  sc->extradata_size[pseudo_stream_id] = extra_size;
2329  sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2330  if (!sc->extradata[pseudo_stream_id])
2331  return AVERROR(ENOMEM);
2332  memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2333  av_freep(&st->codecpar->extradata);
2334  st->codecpar->extradata_size = 0;
2335  }
2336  }
2337 
2338  if (pb->eof_reached)
2339  return AVERROR_EOF;
2340 
2341  return 0;
2342 }
2343 
2345 {
2346  AVStream *st;
2347  MOVStreamContext *sc;
2348  int ret, entries;
2349 
2350  if (c->fc->nb_streams < 1)
2351  return 0;
2352  st = c->fc->streams[c->fc->nb_streams - 1];
2353  sc = st->priv_data;
2354 
2355  avio_r8(pb); /* version */
2356  avio_rb24(pb); /* flags */
2357  entries = avio_rb32(pb);
2358 
2359  if (entries <= 0) {
2360  av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2361  return AVERROR_INVALIDDATA;
2362  }
2363 
2364  if (sc->extradata) {
2365  av_log(c->fc, AV_LOG_ERROR, "Duplicate STSD\n");
2366  return AVERROR_INVALIDDATA;
2367  }
2368  /* Prepare space for hosting multiple extradata. */
2369  sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2370  sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2371  if (!sc->extradata_size || !sc->extradata) {
2372  ret = AVERROR(ENOMEM);
2373  goto fail;
2374  }
2375 
2376  ret = ff_mov_read_stsd_entries(c, pb, entries);
2377  if (ret < 0)
2378  return ret;
2379 
2380  sc->stsd_count = entries;
2381 
2382  /* Restore back the primary extradata. */
2383  av_freep(&st->codecpar->extradata);
2384  st->codecpar->extradata_size = sc->extradata_size[0];
2385  if (sc->extradata_size[0]) {
2387  if (!st->codecpar->extradata)
2388  return AVERROR(ENOMEM);
2389  memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2390  }
2391 
2392  return mov_finalize_stsd_codec(c, pb, st, sc);
2393 fail:
2394  av_freep(&sc->extradata);
2395  av_freep(&sc->extradata_size);
2396  return ret;
2397 }
2398 
2400 {
2401  AVStream *st;
2402  MOVStreamContext *sc;
2403  unsigned int i, entries;
2404 
2405  if (c->fc->nb_streams < 1)
2406  return 0;
2407  st = c->fc->streams[c->fc->nb_streams-1];
2408  sc = st->priv_data;
2409 
2410  avio_r8(pb); /* version */
2411  avio_rb24(pb); /* flags */
2412 
2413  entries = avio_rb32(pb);
2414 
2415  av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2416 
2417  if (!entries)
2418  return 0;
2419  if (sc->stsc_data)
2420  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2421  av_free(sc->stsc_data);
2422  sc->stsc_count = 0;
2423  sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2424  if (!sc->stsc_data)
2425  return AVERROR(ENOMEM);
2426 
2427  for (i = 0; i < entries && !pb->eof_reached; i++) {
2428  sc->stsc_data[i].first = avio_rb32(pb);
2429  sc->stsc_data[i].count = avio_rb32(pb);
2430  sc->stsc_data[i].id = avio_rb32(pb);
2431  }
2432 
2433  sc->stsc_count = i;
2434 
2435  if (pb->eof_reached)
2436  return AVERROR_EOF;
2437 
2438  return 0;
2439 }
2440 
2441 #define mov_stsc_index_valid(index, count) ((index) < (count) - 1)
2442 
2443 /* Compute the samples value for the stsc entry at the given index. */
2444 static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
2445 {
2446  int chunk_count;
2447 
2448  if (mov_stsc_index_valid(index, sc->stsc_count))
2449  chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2450  else
2451  chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2452 
2453  return sc->stsc_data[index].count * chunk_count;
2454 }
2455 
2457 {
2458  AVStream *st;
2459  MOVStreamContext *sc;
2460  unsigned i, entries;
2461 
2462  if (c->fc->nb_streams < 1)
2463  return 0;
2464  st = c->fc->streams[c->fc->nb_streams-1];
2465  sc = st->priv_data;
2466 
2467  avio_rb32(pb); // version + flags
2468 
2469  entries = avio_rb32(pb);
2470  if (sc->stps_data)
2471  av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2472  av_free(sc->stps_data);
2473  sc->stps_count = 0;
2474  sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2475  if (!sc->stps_data)
2476  return AVERROR(ENOMEM);
2477 
2478  for (i = 0; i < entries && !pb->eof_reached; i++) {
2479  sc->stps_data[i] = avio_rb32(pb);
2480  }
2481 
2482  sc->stps_count = i;
2483 
2484  if (pb->eof_reached)
2485  return AVERROR_EOF;
2486 
2487  return 0;
2488 }
2489 
2491 {
2492  AVStream *st;
2493  MOVStreamContext *sc;
2494  unsigned int i, entries;
2495 
2496  if (c->fc->nb_streams < 1)
2497  return 0;
2498  st = c->fc->streams[c->fc->nb_streams-1];
2499  sc = st->priv_data;
2500 
2501  avio_r8(pb); /* version */
2502  avio_rb24(pb); /* flags */
2503 
2504  entries = avio_rb32(pb);
2505 
2506  av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2507 
2508  if (!entries)
2509  {
2510  sc->keyframe_absent = 1;
2511  if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2513  return 0;
2514  }
2515  if (sc->keyframes)
2516  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2517  if (entries >= UINT_MAX / sizeof(int))
2518  return AVERROR_INVALIDDATA;
2519  av_freep(&sc->keyframes);
2520  sc->keyframe_count = 0;
2521  sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2522  if (!sc->keyframes)
2523  return AVERROR(ENOMEM);
2524 
2525  for (i = 0; i < entries && !pb->eof_reached; i++) {
2526  sc->keyframes[i] = avio_rb32(pb);
2527  }
2528 
2529  sc->keyframe_count = i;
2530 
2531  if (pb->eof_reached)
2532  return AVERROR_EOF;
2533 
2534  return 0;
2535 }
2536 
2538 {
2539  AVStream *st;
2540  MOVStreamContext *sc;
2541  unsigned int i, entries, sample_size, field_size, num_bytes;
2542  GetBitContext gb;
2543  unsigned char* buf;
2544  int ret;
2545 
2546  if (c->fc->nb_streams < 1)
2547  return 0;
2548  st = c->fc->streams[c->fc->nb_streams-1];
2549  sc = st->priv_data;
2550 
2551  avio_r8(pb); /* version */
2552  avio_rb24(pb); /* flags */
2553 
2554  if (atom.type == MKTAG('s','t','s','z')) {
2555  sample_size = avio_rb32(pb);
2556  if (!sc->sample_size) /* do not overwrite value computed in stsd */
2557  sc->sample_size = sample_size;
2558  sc->stsz_sample_size = sample_size;
2559  field_size = 32;
2560  } else {
2561  sample_size = 0;
2562  avio_rb24(pb); /* reserved */
2563  field_size = avio_r8(pb);
2564  }
2565  entries = avio_rb32(pb);
2566 
2567  av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2568 
2569  sc->sample_count = entries;
2570  if (sample_size)
2571  return 0;
2572 
2573  if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2574  av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2575  return AVERROR_INVALIDDATA;
2576  }
2577 
2578  if (!entries)
2579  return 0;
2580  if (entries >= (UINT_MAX - 4) / field_size)
2581  return AVERROR_INVALIDDATA;
2582  if (sc->sample_sizes)
2583  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2584  av_free(sc->sample_sizes);
2585  sc->sample_count = 0;
2586  sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2587  if (!sc->sample_sizes)
2588  return AVERROR(ENOMEM);
2589 
2590  num_bytes = (entries*field_size+4)>>3;
2591 
2592  buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2593  if (!buf) {
2594  av_freep(&sc->sample_sizes);
2595  return AVERROR(ENOMEM);
2596  }
2597 
2598  ret = ffio_read_size(pb, buf, num_bytes);
2599  if (ret < 0) {
2600  av_freep(&sc->sample_sizes);
2601  av_free(buf);
2602  return ret;
2603  }
2604 
2605  init_get_bits(&gb, buf, 8*num_bytes);
2606 
2607  for (i = 0; i < entries && !pb->eof_reached; i++) {
2608  sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2609  sc->data_size += sc->sample_sizes[i];
2610  }
2611 
2612  sc->sample_count = i;
2613 
2614  av_free(buf);
2615 
2616  if (pb->eof_reached)
2617  return AVERROR_EOF;
2618 
2619  return 0;
2620 }
2621 
2623 {
2624  AVStream *st;
2625  MOVStreamContext *sc;
2626  unsigned int i, entries;
2627  int64_t duration=0;
2628  int64_t total_sample_count=0;
2629 
2630  if (c->fc->nb_streams < 1)
2631  return 0;
2632  st = c->fc->streams[c->fc->nb_streams-1];
2633  sc = st->priv_data;
2634 
2635  avio_r8(pb); /* version */
2636  avio_rb24(pb); /* flags */
2637  entries = avio_rb32(pb);
2638 
2639  av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2640  c->fc->nb_streams-1, entries);
2641 
2642  if (sc->stts_data)
2643  av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2644  av_free(sc->stts_data);
2645  sc->stts_count = 0;
2646  sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2647  if (!sc->stts_data)
2648  return AVERROR(ENOMEM);
2649 
2650  for (i = 0; i < entries && !pb->eof_reached; i++) {
2651  int sample_duration;
2652  int sample_count;
2653 
2654  sample_count=avio_rb32(pb);
2655  sample_duration = avio_rb32(pb);
2656 
2657  if (sample_count < 0) {
2658  av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2659  return AVERROR_INVALIDDATA;
2660  }
2661  sc->stts_data[i].count= sample_count;
2662  sc->stts_data[i].duration= sample_duration;
2663 
2664  av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2665  sample_count, sample_duration);
2666 
2667  if ( i+1 == entries
2668  && i
2669  && sample_count == 1
2670  && total_sample_count > 100
2671  && sample_duration/10 > duration / total_sample_count)
2672  sample_duration = duration / total_sample_count;
2673  duration+=(int64_t)sample_duration*sample_count;
2674  total_sample_count+=sample_count;
2675  }
2676 
2677  sc->stts_count = i;
2678 
2679  sc->duration_for_fps += duration;
2680  sc->nb_frames_for_fps += total_sample_count;
2681 
2682  if (pb->eof_reached)
2683  return AVERROR_EOF;
2684 
2685  st->nb_frames= total_sample_count;
2686  if (duration)
2687  st->duration= duration;
2688  sc->track_end = duration;
2689  return 0;
2690 }
2691 
2693 {
2694  if (duration < 0) {
2695  if (duration == INT_MIN) {
2696  av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2697  duration++;
2698  }
2699  sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2700  }
2701 }
2702 
2704 {
2705  AVStream *st;
2706  MOVStreamContext *sc;
2707  unsigned int i, entries, ctts_count = 0;
2708 
2709  if (c->fc->nb_streams < 1)
2710  return 0;
2711  st = c->fc->streams[c->fc->nb_streams-1];
2712  sc = st->priv_data;
2713 
2714  avio_r8(pb); /* version */
2715  avio_rb24(pb); /* flags */
2716  entries = avio_rb32(pb);
2717 
2718  av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2719 
2720  if (!entries)
2721  return 0;
2722  if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2723  return AVERROR_INVALIDDATA;
2724  av_freep(&sc->ctts_data);
2725  sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2726  if (!sc->ctts_data)
2727  return AVERROR(ENOMEM);
2728 
2729  for (i = 0; i < entries && !pb->eof_reached; i++) {
2730  int count =avio_rb32(pb);
2731  int duration =avio_rb32(pb);
2732 
2733  if (count <= 0) {
2734  av_log(c->fc, AV_LOG_TRACE,
2735  "ignoring CTTS entry with count=%d duration=%d\n",
2736  count, duration);
2737  continue;
2738  }
2739 
2740  sc->ctts_data[ctts_count].count = count;
2741  sc->ctts_data[ctts_count].duration = duration;
2742  ctts_count++;
2743 
2744  av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2745  count, duration);
2746 
2747  if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2748  av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2749  av_freep(&sc->ctts_data);
2750  sc->ctts_count = 0;
2751  return 0;
2752  }
2753 
2754  if (i+2<entries)
2755  mov_update_dts_shift(sc, duration);
2756  }
2757 
2758  sc->ctts_count = ctts_count;
2759 
2760  if (pb->eof_reached)
2761  return AVERROR_EOF;
2762 
2763  av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2764 
2765  return 0;
2766 }
2767 
2769 {
2770  AVStream *st;
2771  MOVStreamContext *sc;
2772  unsigned int i, entries;
2773  uint8_t version;
2774  uint32_t grouping_type;
2775 
2776  if (c->fc->nb_streams < 1)
2777  return 0;
2778  st = c->fc->streams[c->fc->nb_streams-1];
2779  sc = st->priv_data;
2780 
2781  version = avio_r8(pb); /* version */
2782  avio_rb24(pb); /* flags */
2783  grouping_type = avio_rl32(pb);
2784  if (grouping_type != MKTAG( 'r','a','p',' '))
2785  return 0; /* only support 'rap ' grouping */
2786  if (version == 1)
2787  avio_rb32(pb); /* grouping_type_parameter */
2788 
2789  entries = avio_rb32(pb);
2790  if (!entries)
2791  return 0;
2792  if (sc->rap_group)
2793  av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2794  av_free(sc->rap_group);
2795  sc->rap_group_count = 0;
2796  sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2797  if (!sc->rap_group)
2798  return AVERROR(ENOMEM);
2799 
2800  for (i = 0; i < entries && !pb->eof_reached; i++) {
2801  sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2802  sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2803  }
2804 
2805  sc->rap_group_count = i;
2806 
2807  return pb->eof_reached ? AVERROR_EOF : 0;
2808 }
2809 
2810 /**
2811  * Get ith edit list entry (media time, duration).
2812  */
2814  const MOVStreamContext *msc,
2815  unsigned int edit_list_index,
2816  int64_t *edit_list_media_time,
2817  int64_t *edit_list_duration,
2818  int64_t global_timescale)
2819 {
2820  if (edit_list_index == msc->elst_count) {
2821  return 0;
2822  }
2823  *edit_list_media_time = msc->elst_data[edit_list_index].time;
2824  *edit_list_duration = msc->elst_data[edit_list_index].duration;
2825 
2826  /* duration is in global timescale units;convert to msc timescale */
2827  if (global_timescale == 0) {
2828  avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
2829  return 0;
2830  }
2831  *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
2832  global_timescale);
2833  return 1;
2834 }
2835 
2836 /**
2837  * Find the closest previous frame to the timestamp, in e_old index
2838  * entries. Searching for just any frame / just key frames can be controlled by
2839  * last argument 'flag'.
2840  * Returns the index of the entry in st->index_entries if successful,
2841  * else returns -1.
2842  */
2844  AVIndexEntry *e_old,
2845  int nb_old,
2846  int64_t timestamp,
2847  int flag)
2848 {
2849  AVIndexEntry *e_keep = st->index_entries;
2850  int nb_keep = st->nb_index_entries;
2851  int64_t found = -1;
2852  int64_t i = 0;
2853 
2854  st->index_entries = e_old;
2855  st->nb_index_entries = nb_old;
2856  found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
2857 
2858  // Keep going backwards in the index entries until the timestamp is the same.
2859  if (found >= 0) {
2860  for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
2861  i--) {
2862  if ((flag & AVSEEK_FLAG_ANY) ||
2863  (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
2864  found = i - 1;
2865  }
2866  }
2867  }
2868 
2869  /* restore AVStream state*/
2870  st->index_entries = e_keep;
2871  st->nb_index_entries = nb_keep;
2872  return found;
2873 }
2874 
2875 /**
2876  * Add index entry with the given values, to the end of st->index_entries.
2877  * Returns the new size st->index_entries if successful, else returns -1.
2878  *
2879  * This function is similar to ff_add_index_entry in libavformat/utils.c
2880  * except that here we are always unconditionally adding an index entry to
2881  * the end, instead of searching the entries list and skipping the add if
2882  * there is an existing entry with the same timestamp.
2883  * This is needed because the mov_fix_index calls this func with the same
2884  * unincremented timestamp for successive discarded frames.
2885  */
2886 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
2887  int size, int distance, int flags)
2888 {
2889  AVIndexEntry *entries, *ie;
2890  int64_t index = -1;
2891  const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
2892 
2893  // Double the allocation each time, to lower memory fragmentation.
2894  // Another difference from ff_add_index_entry function.
2895  const size_t requested_size =
2896  min_size_needed > st->index_entries_allocated_size ?
2897  FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
2898  min_size_needed;
2899 
2900  if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
2901  return -1;
2902 
2903  entries = av_fast_realloc(st->index_entries,
2905  requested_size);
2906  if(!entries)
2907  return -1;
2908 
2909  st->index_entries= entries;
2910 
2911  index= st->nb_index_entries++;
2912  ie= &entries[index];
2913 
2914  ie->pos = pos;
2915  ie->timestamp = timestamp;
2916  ie->min_distance= distance;
2917  ie->size= size;
2918  ie->flags = flags;
2919  return index;
2920 }
2921 
2922 /**
2923  * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
2924  * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
2925  */
2926 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
2927  int64_t* frame_duration_buffer,
2928  int frame_duration_buffer_size) {
2929  int i = 0;
2930  av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
2931  for (i = 0; i < frame_duration_buffer_size; i++) {
2932  end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
2933  st->index_entries[end_index - 1 - i].timestamp = end_ts;
2934  }
2935 }
2936 
2937 /**
2938  * Append a new ctts entry to ctts_data.
2939  * Returns the new ctts_count if successful, else returns -1.
2940  */
2941 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
2942  int count, int duration)
2943 {
2944  MOVStts *ctts_buf_new;
2945  const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
2946  const size_t requested_size =
2947  min_size_needed > *allocated_size ?
2948  FFMAX(min_size_needed, 2 * (*allocated_size)) :
2949  min_size_needed;
2950 
2951  if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
2952  return -1;
2953 
2954  ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
2955 
2956  if(!ctts_buf_new)
2957  return -1;
2958 
2959  *ctts_data = ctts_buf_new;
2960 
2961  ctts_buf_new[*ctts_count].count = count;
2962  ctts_buf_new[*ctts_count].duration = duration;
2963 
2964  *ctts_count = (*ctts_count) + 1;
2965  return *ctts_count;
2966 }
2967 
2969 {
2970  sc->current_sample++;
2971  sc->current_index++;
2972  if (sc->index_ranges &&
2973  sc->current_index >= sc->current_index_range->end &&
2974  sc->current_index_range->end) {
2975  sc->current_index_range++;
2977  }
2978 }
2979 
2981 {
2982  sc->current_sample--;
2983  sc->current_index--;
2984  if (sc->index_ranges &&
2986  sc->current_index_range > sc->index_ranges) {
2987  sc->current_index_range--;
2988  sc->current_index = sc->current_index_range->end - 1;
2989  }
2990 }
2991 
2992 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
2993 {
2994  int64_t range_size;
2995 
2996  sc->current_sample = current_sample;
2997  sc->current_index = current_sample;
2998  if (!sc->index_ranges) {
2999  return;
3000  }
3001 
3002  for (sc->current_index_range = sc->index_ranges;
3003  sc->current_index_range->end;
3004  sc->current_index_range++) {
3005  range_size = sc->current_index_range->end - sc->current_index_range->start;
3006  if (range_size > current_sample) {
3007  sc->current_index = sc->current_index_range->start + current_sample;
3008  break;
3009  }
3010  current_sample -= range_size;
3011  }
3012 }
3013 
3014 /**
3015  * Fix st->index_entries, so that it contains only the entries (and the entries
3016  * which are needed to decode them) that fall in the edit list time ranges.
3017  * Also fixes the timestamps of the index entries to match the timeline
3018  * specified the edit lists.
3019  */
3020 static void mov_fix_index(MOVContext *mov, AVStream *st)
3021 {
3022  MOVStreamContext *msc = st->priv_data;
3023  AVIndexEntry *e_old = st->index_entries;
3024  int nb_old = st->nb_index_entries;
3025  const AVIndexEntry *e_old_end = e_old + nb_old;
3026  const AVIndexEntry *current = NULL;
3027  MOVStts *ctts_data_old = msc->ctts_data;
3028  int64_t ctts_index_old = 0;
3029  int64_t ctts_sample_old = 0;
3030  int64_t ctts_count_old = msc->ctts_count;
3031  int64_t edit_list_media_time = 0;
3032  int64_t edit_list_duration = 0;
3033  int64_t frame_duration = 0;
3034  int64_t edit_list_dts_counter = 0;
3035  int64_t edit_list_dts_entry_end = 0;
3036  int64_t edit_list_start_ctts_sample = 0;
3037  int64_t curr_cts;
3038  int64_t edit_list_index = 0;
3039  int64_t index;
3040  int64_t index_ctts_count;
3041  int flags;
3042  unsigned int ctts_allocated_size = 0;
3043  int64_t start_dts = 0;
3044  int64_t edit_list_media_time_dts = 0;
3045  int64_t edit_list_start_encountered = 0;
3046  int64_t search_timestamp = 0;
3047  int64_t* frame_duration_buffer = NULL;
3048  int num_discarded_begin = 0;
3049  int first_non_zero_audio_edit = -1;
3050  int packet_skip_samples = 0;
3051  MOVIndexRange *current_index_range;
3052 
3053  if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3054  return;
3055  }
3056 
3057  // allocate the index ranges array
3058  msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3059  if (!msc->index_ranges) {
3060  av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3061  return;
3062  }
3063  msc->current_index_range = msc->index_ranges;
3064  current_index_range = msc->index_ranges - 1;
3065 
3066  // Clean AVStream from traces of old index
3067  st->index_entries = NULL;
3069  st->nb_index_entries = 0;
3070 
3071  // Clean ctts fields of MOVStreamContext
3072  msc->ctts_data = NULL;
3073  msc->ctts_count = 0;
3074  msc->ctts_index = 0;
3075  msc->ctts_sample = 0;
3076 
3077  // If the dts_shift is positive (in case of negative ctts values in mov),
3078  // then negate the DTS by dts_shift
3079  if (msc->dts_shift > 0)
3080  edit_list_dts_entry_end -= msc->dts_shift;
3081 
3082  // Offset the DTS by ctts[0] to make the PTS of the first frame 0
3083  if (ctts_data_old && ctts_count_old > 0) {
3084  edit_list_dts_entry_end -= ctts_data_old[0].duration;
3085  av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by ctts[%d].duration: %d\n", 0, ctts_data_old[0].duration);
3086  }
3087 
3088  start_dts = edit_list_dts_entry_end;
3089 
3090  while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3091  &edit_list_duration, mov->time_scale)) {
3092  av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3093  st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3094  edit_list_index++;
3095  edit_list_dts_counter = edit_list_dts_entry_end;
3096  edit_list_dts_entry_end += edit_list_duration;
3097  num_discarded_begin = 0;
3098  if (edit_list_media_time == -1) {
3099  continue;
3100  }
3101 
3102  // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3103  // according to the edit list below.
3104  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3105  if (first_non_zero_audio_edit < 0) {
3106  first_non_zero_audio_edit = 1;
3107  } else {
3108  first_non_zero_audio_edit = 0;
3109  }
3110 
3111  if (first_non_zero_audio_edit > 0)
3112  st->skip_samples = msc->start_pad = 0;
3113  }
3114 
3115  //find closest previous key frame
3116  edit_list_media_time_dts = edit_list_media_time;
3117  if (msc->dts_shift > 0) {
3118  edit_list_media_time_dts -= msc->dts_shift;
3119  }
3120 
3121  // While reordering frame index according to edit list we must handle properly
3122  // the scenario when edit list entry starts from none key frame.
3123  // We find closest previous key frame and preserve it and consequent frames in index.
3124  // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3125  search_timestamp = edit_list_media_time_dts;
3126  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3127  // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3128  // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3129  // edit_list_media_time to cover the decoder delay.
3130  search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3131  }
3132 
3133  index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);
3134  if (index == -1) {
3135  av_log(mov->fc, AV_LOG_WARNING,
3136  "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3137  st->index, edit_list_index, search_timestamp);
3138  index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);
3139 
3140  if (index == -1) {
3141  av_log(mov->fc, AV_LOG_WARNING,
3142  "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"
3143  "Rounding edit list media time to zero.\n",
3144  st->index, edit_list_index, search_timestamp);
3145  index = 0;
3146  edit_list_media_time = 0;
3147  }
3148  }
3149  current = e_old + index;
3150 
3151  ctts_index_old = 0;
3152  ctts_sample_old = 0;
3153 
3154  // set ctts_index properly for the found key frame
3155  for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
3156  if (ctts_data_old && ctts_index_old < ctts_count_old) {
3157  ctts_sample_old++;
3158  if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
3159  ctts_index_old++;
3160  ctts_sample_old = 0;
3161  }
3162  }
3163  }
3164 
3165  edit_list_start_ctts_sample = ctts_sample_old;
3166 
3167  // Iterate over index and arrange it according to edit list
3168  edit_list_start_encountered = 0;
3169  for (; current < e_old_end; current++, index++) {
3170  // check if frame outside edit list mark it for discard
3171  frame_duration = (current + 1 < e_old_end) ?
3172  ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3173 
3174  flags = current->flags;
3175 
3176  // frames (pts) before or after edit list
3177  curr_cts = current->timestamp + msc->dts_shift;
3178 
3179  if (ctts_data_old && ctts_index_old < ctts_count_old) {
3180  av_log(mov->fc, AV_LOG_DEBUG, "shifted frame pts, curr_cts: %"PRId64" @ %"PRId64", ctts: %d, ctts_count: %"PRId64"\n",
3181  curr_cts, ctts_index_old, ctts_data_old[ctts_index_old].duration, ctts_count_old);
3182  curr_cts += ctts_data_old[ctts_index_old].duration;
3183  ctts_sample_old++;
3184  if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3185  if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3186  &ctts_allocated_size,
3187  ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3188  ctts_data_old[ctts_index_old].duration) == -1) {
3189  av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3190  ctts_index_old,
3191  ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3192  ctts_data_old[ctts_index_old].duration);
3193  break;
3194  }
3195  ctts_index_old++;
3196  ctts_sample_old = 0;
3197  edit_list_start_ctts_sample = 0;
3198  }
3199  }
3200 
3201  if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3203  curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3204  first_non_zero_audio_edit > 0) {
3205  packet_skip_samples = edit_list_media_time - curr_cts;
3206  st->skip_samples += packet_skip_samples;
3207 
3208  // Shift the index entry timestamp by packet_skip_samples to be correct.
3209  edit_list_dts_counter -= packet_skip_samples;
3210  if (edit_list_start_encountered == 0) {
3211  edit_list_start_encountered = 1;
3212  // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3213  // discarded packets.
3214  if (frame_duration_buffer) {
3215  fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3216  frame_duration_buffer, num_discarded_begin);
3217  av_freep(&frame_duration_buffer);
3218  }
3219  }
3220 
3221  av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3222  } else {
3223  flags |= AVINDEX_DISCARD_FRAME;
3224  av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3225 
3226  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3227  num_discarded_begin++;
3228  frame_duration_buffer = av_realloc(frame_duration_buffer,
3229  num_discarded_begin * sizeof(int64_t));
3230  if (!frame_duration_buffer) {
3231  av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3232  break;
3233  }
3234  frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3235 
3236  // Increment skip_samples for the first non-zero audio edit list
3237  if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3238  st->skip_samples += frame_duration;
3239  msc->start_pad = st->skip_samples;
3240  }
3241  }
3242  }
3243  } else if (edit_list_start_encountered == 0) {
3244  edit_list_start_encountered = 1;
3245  // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3246  // discarded packets.
3247  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3248  fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3249  frame_duration_buffer, num_discarded_begin);
3250  av_freep(&frame_duration_buffer);
3251  }
3252  }
3253 
3254  if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3255  current->min_distance, flags) == -1) {
3256  av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3257  break;
3258  }
3259 
3260  // Update the index ranges array
3261  if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3262  current_index_range++;
3263  current_index_range->start = index;
3264  }
3265  current_index_range->end = index + 1;
3266 
3267  // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3268  if (edit_list_start_encountered > 0) {
3269  edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3270  }
3271 
3272  // Break when found first key frame after edit entry completion
3273  if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
3274  ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3275 
3276  if (ctts_data_old && ctts_sample_old != 0) {
3277  if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3278  &ctts_allocated_size,
3279  ctts_sample_old - edit_list_start_ctts_sample,
3280  ctts_data_old[ctts_index_old].duration) == -1) {
3281  av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3282  ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3283  ctts_data_old[ctts_index_old].duration);
3284  break;
3285  }
3286  }
3287  break;
3288  }
3289  }
3290  }
3291  // Update av stream length
3292  st->duration = edit_list_dts_entry_end - start_dts;
3293 
3294  // Free the old index and the old CTTS structures
3295  av_free(e_old);
3296  av_free(ctts_data_old);
3297 
3298  // Null terminate the index ranges array
3299  current_index_range++;
3300  current_index_range->start = 0;
3301  current_index_range->end = 0;
3302  msc->current_index = msc->index_ranges[0].start;
3303 }
3304 
3305 static void mov_build_index(MOVContext *mov, AVStream *st)
3306 {
3307  MOVStreamContext *sc = st->priv_data;
3308  int64_t current_offset;
3309  int64_t current_dts = 0;
3310  unsigned int stts_index = 0;
3311  unsigned int stsc_index = 0;
3312  unsigned int stss_index = 0;
3313  unsigned int stps_index = 0;
3314  unsigned int i, j;
3315  uint64_t stream_size = 0;
3316 
3317  if (sc->elst_count) {
3318  int i, edit_start_index = 0, multiple_edits = 0;
3319  int64_t empty_duration = 0; // empty duration of the first edit list entry
3320  int64_t start_time = 0; // start time of the media
3321 
3322  for (i = 0; i < sc->elst_count; i++) {
3323  const MOVElst *e = &sc->elst_data[i];
3324  if (i == 0 && e->time == -1) {
3325  /* if empty, the first entry is the start time of the stream
3326  * relative to the presentation itself */
3327  empty_duration = e->duration;
3328  edit_start_index = 1;
3329  } else if (i == edit_start_index && e->time >= 0) {
3330  start_time = e->time;
3331  } else {
3332  multiple_edits = 1;
3333  }
3334  }
3335 
3336  if (multiple_edits && !mov->advanced_editlist)
3337  av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3338  "Use -advanced_editlist to correctly decode otherwise "
3339  "a/v desync might occur\n");
3340 
3341  /* adjust first dts according to edit list */
3342  if ((empty_duration || start_time) && mov->time_scale > 0) {
3343  if (empty_duration)
3344  empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3345  sc->time_offset = start_time - empty_duration;
3346  if (!mov->advanced_editlist)
3347  current_dts = -sc->time_offset;
3348  }
3349 
3350  if (!multiple_edits && !mov->advanced_editlist &&
3351  st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3352  sc->start_pad = start_time;
3353  }
3354 
3355  /* only use old uncompressed audio chunk demuxing when stts specifies it */
3356  if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3357  sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3358  unsigned int current_sample = 0;
3359  unsigned int stts_sample = 0;
3360  unsigned int sample_size;
3361  unsigned int distance = 0;
3362  unsigned int rap_group_index = 0;
3363  unsigned int rap_group_sample = 0;
3364  int64_t last_dts = 0;
3365  int64_t dts_correction = 0;
3366  int rap_group_present = sc->rap_group_count && sc->rap_group;
3367  int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3368 
3369  current_dts -= sc->dts_shift;
3370  last_dts = current_dts;
3371 
3372  if (!sc->sample_count || st->nb_index_entries)
3373  return;
3374  if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3375  return;
3377  st->nb_index_entries + sc->sample_count,
3378  sizeof(*st->index_entries)) < 0) {
3379  st->nb_index_entries = 0;
3380  return;
3381  }
3383 
3384  for (i = 0; i < sc->chunk_count; i++) {
3385  int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3386  current_offset = sc->chunk_offsets[i];
3387  while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3388  i + 1 == sc->stsc_data[stsc_index + 1].first)
3389  stsc_index++;
3390 
3391  if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3392  sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3393  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3394  sc->stsz_sample_size = sc->sample_size;
3395  }
3396  if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3397  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3398  sc->stsz_sample_size = sc->sample_size;
3399  }
3400 
3401  for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3402  int keyframe = 0;
3403  if (current_sample >= sc->sample_count) {
3404  av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3405  return;
3406  }
3407 
3408  if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3409  keyframe = 1;
3410  if (stss_index + 1 < sc->keyframe_count)
3411  stss_index++;
3412  } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3413  keyframe = 1;
3414  if (stps_index + 1 < sc->stps_count)
3415  stps_index++;
3416  }
3417  if (rap_group_present && rap_group_index < sc->rap_group_count) {
3418  if (sc->rap_group[rap_group_index].index > 0)
3419  keyframe = 1;
3420  if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3421  rap_group_sample = 0;
3422  rap_group_index++;
3423  }
3424  }
3425  if (sc->keyframe_absent
3426  && !sc->stps_count
3427  && !rap_group_present
3428  && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3429  keyframe = 1;
3430  if (keyframe)
3431  distance = 0;
3432  sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3433  if (sc->pseudo_stream_id == -1 ||
3434  sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3435  AVIndexEntry *e;
3436  if (sample_size > 0x3FFFFFFF) {
3437  av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3438  return;
3439  }
3440  e = &st->index_entries[st->nb_index_entries++];
3441  e->pos = current_offset;
3442  e->timestamp = current_dts;
3443  e->size = sample_size;
3444  e->min_distance = distance;
3445  e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3446  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3447  "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3448  current_offset, current_dts, sample_size, distance, keyframe);
3449  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3450  ff_rfps_add_frame(mov->fc, st, current_dts);
3451  }
3452 
3453  current_offset += sample_size;
3454  stream_size += sample_size;
3455 
3456  /* A negative sample duration is invalid based on the spec,
3457  * but some samples need it to correct the DTS. */
3458  if (sc->stts_data[stts_index].duration < 0) {
3459  av_log(mov->fc, AV_LOG_WARNING,
3460  "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3461  sc->stts_data[stts_index].duration, stts_index,
3462  st->index);
3463  dts_correction += sc->stts_data[stts_index].duration - 1;
3464  sc->stts_data[stts_index].duration = 1;
3465  }
3466  current_dts += sc->stts_data[stts_index].duration;
3467  if (!dts_correction || current_dts + dts_correction > last_dts) {
3468  current_dts += dts_correction;
3469  dts_correction = 0;
3470  } else {
3471  /* Avoid creating non-monotonous DTS */
3472  dts_correction += current_dts - last_dts - 1;
3473  current_dts = last_dts + 1;
3474  }
3475  last_dts = current_dts;
3476  distance++;
3477  stts_sample++;
3478  current_sample++;
3479  if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3480  stts_sample = 0;
3481  stts_index++;
3482  }
3483  }
3484  }
3485  if (st->duration > 0)
3486  st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3487  } else {
3488  unsigned chunk_samples, total = 0;
3489 
3490  // compute total chunk count
3491  for (i = 0; i < sc->stsc_count; i++) {
3492  unsigned count, chunk_count;
3493 
3494  chunk_samples = sc->stsc_data[i].count;
3495  if (i != sc->stsc_count - 1 &&
3496  sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3497  av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3498  return;
3499  }
3500 
3501  if (sc->samples_per_frame >= 160) { // gsm
3502  count = chunk_samples / sc->samples_per_frame;
3503  } else if (sc->samples_per_frame > 1) {
3504  unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3505  count = (chunk_samples+samples-1) / samples;
3506  } else {
3507  count = (chunk_samples+1023) / 1024;
3508  }
3509 
3510  if (mov_stsc_index_valid(i, sc->stsc_count))
3511  chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3512  else
3513  chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3514  total += chunk_count * count;
3515  }
3516 
3517  av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3518  if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3519  return;
3521  st->nb_index_entries + total,
3522  sizeof(*st->index_entries)) < 0) {
3523  st->nb_index_entries = 0;
3524  return;
3525  }
3526  st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3527 
3528  // populate index
3529  for (i = 0; i < sc->chunk_count; i++) {
3530  current_offset = sc->chunk_offsets[i];
3531  if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3532  i + 1 == sc->stsc_data[stsc_index + 1].first)
3533  stsc_index++;
3534  chunk_samples = sc->stsc_data[stsc_index].count;
3535 
3536  while (chunk_samples > 0) {
3537  AVIndexEntry *e;
3538  unsigned size, samples;
3539 
3540  if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3542  "Zero bytes per frame, but %d samples per frame",
3543  sc->samples_per_frame);
3544  return;
3545  }
3546 
3547  if (sc->samples_per_frame >= 160) { // gsm
3548  samples = sc->samples_per_frame;
3549  size = sc->bytes_per_frame;
3550  } else {
3551  if (sc->samples_per_frame > 1) {
3552  samples = FFMIN((1024 / sc->samples_per_frame)*
3553  sc->samples_per_frame, chunk_samples);
3554  size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3555  } else {
3556  samples = FFMIN(1024, chunk_samples);
3557  size = samples * sc->sample_size;
3558  }
3559  }
3560 
3561  if (st->nb_index_entries >= total) {
3562  av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3563  return;
3564  }
3565  if (size > 0x3FFFFFFF) {
3566  av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3567  return;
3568  }
3569  e = &st->index_entries[st->nb_index_entries++];
3570  e->pos = current_offset;
3571  e->timestamp = current_dts;
3572  e->size = size;
3573  e->min_distance = 0;
3574  e->flags = AVINDEX_KEYFRAME;
3575  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3576  "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3577  size, samples);
3578 
3579  current_offset += size;
3580  current_dts += samples;
3581  chunk_samples -= samples;
3582  }
3583  }
3584  }
3585 
3586  if (!mov->ignore_editlist && mov->advanced_editlist) {
3587  // Fix index according to edit lists.
3588  mov_fix_index(mov, st);
3589  }
3590 }
3591 
3592 static int test_same_origin(const char *src, const char *ref) {
3593  char src_proto[64];
3594  char ref_proto[64];
3595  char src_auth[256];
3596  char ref_auth[256];
3597  char src_host[256];
3598  char ref_host[256];
3599  int src_port=-1;
3600  int ref_port=-1;
3601 
3602  av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3603  av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3604 
3605  if (strlen(src) == 0) {
3606  return -1;
3607  } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3608  strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3609  strlen(src_host) + 1 >= sizeof(src_host) ||
3610  strlen(ref_host) + 1 >= sizeof(ref_host)) {
3611  return 0;
3612  } else if (strcmp(src_proto, ref_proto) ||
3613  strcmp(src_auth, ref_auth) ||
3614  strcmp(src_host, ref_host) ||
3615  src_port != ref_port) {
3616  return 0;
3617  } else
3618  return 1;
3619 }
3620 
3621 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3622 {
3623  /* try relative path, we do not try the absolute because it can leak information about our
3624  system to an attacker */
3625  if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3626  char filename[1025];
3627  const char *src_path;
3628  int i, l;
3629 
3630  /* find a source dir */
3631  src_path = strrchr(src, '/');
3632  if (src_path)
3633  src_path++;
3634  else
3635  src_path = src;
3636 
3637  /* find a next level down to target */
3638  for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3639  if (ref->path[l] == '/') {
3640  if (i == ref->nlvl_to - 1)
3641  break;
3642  else
3643  i++;
3644  }
3645 
3646  /* compose filename if next level down to target was found */
3647  if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3648  memcpy(filename, src, src_path - src);
3649  filename[src_path - src] = 0;
3650 
3651  for (i = 1; i < ref->nlvl_from; i++)
3652  av_strlcat(filename, "../", sizeof(filename));
3653 
3654  av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3655  if (!c->use_absolute_path) {
3656  int same_origin = test_same_origin(src, filename);
3657 
3658  if (!same_origin) {
3659  av_log(c->fc, AV_LOG_ERROR,
3660  "Reference with mismatching origin, %s not tried for security reasons, "
3661  "set demuxer option use_absolute_path to allow it anyway\n",
3662  ref->path);
3663  return AVERROR(ENOENT);
3664  }
3665 
3666  if(strstr(ref->path + l + 1, "..") ||
3667  strstr(ref->path + l + 1, ":") ||
3668  (ref->nlvl_from > 1 && same_origin < 0) ||
3669  (filename[0] == '/' && src_path == src))
3670  return AVERROR(ENOENT);
3671  }
3672 
3673  if (strlen(filename) + 1 == sizeof(filename))
3674  return AVERROR(ENOENT);
3675  if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3676  return 0;
3677  }
3678  } else if (c->use_absolute_path) {
3679  av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3680  "this is a possible security issue\n");
3681  if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3682  return 0;
3683  } else {
3684  av_log(c->fc, AV_LOG_ERROR,
3685  "Absolute path %s not tried for security reasons, "
3686  "set demuxer option use_absolute_path to allow absolute paths\n",
3687  ref->path);
3688  }
3689 
3690  return AVERROR(ENOENT);
3691 }
3692 
3694 {
3695  if (sc->time_scale <= 0) {
3696  av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3697  sc->time_scale = c->time_scale;
3698  if (sc->time_scale <= 0)
3699  sc->time_scale = 1;
3700  }
3701 }
3702 
3704 {
3705  AVStream *st;
3706  MOVStreamContext *sc;
3707  int ret;
3708 
3709  st = avformat_new_stream(c->fc, NULL);
3710  if (!st) return AVERROR(ENOMEM);
3711  st->id = c->fc->nb_streams;
3712  sc = av_mallocz(sizeof(MOVStreamContext));
3713  if (!sc) return AVERROR(ENOMEM);
3714 
3715  st->priv_data = sc;
3717  sc->ffindex = st->index;
3718  c->trak_index = st->index;
3719 
3720  if ((ret = mov_read_default(c, pb, atom)) < 0)
3721  return ret;
3722 
3723  c->trak_index = -1;
3724 
3725  /* sanity checks */
3726  if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3727  (!sc->sample_size && !sc->sample_count))) {
3728  av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3729  st->index);
3730  return 0;
3731  }
3732 
3733  fix_timescale(c, sc);
3734 
3735  avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3736 
3737  mov_build_index(c, st);
3738 
3739  if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3740  MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3741  if (c->enable_drefs) {
3742  if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3743  av_log(c->fc, AV_LOG_ERROR,
3744  "stream %d, error opening alias: path='%s', dir='%s', "
3745  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3746  st->index, dref->path, dref->dir, dref->filename,
3747  dref->volume, dref->nlvl_from, dref->nlvl_to);
3748  } else {
3749  av_log(c->fc, AV_LOG_WARNING,
3750  "Skipped opening external track: "
3751  "stream %d, alias: path='%s', dir='%s', "
3752  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3753  "Set enable_drefs to allow this.\n",
3754  st->index, dref->path, dref->dir, dref->filename,
3755  dref->volume, dref->nlvl_from, dref->nlvl_to);
3756  }
3757  } else {
3758  sc->pb = c->fc->pb;
3759  sc->pb_is_copied = 1;
3760  }
3761 
3762  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3763  if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
3764  sc->height && sc->width &&
3765  (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
3766  st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
3767  ((double)st->codecpar->width * sc->height), INT_MAX);
3768  }
3769 
3770 #if FF_API_R_FRAME_RATE
3771  if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3773  sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3774 #endif
3775  }
3776 
3777  // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3778  if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3779  TAG_IS_AVCI(st->codecpar->codec_tag)) {
3780  ret = ff_generate_avci_extradata(st);
3781  if (ret < 0)
3782  return ret;
3783  }
3784 
3785  switch (st->codecpar->codec_id) {
3786 #if CONFIG_H261_DECODER
3787  case AV_CODEC_ID_H261:
3788 #endif
3789 #if CONFIG_H263_DECODER
3790  case AV_CODEC_ID_H263:
3791 #endif
3792 #if CONFIG_MPEG4_DECODER
3793  case AV_CODEC_ID_MPEG4:
3794 #endif
3795  st->codecpar->width = 0; /* let decoder init width/height */
3796  st->codecpar->height= 0;
3797  break;
3798  }
3799 
3800  // If the duration of the mp3 packets is not constant, then they could need a parser
3801  if (st->codecpar->codec_id == AV_CODEC_ID_MP3
3802  && sc->stts_count > 3
3803  && sc->stts_count*10 > st->nb_frames
3804  && sc->time_scale == st->codecpar->sample_rate) {
3806  }
3807  /* Do not need those anymore. */
3808  av_freep(&sc->chunk_offsets);
3809  av_freep(&sc->sample_sizes);
3810  av_freep(&sc->keyframes);
3811  av_freep(&sc->stts_data);
3812  av_freep(&sc->stps_data);
3813  av_freep(&sc->elst_data);
3814  av_freep(&sc->rap_group);
3815 
3816  return 0;
3817 }
3818 
3820 {
3821  int ret;
3822  c->itunes_metadata = 1;
3823  ret = mov_read_default(c, pb, atom);
3824  c->itunes_metadata = 0;
3825  return ret;
3826 }
3827 
3829 {
3830  uint32_t count;
3831  uint32_t i;
3832 
3833  if (atom.size < 8)
3834  return 0;
3835 
3836  avio_skip(pb, 4);
3837  count = avio_rb32(pb);
3838  if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
3839  av_log(c->fc, AV_LOG_ERROR,
3840  "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
3841  return AVERROR_INVALIDDATA;
3842  }
3843 
3844  c->meta_keys_count = count + 1;
3845  c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3846  if (!c->meta_keys)
3847  return AVERROR(ENOMEM);
3848 
3849  for (i = 1; i <= count; ++i) {
3850  uint32_t key_size = avio_rb32(pb);
3851  uint32_t type = avio_rl32(pb);
3852  if (key_size < 8) {
3853  av_log(c->fc, AV_LOG_ERROR,
3854  "The key# %"PRIu32" in meta has invalid size:"
3855  "%"PRIu32"\n", i, key_size);
3856  return AVERROR_INVALIDDATA;
3857  }
3858  key_size -= 8;
3859  if (type != MKTAG('m','d','t','a')) {
3860  avio_skip(pb, key_size);
3861  }
3862  c->meta_keys[i] = av_mallocz(key_size + 1);
3863  if (!c->meta_keys[i])
3864  return AVERROR(ENOMEM);
3865  avio_read(pb, c->meta_keys[i], key_size);
3866  }
3867 
3868  return 0;
3869 }
3870 
3872 {
3873  int64_t end = avio_tell(pb) + atom.size;
3874  uint8_t *key = NULL, *val = NULL, *mean = NULL;
3875  int i;
3876  int ret = 0;
3877  AVStream *st;
3878  MOVStreamContext *sc;
3879 
3880  if (c->fc->nb_streams < 1)
3881  return 0;
3882  st = c->fc->streams[c->fc->nb_streams-1];
3883  sc = st->priv_data;
3884 
3885  for (i = 0; i < 3; i++) {
3886  uint8_t **p;
3887  uint32_t len, tag;
3888 
3889  if (end - avio_tell(pb) <= 12)
3890  break;
3891 
3892  len = avio_rb32(pb);
3893  tag = avio_rl32(pb);
3894  avio_skip(pb, 4); // flags
3895 
3896  if (len < 12 || len - 12 > end - avio_tell(pb))
3897  break;
3898  len -= 12;
3899 
3900  if (tag == MKTAG('m', 'e', 'a', 'n'))
3901  p = &mean;
3902  else if (tag == MKTAG('n', 'a', 'm', 'e'))
3903  p = &key;
3904  else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3905  avio_skip(pb, 4);
3906  len -= 4;
3907  p = &val;
3908  } else
3909  break;
3910 
3911  *p = av_malloc(len + 1);
3912  if (!*p)
3913  break;
3914  ret = ffio_read_size(pb, *p, len);
3915  if (ret < 0) {
3916  av_freep(p);
3917  break;
3918  }
3919  (*p)[len] = 0;
3920  }
3921 
3922  if (mean && key && val) {
3923  if (strcmp(key, "iTunSMPB") == 0) {
3924  int priming, remainder, samples;
3925  if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3926  if(priming>0 && priming<16384)
3927  sc->start_pad = priming;
3928  }
3929  }
3930  if (strcmp(key, "cdec") != 0) {
3931  av_dict_set(&c->fc->metadata, key, val,
3933  key = val = NULL;
3934  }
3935  } else {
3936  av_log(c->fc, AV_LOG_VERBOSE,
3937  "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3938  }
3939 
3940  avio_seek(pb, end, SEEK_SET);
3941  av_freep(&key);
3942  av_freep(&val);
3943  av_freep(&mean);
3944  return ret;
3945 }
3946 
3948 {
3949  while (atom.size > 8) {
3950  uint32_t tag = avio_rl32(pb);
3951  atom.size -= 4;
3952  if (tag == MKTAG('h','d','l','r')) {
3953  avio_seek(pb, -8, SEEK_CUR);
3954  atom.size += 8;
3955  return mov_read_default(c, pb, atom);
3956  }
3957  }
3958  return 0;
3959 }
3960 
3961 // return 1 when matrix is identity, 0 otherwise
3962 #define IS_MATRIX_IDENT(matrix) \
3963  ( (matrix)[0][0] == (1 << 16) && \
3964  (matrix)[1][1] == (1 << 16) && \
3965  (matrix)[2][2] == (1 << 30) && \
3966  !(matrix)[0][1] && !(matrix)[0][2] && \
3967  !(matrix)[1][0] && !(matrix)[1][2] && \
3968  !(matrix)[2][0] && !(matrix)[2][1])
3969 
3971 {
3972  int i, j, e;
3973  int width;
3974  int height;
3975  int display_matrix[3][3];
3976  int res_display_matrix[3][3] = { { 0 } };
3977  AVStream *st;
3978  MOVStreamContext *sc;
3979  int version;
3980  int flags;
3981 
3982  if (c->fc->nb_streams < 1)
3983  return 0;
3984  st = c->fc->streams[c->fc->nb_streams-1];
3985  sc = st->priv_data;
3986 
3987  version = avio_r8(pb);
3988  flags = avio_rb24(pb);
3990 
3991  if (version == 1) {
3992  avio_rb64(pb);
3993  avio_rb64(pb);
3994  } else {
3995  avio_rb32(pb); /* creation time */
3996  avio_rb32(pb); /* modification time */
3997  }
3998  st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3999  avio_rb32(pb); /* reserved */
4000 
4001  /* highlevel (considering edits) duration in movie timebase */
4002  (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4003  avio_rb32(pb); /* reserved */
4004  avio_rb32(pb); /* reserved */
4005 
4006  avio_rb16(pb); /* layer */
4007  avio_rb16(pb); /* alternate group */
4008  avio_rb16(pb); /* volume */
4009  avio_rb16(pb); /* reserved */
4010 
4011  //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4012  // they're kept in fixed point format through all calculations
4013  // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4014  // side data, but the scale factor is not needed to calculate aspect ratio
4015  for (i = 0; i < 3; i++) {
4016  display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4017  display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4018  display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4019  }
4020 
4021  width = avio_rb32(pb); // 16.16 fixed point track width
4022  height = avio_rb32(pb); // 16.16 fixed point track height
4023  sc->width = width >> 16;
4024  sc->height = height >> 16;
4025 
4026  // apply the moov display matrix (after the tkhd one)
4027  for (i = 0; i < 3; i++) {
4028  const int sh[3] = { 16, 16, 30 };
4029  for (j = 0; j < 3; j++) {
4030  for (e = 0; e < 3; e++) {
4031  res_display_matrix[i][j] +=
4032  ((int64_t) display_matrix[i][e] *
4033  c->movie_display_matrix[e][j]) >> sh[e];
4034  }
4035  }
4036  }
4037 
4038  // save the matrix when it is not the default identity
4039  if (!IS_MATRIX_IDENT(res_display_matrix)) {
4040  double rotate;
4041 
4042  av_freep(&sc->display_matrix);
4043  sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4044  if (!sc->display_matrix)
4045  return AVERROR(ENOMEM);
4046 
4047  for (i = 0; i < 3; i++)
4048  for (j = 0; j < 3; j++)
4049  sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4050 
4053  if (!isnan(rotate)) {
4054  char rotate_buf[64];
4055  rotate = -rotate;
4056  if (rotate < 0) // for backward compatibility
4057  rotate += 360;
4058  snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4059  av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4060  }
4061 #endif
4062  }
4063 
4064  // transform the display width/height according to the matrix
4065  // to keep the same scale, use [width height 1<<16]
4066  if (width && height && sc->display_matrix) {
4067  double disp_transform[2];
4068 
4069  for (i = 0; i < 2; i++)
4070  disp_transform[i] = hypot(sc->display_matrix[0 + i],
4071  sc->display_matrix[3 + i]);
4072 
4073  if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4074  disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4075  fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4077  disp_transform[0] / disp_transform[1],
4078  INT_MAX);
4079  }
4080  return 0;
4081 }
4082 
4084 {
4085  MOVFragment *frag = &c->fragment;
4086  MOVTrackExt *trex = NULL;
4088  int flags, track_id, i, found = 0;
4089 
4090  avio_r8(pb); /* version */
4091  flags = avio_rb24(pb);
4092 
4093  track_id = avio_rb32(pb);
4094  if (!track_id)
4095  return AVERROR_INVALIDDATA;
4096  frag->track_id = track_id;
4097  for (i = 0; i < c->trex_count; i++)
4098  if (c->trex_data[i].track_id == frag->track_id) {
4099  trex = &c->trex_data[i];
4100  break;
4101  }
4102  if (!trex) {
4103  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4104  return AVERROR_INVALIDDATA;
4105  }
4106 
4109  frag->moof_offset : frag->implicit_offset;
4110  frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4111 
4112  frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4113  avio_rb32(pb) : trex->duration;
4114  frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4115  avio_rb32(pb) : trex->size;
4116  frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4117  avio_rb32(pb) : trex->flags;
4118  frag->time = AV_NOPTS_VALUE;
4119  for (i = 0; i < c->fragment_index_count; i++) {
4120  int j;
4121  MOVFragmentIndex* candidate = c->fragment_index_data[i];
4122  if (candidate->track_id == frag->track_id) {
4123  av_log(c->fc, AV_LOG_DEBUG,
4124  "found fragment index for track %u\n", frag->track_id);
4125  index = candidate;
4126  for (j = index->current_item; j < index->item_count; j++) {
4127  if (frag->implicit_offset == index->items[j].moof_offset) {
4128  av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
4129  "for track %u and moof_offset %"PRId64"\n",
4130  frag->track_id, index->items[j].moof_offset);
4131  frag->time = index->items[j].time;
4132  index->current_item = j + 1;
4133  found = 1;
4134  break;
4135  }
4136  }
4137  if (found)
4138  break;
4139  }
4140  }
4141  if (index && !found) {
4142  av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
4143  "it doesn't have an (in-order) entry for moof_offset "
4144  "%"PRId64"\n", frag->track_id, frag->implicit_offset);
4145  }
4146  av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4147  return 0;
4148 }
4149 
4151 {
4152  unsigned i, num;
4153  void *new_tracks;
4154 
4155  num = atom.size / 4;
4156  if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4157  return AVERROR(ENOMEM);
4158 
4159  av_free(c->chapter_tracks);
4160  c->chapter_tracks = new_tracks;
4161  c->nb_chapter_tracks = num;
4162 
4163  for (i = 0; i < num && !pb->eof_reached; i++)
4164  c->chapter_tracks[i] = avio_rb32(pb);
4165 
4166  return 0;
4167 }
4168 
4170 {
4171  MOVTrackExt *trex;
4172  int err;
4173 
4174  if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4175  return AVERROR_INVALIDDATA;
4176  if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4177  sizeof(*c->trex_data))) < 0) {
4178  c->trex_count = 0;
4179  return err;
4180  }
4181 
4182  c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4183 
4184  trex = &c->trex_data[c->trex_count++];
4185  avio_r8(pb); /* version */
4186  avio_rb24(pb); /* flags */
4187  trex->track_id = avio_rb32(pb);
4188  trex->stsd_id = avio_rb32(pb);
4189  trex->duration = avio_rb32(pb);
4190  trex->size = avio_rb32(pb);
4191  trex->flags = avio_rb32(pb);
4192  return 0;
4193 }
4194 
4196 {
4197  MOVFragment *frag = &c->fragment;
4198  AVStream *st = NULL;
4199  MOVStreamContext *sc;
4200  int version, i;
4201 
4202  for (i = 0; i < c->fc->nb_streams; i++) {
4203  if (c->fc->streams[i]->id == frag->track_id) {
4204  st = c->fc->streams[i];
4205  break;
4206  }
4207  }
4208  if (!st) {
4209  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4210  return AVERROR_INVALIDDATA;
4211  }
4212  sc = st->priv_data;
4213  if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4214  return 0;
4215  version = avio_r8(pb);
4216  avio_rb24(pb); /* flags */
4217  if (version) {
4218  sc->track_end = avio_rb64(pb);
4219  } else {
4220  sc->track_end = avio_rb32(pb);
4221  }
4222  return 0;
4223 }
4224 
4226 {
4227  MOVFragment *frag = &c->fragment;
4228  AVStream *st = NULL;
4229  MOVStreamContext *sc;
4230  MOVStts *ctts_data;
4231  uint64_t offset;
4232  int64_t dts;
4233  int data_offset = 0;
4234  unsigned entries, first_sample_flags = frag->flags;
4235  int flags, distance, i, err;
4236 
4237  for (i = 0; i < c->fc->nb_streams; i++) {
4238  if (c->fc->streams[i]->id == frag->track_id) {
4239  st = c->fc->streams[i];
4240  break;
4241  }
4242  }
4243  if (!st) {
4244  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4245  return AVERROR_INVALIDDATA;
4246  }
4247  sc = st->priv_data;
4248  if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4249  return 0;
4250  avio_r8(pb); /* version */
4251  flags = avio_rb24(pb);
4252  entries = avio_rb32(pb);
4253  av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4254 
4255  /* Always assume the presence of composition time offsets.
4256  * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
4257  * 1) in the initial movie, there are no samples.
4258  * 2) in the first movie fragment, there is only one sample without composition time offset.
4259  * 3) in the subsequent movie fragments, there are samples with composition time offset. */
4260  if (!sc->ctts_count && sc->sample_count)
4261  {
4262  /* Complement ctts table if moov atom doesn't have ctts atom. */
4263  ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
4264  if (!ctts_data)
4265  return AVERROR(ENOMEM);
4266  sc->ctts_data = ctts_data;
4267  sc->ctts_data[sc->ctts_count].count = sc->sample_count;
4268  sc->ctts_data[sc->ctts_count].duration = 0;
4269  sc->ctts_count++;
4270  }
4271  if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4272  return AVERROR_INVALIDDATA;
4273  if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
4274  sizeof(*sc->ctts_data))) < 0) {
4275  sc->ctts_count = 0;
4276  return err;
4277  }
4278  if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4279  if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4280  dts = sc->track_end - sc->time_offset;
4281  offset = frag->base_data_offset + data_offset;
4282  distance = 0;
4283  av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4284  for (i = 0; i < entries && !pb->eof_reached; i++) {
4285  unsigned sample_size = frag->size;
4286  int sample_flags = i ? frag->flags : first_sample_flags;
4287  unsigned sample_duration = frag->duration;
4288  int keyframe = 0;
4289 
4290  if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4291  if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4292  if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4293  sc->ctts_data[sc->ctts_count].count = 1;
4294  sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
4295  avio_rb32(pb) : 0;
4297  if (frag->time != AV_NOPTS_VALUE) {
4298  if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4299  int64_t pts = frag->time;
4300  av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
4301  " sc->dts_shift %d ctts.duration %d"
4302  " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
4303  sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
4304  sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4305  dts = pts - sc->dts_shift;
4306  if (flags & MOV_TRUN_SAMPLE_CTS) {
4307  dts -= sc->ctts_data[sc->ctts_count].duration;
4308  } else {
4309  dts -= sc->time_offset;
4310  }
4311  av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
4312  } else {
4313  dts = frag->time - sc->time_offset;
4314  av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
4315  ", using it for dts\n", dts);
4316  }
4317  frag->time = AV_NOPTS_VALUE;
4318  }
4319  sc->ctts_count++;
4321  keyframe = 1;
4322  else
4323  keyframe =
4324  !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4326  if (keyframe)
4327  distance = 0;
4328  err = av_add_index_entry(st, offset, dts, sample_size, distance,
4329  keyframe ? AVINDEX_KEYFRAME : 0);
4330  if (err < 0) {
4331  av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4332  }
4333  av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
4334  "size %u, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
4335  offset, dts, sample_size, distance, keyframe);
4336  distance++;
4337  dts += sample_duration;
4338  offset += sample_size;
4339  sc->data_size += sample_size;
4340  sc->duration_for_fps += sample_duration;
4341  sc->nb_frames_for_fps ++;
4342  }
4343 
4344  if (pb->eof_reached)
4345  return AVERROR_EOF;
4346 
4347  frag->implicit_offset = offset;
4348 
4349  sc->track_end = dts + sc->time_offset;
4350  if (st->duration < sc->track_end)
4351  st->duration = sc->track_end;
4352 
4353  return 0;
4354 }
4355 
4357 {
4358  int64_t offset = avio_tell(pb) + atom.size, pts;
4359  uint8_t version;
4360  unsigned i, track_id;
4361  AVStream *st = NULL;
4362  AVStream *ref_st = NULL;
4363  MOVStreamContext *sc, *ref_sc = NULL;
4366  AVRational timescale;
4367 
4368  version = avio_r8(pb);
4369  if (version > 1) {
4370  avpriv_request_sample(c->fc, "sidx version %u", version);
4371  return 0;
4372  }
4373 
4374  avio_rb24(pb); // flags
4375 
4376  track_id = avio_rb32(pb); // Reference ID
4377  for (i = 0; i < c->fc->nb_streams; i++) {
4378  if (c->fc->streams[i]->id == track_id) {
4379  st = c->fc->streams[i];
4380  break;
4381  }
4382  }
4383  if (!st) {
4384  av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4385  return 0;
4386  }
4387 
4388  sc = st->priv_data;
4389 
4390  timescale = av_make_q(1, avio_rb32(pb));
4391 
4392  if (timescale.den <= 0) {
4393  av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4394  return AVERROR_INVALIDDATA;
4395  }
4396 
4397  if (version == 0) {
4398  pts = avio_rb32(pb);
4399  offset += avio_rb32(pb);
4400  } else {
4401  pts = avio_rb64(pb);
4402  offset += avio_rb64(pb);
4403  }
4404 
4405  avio_rb16(pb); // reserved
4406 
4407  index = av_mallocz(sizeof(MOVFragmentIndex));
4408  if (!index)
4409  return AVERROR(ENOMEM);
4410 
4411  index->track_id = track_id;
4412 
4413  index->item_count = avio_rb16(pb);
4414  index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
4415 
4416  if (!index->items) {
4417  av_freep(&index);
4418  return AVERROR(ENOMEM);
4419  }
4420 
4421  for (i = 0; i < index->item_count; i++) {
4422  uint32_t size = avio_rb32(pb);
4423  uint32_t duration = avio_rb32(pb);
4424  if (size & 0x80000000) {
4425  avpriv_request_sample(c->fc, "sidx reference_type 1");
4426  av_freep(&index->items);
4427  av_freep(&index);
4428  return AVERROR_PATCHWELCOME;
4429  }
4430  avio_rb32(pb); // sap_flags
4431  index->items[i].moof_offset = offset;
4432  index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
4433  offset += size;
4434  pts += duration;
4435  }
4436 
4437  st->duration = sc->track_end = pts;
4438 
4440  c->fragment_index_count + 1,
4441  sizeof(MOVFragmentIndex*));
4442  if (!tmp) {
4443  av_freep(&index->items);
4444  av_freep(&index);
4445  return AVERROR(ENOMEM);
4446  }
4447 
4448  c->fragment_index_data = tmp;
4450  sc->has_sidx = 1;
4451 
4452  if (offset == avio_size(pb)) {
4453  for (i = 0; i < c->fc->nb_streams; i++) {
4454  if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) {
4455  ref_st = c->fc->streams[i];
4456  ref_sc = ref_st->priv_data;
4457  break;
4458  }
4459  }
4460  for (i = 0; i < c->fc->nb_streams; i++) {
4461  st = c->fc->streams[i];
4462  sc = st->priv_data;
4463  if (!sc->has_sidx) {
4464  st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4465  }
4466  }
4467 
4468  c->fragment_index_complete = 1;
4469  }
4470 
4471  return 0;
4472 }
4473 
4474 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4475 /* like the files created with Adobe Premiere 5.0, for samples see */
4476 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4478 {
4479  int err;
4480 
4481  if (atom.size < 8)
4482  return 0; /* continue */
4483  if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
4484  avio_skip(pb, atom.size - 4);
4485  return 0;
4486  }
4487  atom.type = avio_rl32(pb);
4488  atom.size -= 8;
4489  if (atom.type != MKTAG('m','d','a','t')) {
4490  avio_skip(pb, atom.size);
4491  return 0;
4492  }
4493  err = mov_read_mdat(c, pb, atom);
4494  return err;
4495 }
4496 
4498 {
4499 #if CONFIG_ZLIB
4500  AVIOContext ctx;
4501  uint8_t *cmov_data;
4502  uint8_t *moov_data; /* uncompressed data */
4503  long cmov_len, moov_len;
4504  int ret = -1;
4505 
4506  avio_rb32(pb); /* dcom atom */
4507  if (avio_rl32(pb) != MKTAG('d','c','o','m'))
4508  return AVERROR_INVALIDDATA;
4509  if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
4510  av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
4511  return AVERROR_INVALIDDATA;
4512  }
4513  avio_rb32(pb); /* cmvd atom */
4514  if (avio_rl32(pb) != MKTAG('c','m','v','d'))
4515  return AVERROR_INVALIDDATA;
4516  moov_len = avio_rb32(pb); /* uncompressed size */
4517  cmov_len = atom.size - 6 * 4;
4518 
4519  cmov_data = av_malloc(cmov_len);
4520  if (!cmov_data)
4521  return AVERROR(ENOMEM);
4522  moov_data = av_malloc(moov_len);
4523  if (!moov_data) {
4524  av_free(cmov_data);
4525  return AVERROR(ENOMEM);
4526  }
4527  ret = ffio_read_size(pb, cmov_data, cmov_len);
4528  if (ret < 0)
4529  goto free_and_return;
4530 
4531  if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
4532  goto free_and_return;
4533  if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
4534  goto free_and_return;
4536  atom.type = MKTAG('m','o','o','v');
4537  atom.size = moov_len;
4538  ret = mov_read_default(c, &ctx, atom);
4539 free_and_return:
4540  av_free(moov_data);
4541  av_free(cmov_data);
4542  return ret;
4543 #else
4544  av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
4545  return AVERROR(ENOSYS);
4546 #endif
4547 }
4548 
4549 /* edit list atom */
4551 {
4552  MOVStreamContext *sc;
4553  int i, edit_count, version;
4554 
4555  if (c->fc->nb_streams < 1 || c->ignore_editlist)
4556  return 0;
4557  sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
4558 
4559  version = avio_r8(pb); /* version */
4560  avio_rb24(pb); /* flags */
4561  edit_count = avio_rb32(pb); /* entries */
4562 
4563  if (!edit_count)
4564  return 0;
4565  if (sc->elst_data)
4566  av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
4567  av_free(sc->elst_data);
4568  sc->elst_count = 0;
4569  sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
4570  if (!sc->elst_data)
4571  return AVERROR(ENOMEM);
4572 
4573  av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
4574  for (i = 0; i < edit_count && !pb->eof_reached; i++) {
4575  MOVElst *e = &sc->elst_data[i];
4576 
4577  if (version == 1) {
4578  e->duration = avio_rb64(pb);
4579  e->time = avio_rb64(pb);
4580  } else {
4581  e->duration = avio_rb32(pb); /* segment duration */
4582  e->time = (int32_t)avio_rb32(pb); /* media time */
4583  }
4584  e->rate = avio_rb32(pb) / 65536.0;
4585  av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
4586  e->duration, e->time, e->rate);
4587 
4588  if (e->time < 0 && e->time != -1 &&
4590  av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
4591  c->fc->nb_streams-1, i, e->time);
4592  return AVERROR_INVALIDDATA;
4593  }
4594  }
4595  sc->elst_count = i;
4596 
4597  return 0;
4598 }
4599 
4601 {
4602  MOVStreamContext *sc;
4603 
4604  if (c->fc->nb_streams < 1)
4605  return AVERROR_INVALIDDATA;
4606  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4607  sc->timecode_track = avio_rb32(pb);
4608  return 0;
4609 }
4610 
4612 {
4613  AVStream *st;
4614  MOVStreamContext *sc;
4615  enum AVStereo3DType type;
4616  int mode;
4617 
4618  if (c->fc->nb_streams < 1)
4619  return 0;
4620 
4621  st = c->fc->streams[c->fc->nb_streams - 1];
4622  sc = st->priv_data;
4623 
4624  if (atom.size < 5) {
4625  av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
4626  return AVERROR_INVALIDDATA;
4627  }
4628  avio_skip(pb, 4); /* version + flags */
4629 
4630  mode = avio_r8(pb);
4631  switch (mode) {
4632  case 0:
4633  type = AV_STEREO3D_2D;
4634  break;
4635  case 1:
4636  type = AV_STEREO3D_TOPBOTTOM;
4637  break;
4638  case 2:
4639  type = AV_STEREO3D_SIDEBYSIDE;
4640  break;
4641  default:
4642  av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
4643  return 0;
4644  }
4645 
4646  sc->stereo3d = av_stereo3d_alloc();
4647  if (!sc->stereo3d)
4648  return AVERROR(ENOMEM);
4649 
4650  sc->stereo3d->type = type;
4651  return 0;
4652 }
4653 
4655 {
4656  AVStream *st;
4657  MOVStreamContext *sc;
4658  int size, layout;
4659  int32_t yaw, pitch, roll;
4660  uint32_t l = 0, t = 0, r = 0, b = 0;
4661  uint32_t tag, padding = 0;
4662  enum AVSphericalProjection projection;
4663 
4664  if (c->fc->nb_streams < 1)
4665  return 0;
4666 
4667  st = c->fc->streams[c->fc->nb_streams - 1];
4668  sc = st->priv_data;
4669 
4670  if (atom.size < 8) {
4671  av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
4672  return AVERROR_INVALIDDATA;
4673  }
4674 
4675  size = avio_rb32(pb);
4676  if (size <= 12 || size > atom.size)
4677  return AVERROR_INVALIDDATA;
4678 
4679  tag = avio_rl32(pb);
4680  if (tag != MKTAG('s','v','h','d')) {
4681  av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
4682  return 0;
4683  }
4684  avio_skip(pb, 4); /* version + flags */
4685  avio_skip(pb, size - 12); /* metadata_source */
4686 
4687  size = avio_rb32(pb);
4688  if (size > atom.size)
4689  return AVERROR_INVALIDDATA;
4690 
4691  tag = avio_rl32(pb);
4692  if (tag != MKTAG('p','r','o','j')) {
4693  av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
4694  return 0;
4695  }
4696 
4697  size = avio_rb32(pb);
4698  if (size > atom.size)
4699  return AVERROR_INVALIDDATA;
4700 
4701  tag = avio_rl32(pb);
4702  if (tag != MKTAG('p','r','h','d')) {
4703  av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
4704  return 0;
4705  }
4706  avio_skip(pb, 4); /* version + flags */
4707 
4708  /* 16.16 fixed point */