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