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