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