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