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