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