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