FFmpeg  4.1.11
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  if (n_hmmt > len / 4)
292  return AVERROR_INVALIDDATA;
293  for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
294  int moment_time = avio_rb32(pb);
295  avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
296  }
297  if (avio_feof(pb))
298  return AVERROR_INVALIDDATA;
299  return 0;
300 }
301 
303 {
304  char tmp_key[5];
305  char key2[32], language[4] = {0};
306  char *str = NULL;
307  const char *key = NULL;
308  uint16_t langcode = 0;
309  uint32_t data_type = 0, str_size, str_size_alloc;
310  int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
311  int raw = 0;
312  int num = 0;
313 
314  switch (atom.type) {
315  case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
316  case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
317  case MKTAG( 'X','M','P','_'):
318  if (c->export_xmp) { key = "xmp"; raw = 1; } break;
319  case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
320  case MKTAG( 'a','k','I','D'): key = "account_type";
322  case MKTAG( 'a','p','I','D'): key = "account_id"; break;
323  case MKTAG( 'c','a','t','g'): key = "category"; break;
324  case MKTAG( 'c','p','i','l'): key = "compilation";
326  case MKTAG( 'c','p','r','t'): key = "copyright"; break;
327  case MKTAG( 'd','e','s','c'): key = "description"; break;
328  case MKTAG( 'd','i','s','k'): key = "disc";
330  case MKTAG( 'e','g','i','d'): key = "episode_uid";
332  case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
333  case MKTAG( 'g','n','r','e'): key = "genre";
334  parse = mov_metadata_gnre; break;
335  case MKTAG( 'h','d','v','d'): key = "hd_video";
337  case MKTAG( 'H','M','M','T'):
338  return mov_metadata_hmmt(c, pb, atom.size);
339  case MKTAG( 'k','e','y','w'): key = "keywords"; break;
340  case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
341  case MKTAG( 'l','o','c','i'):
342  return mov_metadata_loci(c, pb, atom.size);
343  case MKTAG( 'm','a','n','u'): key = "make"; break;
344  case MKTAG( 'm','o','d','l'): key = "model"; break;
345  case MKTAG( 'p','c','s','t'): key = "podcast";
347  case MKTAG( 'p','g','a','p'): key = "gapless_playback";
349  case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
350  case MKTAG( 'r','t','n','g'): key = "rating";
352  case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
353  case MKTAG( 's','o','a','l'): key = "sort_album"; break;
354  case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
355  case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
356  case MKTAG( 's','o','n','m'): key = "sort_name"; break;
357  case MKTAG( 's','o','s','n'): key = "sort_show"; break;
358  case MKTAG( 's','t','i','k'): key = "media_type";
360  case MKTAG( 't','r','k','n'): key = "track";
362  case MKTAG( 't','v','e','n'): key = "episode_id"; break;
363  case MKTAG( 't','v','e','s'): key = "episode_sort";
365  case MKTAG( 't','v','n','n'): key = "network"; break;
366  case MKTAG( 't','v','s','h'): key = "show"; break;
367  case MKTAG( 't','v','s','n'): key = "season_number";
369  case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
370  case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
371  case MKTAG(0xa9,'a','l','b'): key = "album"; break;
372  case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
373  case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
374  case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
375  case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
376  case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
377  case MKTAG(0xa9,'d','a','y'): key = "date"; break;
378  case MKTAG(0xa9,'d','i','r'): key = "director"; break;
379  case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
380  case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
381  case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
382  case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
383  case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
384  case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
385  case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
386  case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
387  case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
388  case MKTAG(0xa9,'m','a','k'): key = "make"; break;
389  case MKTAG(0xa9,'m','o','d'): key = "model"; break;
390  case MKTAG(0xa9,'n','a','m'): key = "title"; break;
391  case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
392  case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
393  case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
394  case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
395  case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
396  case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
397  case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
398  case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
399  case MKTAG(0xa9,'t','r','k'): key = "track"; break;
400  case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
401  case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
402  case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
403  case MKTAG(0xa9,'x','y','z'): key = "location"; break;
404  }
405 retry:
406  if (c->itunes_metadata && atom.size > 8) {
407  int data_size = avio_rb32(pb);
408  int tag = avio_rl32(pb);
409  if (tag == MKTAG('d','a','t','a') && data_size <= atom.size && data_size >= 16) {
410  data_type = avio_rb32(pb); // type
411  avio_rb32(pb); // unknown
412  str_size = data_size - 16;
413  atom.size -= 16;
414 
415  if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
416  int ret = mov_read_covr(c, pb, data_type, str_size);
417  if (ret < 0) {
418  av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
419  return ret;
420  }
421  atom.size -= str_size;
422  if (atom.size > 8)
423  goto retry;
424  return ret;
425  } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
426  uint32_t index = AV_RB32(&atom.type);
427  if (index < c->meta_keys_count && index > 0) {
428  key = c->meta_keys[index];
429  } else {
431  "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
432  index, c->meta_keys_count);
433  }
434  }
435  } else return 0;
436  } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
437  str_size = avio_rb16(pb); // string length
438  if (str_size > atom.size) {
439  raw = 1;
440  avio_seek(pb, -2, SEEK_CUR);
441  av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
442  goto retry;
443  }
444  langcode = avio_rb16(pb);
445  ff_mov_lang_to_iso639(langcode, language);
446  atom.size -= 4;
447  } else
448  str_size = atom.size;
449 
450  if (c->export_all && !key) {
451  snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
452  key = tmp_key;
453  }
454 
455  if (!key)
456  return 0;
457  if (atom.size < 0 || str_size >= INT_MAX/2)
458  return AVERROR_INVALIDDATA;
459 
460  // Allocates enough space if data_type is a int32 or float32 number, otherwise
461  // worst-case requirement for output string in case of utf8 coded input
462  num = (data_type >= 21 && data_type <= 23);
463  str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
464  str = av_mallocz(str_size_alloc);
465  if (!str)
466  return AVERROR(ENOMEM);
467 
468  if (parse)
469  parse(c, pb, str_size, key);
470  else {
471  if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
472  mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
473  } else if (data_type == 21) { // BE signed integer, variable size
474  int val = 0;
475  if (str_size == 1)
476  val = (int8_t)avio_r8(pb);
477  else if (str_size == 2)
478  val = (int16_t)avio_rb16(pb);
479  else if (str_size == 3)
480  val = ((int32_t)(avio_rb24(pb)<<8))>>8;
481  else if (str_size == 4)
482  val = (int32_t)avio_rb32(pb);
483  if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
484  av_log(c->fc, AV_LOG_ERROR,
485  "Failed to store the number (%d) in string.\n", val);
486  av_free(str);
487  return AVERROR_INVALIDDATA;
488  }
489  } else if (data_type == 22) { // BE unsigned integer, variable size
490  unsigned int val = 0;
491  if (str_size == 1)
492  val = avio_r8(pb);
493  else if (str_size == 2)
494  val = avio_rb16(pb);
495  else if (str_size == 3)
496  val = avio_rb24(pb);
497  else if (str_size == 4)
498  val = avio_rb32(pb);
499  if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
500  av_log(c->fc, AV_LOG_ERROR,
501  "Failed to store the number (%u) in string.\n", val);
502  av_free(str);
503  return AVERROR_INVALIDDATA;
504  }
505  } else if (data_type == 23 && str_size >= 4) { // BE float32
506  float val = av_int2float(avio_rb32(pb));
507  if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
508  av_log(c->fc, AV_LOG_ERROR,
509  "Failed to store the float32 number (%f) in string.\n", val);
510  av_free(str);
511  return AVERROR_INVALIDDATA;
512  }
513  } else {
514  int ret = ffio_read_size(pb, str, str_size);
515  if (ret < 0) {
516  av_free(str);
517  return ret;
518  }
519  str[str_size] = 0;
520  }
522  av_dict_set(&c->fc->metadata, key, str, 0);
523  if (*language && strcmp(language, "und")) {
524  snprintf(key2, sizeof(key2), "%s-%s", key, language);
525  av_dict_set(&c->fc->metadata, key2, str, 0);
526  }
527  if (!strcmp(key, "encoder")) {
528  int major, minor, micro;
529  if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
530  c->handbrake_version = 1000000*major + 1000*minor + micro;
531  }
532  }
533  }
534 
535  av_freep(&str);
536  return 0;
537 }
538 
540 {
541  int64_t start;
542  int i, nb_chapters, str_len, version;
543  char str[256+1];
544  int ret;
545 
546  if (c->ignore_chapters)
547  return 0;
548 
549  if ((atom.size -= 5) < 0)
550  return 0;
551 
552  version = avio_r8(pb);
553  avio_rb24(pb);
554  if (version)
555  avio_rb32(pb); // ???
556  nb_chapters = avio_r8(pb);
557 
558  for (i = 0; i < nb_chapters; i++) {
559  if (atom.size < 9)
560  return 0;
561 
562  start = avio_rb64(pb);
563  str_len = avio_r8(pb);
564 
565  if ((atom.size -= 9+str_len) < 0)
566  return 0;
567 
568  ret = ffio_read_size(pb, str, str_len);
569  if (ret < 0)
570  return ret;
571  str[str_len] = 0;
572  avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
573  }
574  return 0;
575 }
576 
577 #define MIN_DATA_ENTRY_BOX_SIZE 12
579 {
580  AVStream *st;
581  MOVStreamContext *sc;
582  int entries, i, j;
583 
584  if (c->fc->nb_streams < 1)
585  return 0;
586  st = c->fc->streams[c->fc->nb_streams-1];
587  sc = st->priv_data;
588 
589  avio_rb32(pb); // version + flags
590  entries = avio_rb32(pb);
591  if (!entries ||
592  entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
593  entries >= UINT_MAX / sizeof(*sc->drefs))
594  return AVERROR_INVALIDDATA;
595  sc->drefs_count = 0;
596  av_free(sc->drefs);
597  sc->drefs_count = 0;
598  sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
599  if (!sc->drefs)
600  return AVERROR(ENOMEM);
601  sc->drefs_count = entries;
602 
603  for (i = 0; i < entries; i++) {
604  MOVDref *dref = &sc->drefs[i];
605  uint32_t size = avio_rb32(pb);
606  int64_t next = avio_tell(pb);
607 
608  if (size < 12 || next < 0 || next > INT64_MAX - size)
609  return AVERROR_INVALIDDATA;
610 
611  next += size - 4;
612 
613  dref->type = avio_rl32(pb);
614  avio_rb32(pb); // version + flags
615 
616  if (dref->type == MKTAG('a','l','i','s') && size > 150) {
617  /* macintosh alias record */
618  uint16_t volume_len, len;
619  int16_t type;
620  int ret;
621 
622  avio_skip(pb, 10);
623 
624  volume_len = avio_r8(pb);
625  volume_len = FFMIN(volume_len, 27);
626  ret = ffio_read_size(pb, dref->volume, 27);
627  if (ret < 0)
628  return ret;
629  dref->volume[volume_len] = 0;
630  av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
631 
632  avio_skip(pb, 12);
633 
634  len = avio_r8(pb);
635  len = FFMIN(len, 63);
636  ret = ffio_read_size(pb, dref->filename, 63);
637  if (ret < 0)
638  return ret;
639  dref->filename[len] = 0;
640  av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
641 
642  avio_skip(pb, 16);
643 
644  /* read next level up_from_alias/down_to_target */
645  dref->nlvl_from = avio_rb16(pb);
646  dref->nlvl_to = avio_rb16(pb);
647  av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
648  dref->nlvl_from, dref->nlvl_to);
649 
650  avio_skip(pb, 16);
651 
652  for (type = 0; type != -1 && avio_tell(pb) < next; ) {
653  if(avio_feof(pb))
654  return AVERROR_EOF;
655  type = avio_rb16(pb);
656  len = avio_rb16(pb);
657  av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
658  if (len&1)
659  len += 1;
660  if (type == 2) { // absolute path
661  av_free(dref->path);
662  dref->path = av_mallocz(len+1);
663  if (!dref->path)
664  return AVERROR(ENOMEM);
665 
666  ret = ffio_read_size(pb, dref->path, len);
667  if (ret < 0) {
668  av_freep(&dref->path);
669  return ret;
670  }
671  if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
672  len -= volume_len;
673  memmove(dref->path, dref->path+volume_len, len);
674  dref->path[len] = 0;
675  }
676  // trim string of any ending zeros
677  for (j = len - 1; j >= 0; j--) {
678  if (dref->path[j] == 0)
679  len--;
680  else
681  break;
682  }
683  for (j = 0; j < len; j++)
684  if (dref->path[j] == ':' || dref->path[j] == 0)
685  dref->path[j] = '/';
686  av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
687  } else if (type == 0) { // directory name
688  av_free(dref->dir);
689  dref->dir = av_malloc(len+1);
690  if (!dref->dir)
691  return AVERROR(ENOMEM);
692 
693  ret = ffio_read_size(pb, dref->dir, len);
694  if (ret < 0) {
695  av_freep(&dref->dir);
696  return ret;
697  }
698  dref->dir[len] = 0;
699  for (j = 0; j < len; j++)
700  if (dref->dir[j] == ':')
701  dref->dir[j] = '/';
702  av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
703  } else
704  avio_skip(pb, len);
705  }
706  } else {
707  av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
708  dref->type, size);
709  entries--;
710  i--;
711  }
712  avio_seek(pb, next, SEEK_SET);
713  }
714  return 0;
715 }
716 
718 {
719  AVStream *st;
720  uint32_t type;
721  uint32_t ctype;
722  int64_t title_size;
723  char *title_str;
724  int ret;
725 
726  avio_r8(pb); /* version */
727  avio_rb24(pb); /* flags */
728 
729  /* component type */
730  ctype = avio_rl32(pb);
731  type = avio_rl32(pb); /* component subtype */
732 
733  av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
734  av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
735 
736  if (c->trak_index < 0) { // meta not inside a trak
737  if (type == MKTAG('m','d','t','a')) {
738  c->found_hdlr_mdta = 1;
739  }
740  return 0;
741  }
742 
743  st = c->fc->streams[c->fc->nb_streams-1];
744 
745  if (type == MKTAG('v','i','d','e'))
747  else if (type == MKTAG('s','o','u','n'))
749  else if (type == MKTAG('m','1','a',' '))
751  else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
753 
754  avio_rb32(pb); /* component manufacture */
755  avio_rb32(pb); /* component flags */
756  avio_rb32(pb); /* component flags mask */
757 
758  title_size = atom.size - 24;
759  if (title_size > 0) {
760  if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
761  return AVERROR_INVALIDDATA;
762  title_str = av_malloc(title_size + 1); /* Add null terminator */
763  if (!title_str)
764  return AVERROR(ENOMEM);
765 
766  ret = ffio_read_size(pb, title_str, title_size);
767  if (ret < 0) {
768  av_freep(&title_str);
769  return ret;
770  }
771  title_str[title_size] = 0;
772  if (title_str[0]) {
773  int off = (!c->isom && title_str[0] == title_size - 1);
774  // flag added so as to not set stream handler name if already set from mdia->hdlr
775  av_dict_set(&st->metadata, "handler_name", title_str + off, AV_DICT_DONT_OVERWRITE);
776  }
777  av_freep(&title_str);
778  }
779 
780  return 0;
781 }
782 
784 {
785  return ff_mov_read_esds(c->fc, pb);
786 }
787 
789 {
790  AVStream *st;
791  enum AVAudioServiceType *ast;
792  int ac3info, acmod, lfeon, bsmod;
793 
794  if (c->fc->nb_streams < 1)
795  return 0;
796  st = c->fc->streams[c->fc->nb_streams-1];
797 
799  sizeof(*ast));
800  if (!ast)
801  return AVERROR(ENOMEM);
802 
803  ac3info = avio_rb24(pb);
804  bsmod = (ac3info >> 14) & 0x7;
805  acmod = (ac3info >> 11) & 0x7;
806  lfeon = (ac3info >> 10) & 0x1;
807  st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
809  if (lfeon)
811  *ast = bsmod;
812  if (st->codecpar->channels > 1 && bsmod == 0x7)
814 
815 #if FF_API_LAVF_AVCTX
817  st->codec->audio_service_type = *ast;
819 #endif
820 
821  return 0;
822 }
823 
825 {
826  AVStream *st;
827  enum AVAudioServiceType *ast;
828  int eac3info, acmod, lfeon, bsmod;
829 
830  if (c->fc->nb_streams < 1)
831  return 0;
832  st = c->fc->streams[c->fc->nb_streams-1];
833 
835  sizeof(*ast));
836  if (!ast)
837  return AVERROR(ENOMEM);
838 
839  /* No need to parse fields for additional independent substreams and its
840  * associated dependent substreams since libavcodec's E-AC-3 decoder
841  * does not support them yet. */
842  avio_rb16(pb); /* data_rate and num_ind_sub */
843  eac3info = avio_rb24(pb);
844  bsmod = (eac3info >> 12) & 0x1f;
845  acmod = (eac3info >> 9) & 0x7;
846  lfeon = (eac3info >> 8) & 0x1;
848  if (lfeon)
851  *ast = bsmod;
852  if (st->codecpar->channels > 1 && bsmod == 0x7)
854 
855 #if FF_API_LAVF_AVCTX
857  st->codec->audio_service_type = *ast;
859 #endif
860 
861  return 0;
862 }
863 
865 {
866  const uint32_t ddts_size = 20;
867  AVStream *st = NULL;
868  uint8_t *buf = NULL;
869  uint32_t frame_duration_code = 0;
870  uint32_t channel_layout_code = 0;
871  GetBitContext gb;
872 
873  buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
874  if (!buf) {
875  return AVERROR(ENOMEM);
876  }
877  if (avio_read(pb, buf, ddts_size) < ddts_size) {
878  av_free(buf);
879  return AVERROR_INVALIDDATA;
880  }
881 
882  init_get_bits(&gb, buf, 8*ddts_size);
883 
884  if (c->fc->nb_streams < 1) {
885  av_free(buf);
886  return 0;
887  }
888  st = c->fc->streams[c->fc->nb_streams-1];
889 
890  st->codecpar->sample_rate = get_bits_long(&gb, 32);
891  if (st->codecpar->sample_rate <= 0) {
892  av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
893  av_free(buf);
894  return AVERROR_INVALIDDATA;
895  }
896  skip_bits_long(&gb, 32); /* max bitrate */
897  st->codecpar->bit_rate = get_bits_long(&gb, 32);
898  st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
899  frame_duration_code = get_bits(&gb, 2);
900  skip_bits(&gb, 30); /* various fields */
901  channel_layout_code = get_bits(&gb, 16);
902 
903  st->codecpar->frame_size =
904  (frame_duration_code == 0) ? 512 :
905  (frame_duration_code == 1) ? 1024 :
906  (frame_duration_code == 2) ? 2048 :
907  (frame_duration_code == 3) ? 4096 : 0;
908 
909  if (channel_layout_code > 0xff) {
910  av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
911  }
912  st->codecpar->channel_layout =
913  ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
914  ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
915  ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
916  ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
917  ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
918  ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
919 
921  av_free(buf);
922 
923  return 0;
924 }
925 
927 {
928  AVStream *st;
929 
930  if (c->fc->nb_streams < 1)
931  return 0;
932  st = c->fc->streams[c->fc->nb_streams-1];
933 
934  if (atom.size < 16)
935  return 0;
936 
937  /* skip version and flags */
938  avio_skip(pb, 4);
939 
940  ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
941 
942  return 0;
943 }
944 
946 {
947  AVStream *st;
948  int ret;
949 
950  if (c->fc->nb_streams < 1)
951  return 0;
952  st = c->fc->streams[c->fc->nb_streams-1];
953 
954  if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
955  av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
956 
957  return ret;
958 }
959 
961 {
962  const int num = avio_rb32(pb);
963  const int den = avio_rb32(pb);
964  AVStream *st;
965 
966  if (c->fc->nb_streams < 1)
967  return 0;
968  st = c->fc->streams[c->fc->nb_streams-1];
969 
970  if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
971  (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
973  "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
975  num, den);
976  } else if (den != 0) {
978  num, den, 32767);
979  }
980  return 0;
981 }
982 
983 /* this atom contains actual media data */
985 {
986  if (atom.size == 0) /* wrong one (MP4) */
987  return 0;
988  c->found_mdat=1;
989  return 0; /* now go for moov */
990 }
991 
992 #define DRM_BLOB_SIZE 56
993 
995 {
996  uint8_t intermediate_key[20];
997  uint8_t intermediate_iv[20];
998  uint8_t input[64];
999  uint8_t output[64];
1000  uint8_t file_checksum[20];
1001  uint8_t calculated_checksum[20];
1002  struct AVSHA *sha;
1003  int i;
1004  int ret = 0;
1005  uint8_t *activation_bytes = c->activation_bytes;
1006  uint8_t *fixed_key = c->audible_fixed_key;
1007 
1008  c->aax_mode = 1;
1009 
1010  sha = av_sha_alloc();
1011  if (!sha)
1012  return AVERROR(ENOMEM);
1013  av_free(c->aes_decrypt);
1014  c->aes_decrypt = av_aes_alloc();
1015  if (!c->aes_decrypt) {
1016  ret = AVERROR(ENOMEM);
1017  goto fail;
1018  }
1019 
1020  /* drm blob processing */
1021  avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1022  avio_read(pb, input, DRM_BLOB_SIZE);
1023  avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1024  avio_read(pb, file_checksum, 20);
1025 
1026  av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1027  for (i = 0; i < 20; i++)
1028  av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1029  av_log(c->fc, AV_LOG_INFO, "\n");
1030 
1031  /* verify activation data */
1032  if (!activation_bytes) {
1033  av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1034  ret = 0; /* allow ffprobe to continue working on .aax files */
1035  goto fail;
1036  }
1037  if (c->activation_bytes_size != 4) {
1038  av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1039  ret = AVERROR(EINVAL);
1040  goto fail;
1041  }
1042 
1043  /* verify fixed key */
1044  if (c->audible_fixed_key_size != 16) {
1045  av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1046  ret = AVERROR(EINVAL);
1047  goto fail;
1048  }
1049 
1050  /* AAX (and AAX+) key derivation */
1051  av_sha_init(sha, 160);
1052  av_sha_update(sha, fixed_key, 16);
1053  av_sha_update(sha, activation_bytes, 4);
1054  av_sha_final(sha, intermediate_key);
1055  av_sha_init(sha, 160);
1056  av_sha_update(sha, fixed_key, 16);
1057  av_sha_update(sha, intermediate_key, 20);
1058  av_sha_update(sha, activation_bytes, 4);
1059  av_sha_final(sha, intermediate_iv);
1060  av_sha_init(sha, 160);
1061  av_sha_update(sha, intermediate_key, 16);
1062  av_sha_update(sha, intermediate_iv, 16);
1063  av_sha_final(sha, calculated_checksum);
1064  if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1065  av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1066  ret = AVERROR_INVALIDDATA;
1067  goto fail;
1068  }
1069  av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1070  av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1071  for (i = 0; i < 4; i++) {
1072  // file data (in output) is stored in big-endian mode
1073  if (activation_bytes[i] != output[3 - i]) { // critical error
1074  av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1075  ret = AVERROR_INVALIDDATA;
1076  goto fail;
1077  }
1078  }
1079  memcpy(c->file_key, output + 8, 16);
1080  memcpy(input, output + 26, 16);
1081  av_sha_init(sha, 160);
1082  av_sha_update(sha, input, 16);
1083  av_sha_update(sha, c->file_key, 16);
1084  av_sha_update(sha, fixed_key, 16);
1085  av_sha_final(sha, c->file_iv);
1086 
1087 fail:
1088  av_free(sha);
1089 
1090  return ret;
1091 }
1092 
1093 // Audible AAX (and AAX+) bytestream decryption
1094 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1095 {
1096  int blocks = 0;
1097  unsigned char iv[16];
1098 
1099  memcpy(iv, c->file_iv, 16); // iv is overwritten
1100  blocks = size >> 4; // trailing bytes are not encrypted!
1101  av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1102  av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1103 
1104  return 0;
1105 }
1106 
1107 /* read major brand, minor version and compatible brands and store them as metadata */
1109 {
1110  uint32_t minor_ver;
1111  int comp_brand_size;
1112  char* comp_brands_str;
1113  uint8_t type[5] = {0};
1114  int ret = ffio_read_size(pb, type, 4);
1115  if (ret < 0)
1116  return ret;
1117 
1118  if (strcmp(type, "qt "))
1119  c->isom = 1;
1120  av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1121  av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1122  minor_ver = avio_rb32(pb); /* minor version */
1123  av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1124 
1125  comp_brand_size = atom.size - 8;
1126  if (comp_brand_size < 0 || comp_brand_size == INT_MAX)
1127  return AVERROR_INVALIDDATA;
1128  comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1129  if (!comp_brands_str)
1130  return AVERROR(ENOMEM);
1131 
1132  ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1133  if (ret < 0) {
1134  av_freep(&comp_brands_str);
1135  return ret;
1136  }
1137  comp_brands_str[comp_brand_size] = 0;
1138  av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1139  av_freep(&comp_brands_str);
1140 
1141  return 0;
1142 }
1143 
1144 /* this atom should contain all header atoms */
1146 {
1147  int ret;
1148 
1149  if (c->found_moov) {
1150  av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1151  avio_skip(pb, atom.size);
1152  return 0;
1153  }
1154 
1155  if ((ret = mov_read_default(c, pb, atom)) < 0)
1156  return ret;
1157  /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1158  /* so we don't parse the whole file if over a network */
1159  c->found_moov=1;
1160  return 0; /* now go for mdat */
1161 }
1162 
1164  MOVFragmentIndex *frag_index,
1165  int index,
1166  int id)
1167 {
1168  int i;
1169  MOVFragmentIndexItem * item;
1170 
1171  if (index < 0 || index >= frag_index->nb_items)
1172  return NULL;
1173  item = &frag_index->item[index];
1174  for (i = 0; i < item->nb_stream_info; i++)
1175  if (item->stream_info[i].id == id)
1176  return &item->stream_info[i];
1177 
1178  // This shouldn't happen
1179  return NULL;
1180 }
1181 
1182 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1183 {
1184  int i;
1185  MOVFragmentIndexItem * item;
1186 
1187  if (frag_index->current < 0 ||
1188  frag_index->current >= frag_index->nb_items)
1189  return;
1190 
1191  item = &frag_index->item[frag_index->current];
1192  for (i = 0; i < item->nb_stream_info; i++)
1193  if (item->stream_info[i].id == id) {
1194  item->current = i;
1195  return;
1196  }
1197 
1198  // id not found. This shouldn't happen.
1199  item->current = -1;
1200 }
1201 
1203  MOVFragmentIndex *frag_index)
1204 {
1205  MOVFragmentIndexItem *item;
1206  if (frag_index->current < 0 ||
1207  frag_index->current >= frag_index->nb_items)
1208  return NULL;
1209 
1210  item = &frag_index->item[frag_index->current];
1211  if (item->current >= 0 && item->current < item->nb_stream_info)
1212  return &item->stream_info[item->current];
1213 
1214  // This shouldn't happen
1215  return NULL;
1216 }
1217 
1218 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1219 {
1220  int a, b, m;
1221  int64_t moof_offset;
1222 
1223  // Optimize for appending new entries
1224  if (!frag_index->nb_items ||
1225  frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1226  return frag_index->nb_items;
1227 
1228  a = -1;
1229  b = frag_index->nb_items;
1230 
1231  while (b - a > 1) {
1232  m = (a + b) >> 1;
1233  moof_offset = frag_index->item[m].moof_offset;
1234  if (moof_offset >= offset)
1235  b = m;
1236  if (moof_offset <= offset)
1237  a = m;
1238  }
1239  return b;
1240 }
1241 
1242 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1243 {
1244 
1245  if (frag_stream_info) {
1246  if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1247  return frag_stream_info->sidx_pts;
1248  if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1249  return frag_stream_info->first_tfra_pts;
1250  if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1251  return frag_stream_info->tfdt_dts;
1252  }
1253  return AV_NOPTS_VALUE;
1254 }
1255 
1256 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1257  int index, int track_id)
1258 {
1259  MOVFragmentStreamInfo * frag_stream_info;
1260  int64_t timestamp;
1261  int i;
1262 
1263  if (track_id >= 0) {
1264  frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1265  return frag_stream_info->sidx_pts;
1266  }
1267 
1268  for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1269  frag_stream_info = &frag_index->item[index].stream_info[i];
1270  timestamp = get_stream_info_time(frag_stream_info);
1271  if (timestamp != AV_NOPTS_VALUE)
1272  return timestamp;
1273  }
1274  return AV_NOPTS_VALUE;
1275 }
1276 
1278  AVStream *st, int64_t timestamp)
1279 {
1280  int a, b, m, m0;
1281  int64_t frag_time;
1282  int id = -1;
1283 
1284  if (st) {
1285  // If the stream is referenced by any sidx, limit the search
1286  // to fragments that referenced this stream in the sidx
1287  MOVStreamContext *sc = st->priv_data;
1288  if (sc->has_sidx)
1289  id = st->id;
1290  }
1291 
1292  a = -1;
1293  b = frag_index->nb_items;
1294 
1295  while (b - a > 1) {
1296  m0 = m = (a + b) >> 1;
1297 
1298  while (m < b &&
1299  (frag_time = get_frag_time(frag_index, m, id)) == AV_NOPTS_VALUE)
1300  m++;
1301 
1302  if (m < b && frag_time <= timestamp)
1303  a = m;
1304  else
1305  b = m0;
1306  }
1307 
1308  return a;
1309 }
1310 
1311 static int update_frag_index(MOVContext *c, int64_t offset)
1312 {
1313  int index, i;
1314  MOVFragmentIndexItem * item;
1315  MOVFragmentStreamInfo * frag_stream_info;
1316 
1317  // If moof_offset already exists in frag_index, return index to it
1318  index = search_frag_moof_offset(&c->frag_index, offset);
1319  if (index < c->frag_index.nb_items &&
1320  c->frag_index.item[index].moof_offset == offset)
1321  return index;
1322 
1323  // offset is not yet in frag index.
1324  // Insert new item at index (sorted by moof offset)
1325  item = av_fast_realloc(c->frag_index.item,
1327  (c->frag_index.nb_items + 1) *
1328  sizeof(*c->frag_index.item));
1329  if(!item)
1330  return -1;
1331  c->frag_index.item = item;
1332 
1333  frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1334  sizeof(*item->stream_info));
1335  if (!frag_stream_info)
1336  return -1;
1337 
1338  for (i = 0; i < c->fc->nb_streams; i++) {
1339  // Avoid building frag index if streams lack track id.
1340  if (c->fc->streams[i]->id < 0) {
1341  av_free(frag_stream_info);
1342  return AVERROR_INVALIDDATA;
1343  }
1344 
1345  frag_stream_info[i].id = c->fc->streams[i]->id;
1346  frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1347  frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1348  frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1349  frag_stream_info[i].index_entry = -1;
1350  frag_stream_info[i].encryption_index = NULL;
1351  }
1352 
1353  if (index < c->frag_index.nb_items)
1354  memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1355  (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1356 
1357  item = &c->frag_index.item[index];
1358  item->headers_read = 0;
1359  item->current = 0;
1360  item->nb_stream_info = c->fc->nb_streams;
1361  item->moof_offset = offset;
1362  item->stream_info = frag_stream_info;
1363  c->frag_index.nb_items++;
1364 
1365  return index;
1366 }
1367 
1368 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1369  int id, int entries)
1370 {
1371  int i;
1372  MOVFragmentStreamInfo * frag_stream_info;
1373 
1374  if (index < 0)
1375  return;
1376  for (i = index; i < frag_index->nb_items; i++) {
1377  frag_stream_info = get_frag_stream_info(frag_index, i, id);
1378  if (frag_stream_info && frag_stream_info->index_entry >= 0)
1379  frag_stream_info->index_entry += entries;
1380  }
1381 }
1382 
1384 {
1385  // Set by mov_read_tfhd(). mov_read_trun() will reject files missing tfhd.
1386  c->fragment.found_tfhd = 0;
1387 
1388  if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1389  c->has_looked_for_mfra = 1;
1390  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1391  int ret;
1392  av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1393  "for a mfra\n");
1394  if ((ret = mov_read_mfra(c, pb)) < 0) {
1395  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1396  "read the mfra (may be a live ismv)\n");
1397  }
1398  } else {
1399  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1400  "seekable, can not look for mfra\n");
1401  }
1402  }
1404  av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1406  return mov_read_default(c, pb, atom);
1407 }
1408 
1409 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1410 {
1411  if (time) {
1412  if(time >= 2082844800)
1413  time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1414 
1415  if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1416  av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1417  return;
1418  }
1419 
1420  avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1421  }
1422 }
1423 
1425 {
1426  AVStream *st;
1427  MOVStreamContext *sc;
1428  int version;
1429  char language[4] = {0};
1430  unsigned lang;
1431  int64_t creation_time;
1432 
1433  if (c->fc->nb_streams < 1)
1434  return 0;
1435  st = c->fc->streams[c->fc->nb_streams-1];
1436  sc = st->priv_data;
1437 
1438  if (sc->time_scale) {
1439  av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1440  return AVERROR_INVALIDDATA;
1441  }
1442 
1443  version = avio_r8(pb);
1444  if (version > 1) {
1445  avpriv_request_sample(c->fc, "Version %d", version);
1446  return AVERROR_PATCHWELCOME;
1447  }
1448  avio_rb24(pb); /* flags */
1449  if (version == 1) {
1450  creation_time = avio_rb64(pb);
1451  avio_rb64(pb);
1452  } else {
1453  creation_time = avio_rb32(pb);
1454  avio_rb32(pb); /* modification time */
1455  }
1456  mov_metadata_creation_time(&st->metadata, creation_time);
1457 
1458  sc->time_scale = avio_rb32(pb);
1459  if (sc->time_scale <= 0) {
1460  av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1461  sc->time_scale = 1;
1462  }
1463  st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1464 
1465  lang = avio_rb16(pb); /* language */
1466  if (ff_mov_lang_to_iso639(lang, language))
1467  av_dict_set(&st->metadata, "language", language, 0);
1468  avio_rb16(pb); /* quality */
1469 
1470  return 0;
1471 }
1472 
1474 {
1475  int i;
1476  int64_t creation_time;
1477  int version = avio_r8(pb); /* version */
1478  avio_rb24(pb); /* flags */
1479 
1480  if (version == 1) {
1481  creation_time = avio_rb64(pb);
1482  avio_rb64(pb);
1483  } else {
1484  creation_time = avio_rb32(pb);
1485  avio_rb32(pb); /* modification time */
1486  }
1487  mov_metadata_creation_time(&c->fc->metadata, creation_time);
1488  c->time_scale = avio_rb32(pb); /* time scale */
1489  if (c->time_scale <= 0) {
1490  av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1491  c->time_scale = 1;
1492  }
1493  av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1494 
1495  c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1496  // set the AVCodecContext duration because the duration of individual tracks
1497  // may be inaccurate
1498  if (c->time_scale > 0 && !c->trex_data)
1500  avio_rb32(pb); /* preferred scale */
1501 
1502  avio_rb16(pb); /* preferred volume */
1503 
1504  avio_skip(pb, 10); /* reserved */
1505 
1506  /* movie display matrix, store it in main context and use it later on */
1507  for (i = 0; i < 3; i++) {
1508  c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1509  c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1510  c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
1511  }
1512 
1513  avio_rb32(pb); /* preview time */
1514  avio_rb32(pb); /* preview duration */
1515  avio_rb32(pb); /* poster time */
1516  avio_rb32(pb); /* selection time */
1517  avio_rb32(pb); /* selection duration */
1518  avio_rb32(pb); /* current time */
1519  avio_rb32(pb); /* next track ID */
1520 
1521  return 0;
1522 }
1523 
1525 {
1526  AVStream *st;
1527  int little_endian;
1528 
1529  if (c->fc->nb_streams < 1)
1530  return 0;
1531  st = c->fc->streams[c->fc->nb_streams-1];
1532 
1533  little_endian = avio_rb16(pb) & 0xFF;
1534  av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1535  if (little_endian == 1) {
1536  switch (st->codecpar->codec_id) {
1537  case AV_CODEC_ID_PCM_S24BE:
1539  break;
1540  case AV_CODEC_ID_PCM_S32BE:
1542  break;
1543  case AV_CODEC_ID_PCM_F32BE:
1545  break;
1546  case AV_CODEC_ID_PCM_F64BE:
1548  break;
1549  default:
1550  break;
1551  }
1552  }
1553  return 0;
1554 }
1555 
1557 {
1558  AVStream *st;
1559  char color_parameter_type[5] = { 0 };
1560  uint16_t color_primaries, color_trc, color_matrix;
1561  int ret;
1562 
1563  if (c->fc->nb_streams < 1)
1564  return 0;
1565  st = c->fc->streams[c->fc->nb_streams - 1];
1566 
1567  ret = ffio_read_size(pb, color_parameter_type, 4);
1568  if (ret < 0)
1569  return ret;
1570  if (strncmp(color_parameter_type, "nclx", 4) &&
1571  strncmp(color_parameter_type, "nclc", 4)) {
1572  av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1573  color_parameter_type);
1574  return 0;
1575  }
1576 
1577  color_primaries = avio_rb16(pb);
1578  color_trc = avio_rb16(pb);
1579  color_matrix = avio_rb16(pb);
1580 
1581  av_log(c->fc, AV_LOG_TRACE,
1582  "%s: pri %d trc %d matrix %d",
1583  color_parameter_type, color_primaries, color_trc, color_matrix);
1584 
1585  if (!strncmp(color_parameter_type, "nclx", 4)) {
1586  uint8_t color_range = avio_r8(pb) >> 7;
1587  av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1588  if (color_range)
1590  else
1592  }
1593 
1594  if (!av_color_primaries_name(color_primaries))
1595  color_primaries = AVCOL_PRI_UNSPECIFIED;
1596  if (!av_color_transfer_name(color_trc))
1597  color_trc = AVCOL_TRC_UNSPECIFIED;
1598  if (!av_color_space_name(color_matrix))
1599  color_matrix = AVCOL_SPC_UNSPECIFIED;
1600 
1602  st->codecpar->color_trc = color_trc;
1603  st->codecpar->color_space = color_matrix;
1604  av_log(c->fc, AV_LOG_TRACE, "\n");
1605 
1606  return 0;
1607 }
1608 
1610 {
1611  AVStream *st;
1612  unsigned mov_field_order;
1613  enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1614 
1615  if (c->fc->nb_streams < 1) // will happen with jp2 files
1616  return 0;
1617  st = c->fc->streams[c->fc->nb_streams-1];
1618  if (atom.size < 2)
1619  return AVERROR_INVALIDDATA;
1620  mov_field_order = avio_rb16(pb);
1621  if ((mov_field_order & 0xFF00) == 0x0100)
1622  decoded_field_order = AV_FIELD_PROGRESSIVE;
1623  else if ((mov_field_order & 0xFF00) == 0x0200) {
1624  switch (mov_field_order & 0xFF) {
1625  case 0x01: decoded_field_order = AV_FIELD_TT;
1626  break;
1627  case 0x06: decoded_field_order = AV_FIELD_BB;
1628  break;
1629  case 0x09: decoded_field_order = AV_FIELD_TB;
1630  break;
1631  case 0x0E: decoded_field_order = AV_FIELD_BT;
1632  break;
1633  }
1634  }
1635  if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1636  av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1637  }
1638  st->codecpar->field_order = decoded_field_order;
1639 
1640  return 0;
1641 }
1642 
1644 {
1645  int err = 0;
1646  uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1647  if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1648  return AVERROR_INVALIDDATA;
1649  if ((err = av_reallocp(&par->extradata, size)) < 0) {
1650  par->extradata_size = 0;
1651  return err;
1652  }
1654  return 0;
1655 }
1656 
1657 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1659  AVCodecParameters *par, uint8_t *buf)
1660 {
1661  int64_t result = atom.size;
1662  int err;
1663 
1664  AV_WB32(buf , atom.size + 8);
1665  AV_WL32(buf + 4, atom.type);
1666  err = ffio_read_size(pb, buf + 8, atom.size);
1667  if (err < 0) {
1668  par->extradata_size -= atom.size;
1669  return err;
1670  } else if (err < atom.size) {
1671  av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1672  par->extradata_size -= atom.size - err;
1673  result = err;
1674  }
1675  memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1676  return result;
1677 }
1678 
1679 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1681  enum AVCodecID codec_id)
1682 {
1683  AVStream *st;
1684  uint64_t original_size;
1685  int err;
1686 
1687  if (c->fc->nb_streams < 1) // will happen with jp2 files
1688  return 0;
1689  st = c->fc->streams[c->fc->nb_streams-1];
1690 
1691  if (st->codecpar->codec_id != codec_id)
1692  return 0; /* unexpected codec_id - don't mess with extradata */
1693 
1694  original_size = st->codecpar->extradata_size;
1695  err = mov_realloc_extradata(st->codecpar, atom);
1696  if (err)
1697  return err;
1698 
1699  err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1700  if (err < 0)
1701  return err;
1702  return 0; // Note: this is the original behavior to ignore truncation.
1703 }
1704 
1705 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1707 {
1708  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1709 }
1710 
1712 {
1713  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1714 }
1715 
1717 {
1718  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1719 }
1720 
1722 {
1723  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1724 }
1725 
1727 {
1728  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1729  if(ret == 0)
1730  ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1731  return ret;
1732 }
1733 
1735 {
1736  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1737 
1738  if (!ret && c->fc->nb_streams >= 1) {
1739  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1740  if (par->extradata_size >= 40) {
1741  par->height = AV_RB16(&par->extradata[36]);
1742  par->width = AV_RB16(&par->extradata[38]);
1743  }
1744  }
1745  return ret;
1746 }
1747 
1749 {
1750  if (c->fc->nb_streams >= 1) {
1751  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1752  if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1753  par->codec_id == AV_CODEC_ID_H264 &&
1754  atom.size > 11) {
1755  int cid;
1756  avio_skip(pb, 10);
1757  cid = avio_rb16(pb);
1758  /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1759  if (cid == 0xd4d || cid == 0xd4e)
1760  par->width = 1440;
1761  return 0;
1762  } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1763  par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
1764  par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1765  atom.size >= 24) {
1766  int num, den;
1767  avio_skip(pb, 12);
1768  num = avio_rb32(pb);
1769  den = avio_rb32(pb);
1770  if (num <= 0 || den <= 0)
1771  return 0;
1772  switch (avio_rb32(pb)) {
1773  case 2:
1774  if (den >= INT_MAX / 2)
1775  return 0;
1776  den *= 2;
1777  case 1:
1778  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1779  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1780  default:
1781  return 0;
1782  }
1783  }
1784  }
1785 
1786  return mov_read_avid(c, pb, atom);
1787 }
1788 
1790 {
1791  int ret = 0;
1792  int length = 0;
1793  uint64_t original_size;
1794  if (c->fc->nb_streams >= 1) {
1795  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1796  if (par->codec_id == AV_CODEC_ID_H264)
1797  return 0;
1798  if (atom.size == 16) {
1799  original_size = par->extradata_size;
1800  ret = mov_realloc_extradata(par, atom);
1801  if (!ret) {
1802  length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1803  if (length == atom.size) {
1804  const uint8_t range_value = par->extradata[original_size + 19];
1805  switch (range_value) {
1806  case 1:
1808  break;
1809  case 2:
1811  break;
1812  default:
1813  av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1814  break;
1815  }
1816  ff_dlog(c, "color_range: %d\n", par->color_range);
1817  } else {
1818  /* For some reason the whole atom was not added to the extradata */
1819  av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1820  }
1821  } else {
1822  av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1823  }
1824  } else {
1825  av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1826  }
1827  }
1828 
1829  return ret;
1830 }
1831 
1833 {
1834  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1835 }
1836 
1838 {
1839  AVStream *st;
1840  int ret;
1841 
1842  if (c->fc->nb_streams < 1)
1843  return 0;
1844  st = c->fc->streams[c->fc->nb_streams-1];
1845 
1846  if ((uint64_t)atom.size > (1<<30))
1847  return AVERROR_INVALIDDATA;
1848 
1849  if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1852  // pass all frma atom to codec, needed at least for QDMC and QDM2
1853  av_freep(&st->codecpar->extradata);
1854  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1855  if (ret < 0)
1856  return ret;
1857  } else if (atom.size > 8) { /* to read frma, esds atoms */
1858  if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1859  uint64_t buffer;
1860  ret = ffio_ensure_seekback(pb, 8);
1861  if (ret < 0)
1862  return ret;
1863  buffer = avio_rb64(pb);
1864  atom.size -= 8;
1865  if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1866  && buffer >> 32 <= atom.size
1867  && buffer >> 32 >= 8) {
1868  avio_skip(pb, -8);
1869  atom.size += 8;
1870  } else if (!st->codecpar->extradata_size) {
1871 #define ALAC_EXTRADATA_SIZE 36
1873  if (!st->codecpar->extradata)
1874  return AVERROR(ENOMEM);
1877  AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1878  AV_WB64(st->codecpar->extradata + 12, buffer);
1879  avio_read(pb, st->codecpar->extradata + 20, 16);
1880  avio_skip(pb, atom.size - 24);
1881  return 0;
1882  }
1883  }
1884  if ((ret = mov_read_default(c, pb, atom)) < 0)
1885  return ret;
1886  } else
1887  avio_skip(pb, atom.size);
1888  return 0;
1889 }
1890 
1891 /**
1892  * This function reads atom content and puts data in extradata without tag
1893  * nor size unlike mov_read_extradata.
1894  */
1896 {
1897  AVStream *st;
1898  int ret;
1899 
1900  if (c->fc->nb_streams < 1)
1901  return 0;
1902  st = c->fc->streams[c->fc->nb_streams-1];
1903 
1904  if ((uint64_t)atom.size > (1<<30))
1905  return AVERROR_INVALIDDATA;
1906 
1907  if (atom.size >= 10) {
1908  // Broken files created by legacy versions of libavformat will
1909  // wrap a whole fiel atom inside of a glbl atom.
1910  unsigned size = avio_rb32(pb);
1911  unsigned type = avio_rl32(pb);
1912  if (avio_feof(pb))
1913  return AVERROR_INVALIDDATA;
1914  avio_seek(pb, -8, SEEK_CUR);
1915  if (type == MKTAG('f','i','e','l') && size == atom.size)
1916  return mov_read_default(c, pb, atom);
1917  }
1918  if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1919  av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1920  return 0;
1921  }
1922  av_freep(&st->codecpar->extradata);
1923  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1924  if (ret < 0)
1925  return ret;
1926  if (atom.type == MKTAG('h','v','c','C') && st->codecpar->codec_tag == MKTAG('d','v','h','1'))
1928 
1929  return 0;
1930 }
1931 
1933 {
1934  AVStream *st;
1935  uint8_t profile_level;
1936  int ret;
1937 
1938  if (c->fc->nb_streams < 1)
1939  return 0;
1940  st = c->fc->streams[c->fc->nb_streams-1];
1941 
1942  if (atom.size >= (1<<28) || atom.size < 7)
1943  return AVERROR_INVALIDDATA;
1944 
1945  profile_level = avio_r8(pb);
1946  if ((profile_level & 0xf0) != 0xc0)
1947  return 0;
1948 
1949  avio_seek(pb, 6, SEEK_CUR);
1950  av_freep(&st->codecpar->extradata);
1951  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1952  if (ret < 0)
1953  return ret;
1954 
1955  return 0;
1956 }
1957 
1958 /**
1959  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1960  * but can have extradata appended at the end after the 40 bytes belonging
1961  * to the struct.
1962  */
1964 {
1965  AVStream *st;
1966  int ret;
1967 
1968  if (c->fc->nb_streams < 1)
1969  return 0;
1970  if (atom.size <= 40)
1971  return 0;
1972  st = c->fc->streams[c->fc->nb_streams-1];
1973 
1974  if ((uint64_t)atom.size > (1<<30))
1975  return AVERROR_INVALIDDATA;
1976 
1977  avio_skip(pb, 40);
1978  av_freep(&st->codecpar->extradata);
1979  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1980  if (ret < 0)
1981  return ret;
1982 
1983  return 0;
1984 }
1985 
1987 {
1988  AVStream *st;
1989  MOVStreamContext *sc;
1990  unsigned int i, entries;
1991 
1992  if (c->trak_index < 0) {
1993  av_log(c->fc, AV_LOG_WARNING, "STCO outside TRAK\n");
1994  return 0;
1995  }
1996  if (c->fc->nb_streams < 1)
1997  return 0;
1998  st = c->fc->streams[c->fc->nb_streams-1];
1999  sc = st->priv_data;
2000 
2001  avio_r8(pb); /* version */
2002  avio_rb24(pb); /* flags */
2003 
2004  entries = avio_rb32(pb);
2005 
2006  if (!entries)
2007  return 0;
2008 
2009  if (sc->chunk_offsets) {
2010  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicated STCO atom\n");
2011  return 0;
2012  }
2013  av_free(sc->chunk_offsets);
2014  sc->chunk_count = 0;
2015  sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
2016  if (!sc->chunk_offsets)
2017  return AVERROR(ENOMEM);
2018  sc->chunk_count = entries;
2019 
2020  if (atom.type == MKTAG('s','t','c','o'))
2021  for (i = 0; i < entries && !pb->eof_reached; i++)
2022  sc->chunk_offsets[i] = avio_rb32(pb);
2023  else if (atom.type == MKTAG('c','o','6','4'))
2024  for (i = 0; i < entries && !pb->eof_reached; i++)
2025  sc->chunk_offsets[i] = avio_rb64(pb);
2026  else
2027  return AVERROR_INVALIDDATA;
2028 
2029  sc->chunk_count = i;
2030 
2031  if (pb->eof_reached) {
2032  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
2033  return AVERROR_EOF;
2034  }
2035 
2036  return 0;
2037 }
2038 
2039 static int mov_codec_id(AVStream *st, uint32_t format)
2040 {
2041  int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2042 
2043  if (id <= 0 &&
2044  ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2045  (format & 0xFFFF) == 'T' + ('S' << 8)))
2046  id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2047 
2048  if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2050  } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2051  /* skip old ASF MPEG-4 tag */
2052  format && format != MKTAG('m','p','4','s')) {
2054  if (id <= 0)
2055  id = ff_codec_get_id(ff_codec_bmp_tags, format);
2056  if (id > 0)
2058  else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2060  st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2062  if (id > 0)
2064  else
2065  id = ff_codec_get_id(ff_codec_movdata_tags, format);
2066  }
2067  }
2068 
2069  st->codecpar->codec_tag = format;
2070 
2071  return id;
2072 }
2073 
2075  AVStream *st, MOVStreamContext *sc)
2076 {
2077  uint8_t codec_name[32] = { 0 };
2078  int64_t stsd_start;
2079  unsigned int len;
2080 
2081  /* The first 16 bytes of the video sample description are already
2082  * read in ff_mov_read_stsd_entries() */
2083  stsd_start = avio_tell(pb) - 16;
2084 
2085  avio_rb16(pb); /* version */
2086  avio_rb16(pb); /* revision level */
2087  avio_rb32(pb); /* vendor */
2088  avio_rb32(pb); /* temporal quality */
2089  avio_rb32(pb); /* spatial quality */
2090 
2091  st->codecpar->width = avio_rb16(pb); /* width */
2092  st->codecpar->height = avio_rb16(pb); /* height */
2093 
2094  avio_rb32(pb); /* horiz resolution */
2095  avio_rb32(pb); /* vert resolution */
2096  avio_rb32(pb); /* data size, always 0 */
2097  avio_rb16(pb); /* frames per samples */
2098 
2099  len = avio_r8(pb); /* codec name, pascal string */
2100  if (len > 31)
2101  len = 31;
2102  mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2103  if (len < 31)
2104  avio_skip(pb, 31 - len);
2105 
2106  if (codec_name[0])
2107  av_dict_set(&st->metadata, "encoder", codec_name, 0);
2108 
2109  /* codec_tag YV12 triggers an UV swap in rawdec.c */
2110  if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2111  st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2112  st->codecpar->width &= ~1;
2113  st->codecpar->height &= ~1;
2114  }
2115  /* Flash Media Server uses tag H.263 with Sorenson Spark */
2116  if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2117  !strncmp(codec_name, "Sorenson H263", 13))
2119 
2120  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2121 
2122  avio_seek(pb, stsd_start, SEEK_SET);
2123 
2124  if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2125  st->codecpar->bits_per_coded_sample &= 0x1F;
2126  sc->has_palette = 1;
2127  }
2128 }
2129 
2131  AVStream *st, MOVStreamContext *sc)
2132 {
2133  int bits_per_sample, flags;
2134  uint16_t version = avio_rb16(pb);
2135  AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2136 
2137  avio_rb16(pb); /* revision level */
2138  avio_rb32(pb); /* vendor */
2139 
2140  st->codecpar->channels = avio_rb16(pb); /* channel count */
2141  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2142  av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2143 
2144  sc->audio_cid = avio_rb16(pb);
2145  avio_rb16(pb); /* packet size = 0 */
2146 
2147  st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2148 
2149  // Read QT version 1 fields. In version 0 these do not exist.
2150  av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2151  if (!c->isom ||
2152  (compatible_brands && strstr(compatible_brands->value, "qt ")) ||
2153  (sc->stsd_version == 0 && version > 0)) {
2154  if (version == 1) {
2155  sc->samples_per_frame = avio_rb32(pb);
2156  avio_rb32(pb); /* bytes per packet */
2157  sc->bytes_per_frame = avio_rb32(pb);
2158  avio_rb32(pb); /* bytes per sample */
2159  } else if (version == 2) {
2160  avio_rb32(pb); /* sizeof struct only */
2162  st->codecpar->channels = avio_rb32(pb);
2163  avio_rb32(pb); /* always 0x7F000000 */
2165 
2166  flags = avio_rb32(pb); /* lpcm format specific flag */
2167  sc->bytes_per_frame = avio_rb32(pb);
2168  sc->samples_per_frame = avio_rb32(pb);
2169  if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2170  st->codecpar->codec_id =
2172  flags);
2173  }
2174  if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2175  /* can't correctly handle variable sized packet as audio unit */
2176  switch (st->codecpar->codec_id) {
2177  case AV_CODEC_ID_MP2:
2178  case AV_CODEC_ID_MP3:
2180  break;
2181  }
2182  }
2183  }
2184 
2185  if (sc->format == 0) {
2186  if (st->codecpar->bits_per_coded_sample == 8)
2187  st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2188  else if (st->codecpar->bits_per_coded_sample == 16)
2189  st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2190  }
2191 
2192  switch (st->codecpar->codec_id) {
2193  case AV_CODEC_ID_PCM_S8:
2194  case AV_CODEC_ID_PCM_U8:
2195  if (st->codecpar->bits_per_coded_sample == 16)
2197  break;
2198  case AV_CODEC_ID_PCM_S16LE:
2199  case AV_CODEC_ID_PCM_S16BE:
2200  if (st->codecpar->bits_per_coded_sample == 8)
2202  else if (st->codecpar->bits_per_coded_sample == 24)
2203  st->codecpar->codec_id =
2206  else if (st->codecpar->bits_per_coded_sample == 32)
2207  st->codecpar->codec_id =
2210  break;
2211  /* set values for old format before stsd version 1 appeared */
2212  case AV_CODEC_ID_MACE3:
2213  sc->samples_per_frame = 6;
2214  sc->bytes_per_frame = 2 * st->codecpar->channels;
2215  break;
2216  case AV_CODEC_ID_MACE6:
2217  sc->samples_per_frame = 6;
2218  sc->bytes_per_frame = 1 * st->codecpar->channels;
2219  break;
2221  sc->samples_per_frame = 64;
2222  sc->bytes_per_frame = 34 * st->codecpar->channels;
2223  break;
2224  case AV_CODEC_ID_GSM:
2225  sc->samples_per_frame = 160;
2226  sc->bytes_per_frame = 33;
2227  break;
2228  default:
2229  break;
2230  }
2231 
2232  bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2233  if (bits_per_sample && (bits_per_sample >> 3) * (uint64_t)st->codecpar->channels <= INT_MAX) {
2234  st->codecpar->bits_per_coded_sample = bits_per_sample;
2235  sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2236  }
2237 }
2238 
2240  AVStream *st, MOVStreamContext *sc,
2241  int64_t size)
2242 {
2243  // ttxt stsd contains display flags, justification, background
2244  // color, fonts, and default styles, so fake an atom to read it
2245  MOVAtom fake_atom = { .size = size };
2246  // mp4s contains a regular esds atom
2247  if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2248  mov_read_glbl(c, pb, fake_atom);
2249  st->codecpar->width = sc->width;
2250  st->codecpar->height = sc->height;
2251 }
2252 
2253 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2254 {
2255  uint8_t r, g, b;
2256  int y, cb, cr;
2257 
2258  y = (ycbcr >> 16) & 0xFF;
2259  cr = (ycbcr >> 8) & 0xFF;
2260  cb = ycbcr & 0xFF;
2261 
2262  b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2263  g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2264  r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2265 
2266  return (r << 16) | (g << 8) | b;
2267 }
2268 
2270 {
2271  char buf[256] = {0};
2272  uint8_t *src = st->codecpar->extradata;
2273  int i;
2274 
2275  if (st->codecpar->extradata_size != 64)
2276  return 0;
2277 
2278  if (st->codecpar->width > 0 && st->codecpar->height > 0)
2279  snprintf(buf, sizeof(buf), "size: %dx%d\n",
2280  st->codecpar->width, st->codecpar->height);
2281  av_strlcat(buf, "palette: ", sizeof(buf));
2282 
2283  for (i = 0; i < 16; i++) {
2284  uint32_t yuv = AV_RB32(src + i * 4);
2285  uint32_t rgba = yuv_to_rgba(yuv);
2286 
2287  av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2288  }
2289 
2290  if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2291  return 0;
2292 
2293  av_freep(&st->codecpar->extradata);
2294  st->codecpar->extradata_size = 0;
2296  if (!st->codecpar->extradata)
2297  return AVERROR(ENOMEM);
2298  st->codecpar->extradata_size = strlen(buf);
2299  memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2300 
2301  return 0;
2302 }
2303 
2305  AVStream *st, MOVStreamContext *sc,
2306  int64_t size)
2307 {
2308  int ret;
2309 
2310  if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2311  if ((int)size != size)
2312  return AVERROR(ENOMEM);
2313 
2314  ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2315  if (ret < 0)
2316  return ret;
2317  if (size > 16) {
2318  MOVStreamContext *tmcd_ctx = st->priv_data;
2319  int val;
2320  val = AV_RB32(st->codecpar->extradata + 4);
2321  tmcd_ctx->tmcd_flags = val;
2322  st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2323  st->avg_frame_rate.den = 1;
2324 #if FF_API_LAVF_AVCTX
2326  st->codec->time_base = av_inv_q(st->avg_frame_rate);
2328 #endif
2329  /* adjust for per frame dur in counter mode */
2330  if (tmcd_ctx->tmcd_flags & 0x0008) {
2331  int timescale = AV_RB32(st->codecpar->extradata + 8);
2332  int framedur = AV_RB32(st->codecpar->extradata + 12);
2333  st->avg_frame_rate = av_mul_q(st->avg_frame_rate, (AVRational){timescale, framedur});
2334 #if FF_API_LAVF_AVCTX
2336  st->codec->time_base = av_mul_q(st->codec->time_base , (AVRational){framedur, timescale});
2338 #endif
2339  }
2340  if (size > 30) {
2341  uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2342  uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2343  if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2344  uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2345  if (str_size > 0 && size >= (int)str_size + 30) {
2346  char *reel_name = av_malloc(str_size + 1);
2347  if (!reel_name)
2348  return AVERROR(ENOMEM);
2349  memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2350  reel_name[str_size] = 0; /* Add null terminator */
2351  /* don't add reel_name if emtpy string */
2352  if (*reel_name == 0) {
2353  av_free(reel_name);
2354  } else {
2355  av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2356  }
2357  }
2358  }
2359  }
2360  }
2361  } else {
2362  /* other codec type, just skip (rtp, mp4s ...) */
2363  avio_skip(pb, size);
2364  }
2365  return 0;
2366 }
2367 
2369  AVStream *st, MOVStreamContext *sc)
2370 {
2371  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2372  !st->codecpar->sample_rate && sc->time_scale > 1)
2373  st->codecpar->sample_rate = sc->time_scale;
2374 
2375  /* special codec parameters handling */
2376  switch (st->codecpar->codec_id) {
2377 #if CONFIG_DV_DEMUXER
2378  case AV_CODEC_ID_DVAUDIO:
2380  if (!c->dv_fctx) {
2381  av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2382  return AVERROR(ENOMEM);
2383  }
2385  if (!c->dv_demux) {
2386  av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2387  return AVERROR(ENOMEM);
2388  }
2389  sc->dv_audio_container = 1;
2391  break;
2392 #endif
2393  /* no ifdef since parameters are always those */
2394  case AV_CODEC_ID_QCELP:
2395  st->codecpar->channels = 1;
2396  // force sample rate for qcelp when not stored in mov
2397  if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2398  st->codecpar->sample_rate = 8000;
2399  // FIXME: Why is the following needed for some files?
2400  sc->samples_per_frame = 160;
2401  if (!sc->bytes_per_frame)
2402  sc->bytes_per_frame = 35;
2403  break;
2404  case AV_CODEC_ID_AMR_NB:
2405  st->codecpar->channels = 1;
2406  /* force sample rate for amr, stsd in 3gp does not store sample rate */
2407  st->codecpar->sample_rate = 8000;
2408  break;
2409  case AV_CODEC_ID_AMR_WB:
2410  st->codecpar->channels = 1;
2411  st->codecpar->sample_rate = 16000;
2412  break;
2413  case AV_CODEC_ID_MP2:
2414  case AV_CODEC_ID_MP3:
2415  /* force type after stsd for m1a hdlr */
2417  break;
2418  case AV_CODEC_ID_GSM:
2419  case AV_CODEC_ID_ADPCM_MS:
2421  case AV_CODEC_ID_ILBC:
2422  case AV_CODEC_ID_MACE3:
2423  case AV_CODEC_ID_MACE6:
2424  case AV_CODEC_ID_QDM2:
2426  break;
2427  case AV_CODEC_ID_ALAC:
2428  if (st->codecpar->extradata_size == 36) {
2429  st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2430  st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2431  }
2432  break;
2433  case AV_CODEC_ID_AC3:
2434  case AV_CODEC_ID_EAC3:
2436  case AV_CODEC_ID_VC1:
2437  case AV_CODEC_ID_VP8:
2438  case AV_CODEC_ID_VP9:
2440  break;
2441  default:
2442  break;
2443  }
2444  return 0;
2445 }
2446 
2448  int codec_tag, int format,
2449  int64_t size)
2450 {
2451  int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2452 
2453  if (codec_tag &&
2454  (codec_tag != format &&
2455  // AVID 1:1 samples with differing data format and codec tag exist
2456  (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2457  // prores is allowed to have differing data format and codec tag
2458  codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2459  // so is dv (sigh)
2460  codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2461  (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2462  : codec_tag != MKTAG('j','p','e','g')))) {
2463  /* Multiple fourcc, we skip JPEG. This is not correct, we should
2464  * export it as a separate AVStream but this needs a few changes
2465  * in the MOV demuxer, patch welcome. */
2466 
2467  av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2468  avio_skip(pb, size);
2469  return 1;
2470  }
2471 
2472  return 0;
2473 }
2474 
2476 {
2477  AVStream *st;
2478  MOVStreamContext *sc;
2479  int pseudo_stream_id;
2480 
2481  av_assert0 (c->fc->nb_streams >= 1);
2482  st = c->fc->streams[c->fc->nb_streams-1];
2483  sc = st->priv_data;
2484 
2485  for (pseudo_stream_id = 0;
2486  pseudo_stream_id < entries && !pb->eof_reached;
2487  pseudo_stream_id++) {
2488  //Parsing Sample description table
2489  enum AVCodecID id;
2490  int ret, dref_id = 1;
2491  MOVAtom a = { AV_RL32("stsd") };
2492  int64_t start_pos = avio_tell(pb);
2493  int64_t size = avio_rb32(pb); /* size */
2494  uint32_t format = avio_rl32(pb); /* data format */
2495 
2496  if (size >= 16) {
2497  avio_rb32(pb); /* reserved */
2498  avio_rb16(pb); /* reserved */
2499  dref_id = avio_rb16(pb);
2500  } else if (size <= 7) {
2501  av_log(c->fc, AV_LOG_ERROR,
2502  "invalid size %"PRId64" in stsd\n", size);
2503  return AVERROR_INVALIDDATA;
2504  }
2505 
2506  if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2507  size - (avio_tell(pb) - start_pos))) {
2508  sc->stsd_count++;
2509  continue;
2510  }
2511 
2512  sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2513  sc->dref_id= dref_id;
2514  sc->format = format;
2515 
2516  id = mov_codec_id(st, format);
2517 
2518  av_log(c->fc, AV_LOG_TRACE,
2519  "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2520  av_fourcc2str(format), st->codecpar->codec_type);
2521 
2522  st->codecpar->codec_id = id;
2524  mov_parse_stsd_video(c, pb, st, sc);
2525  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2526  mov_parse_stsd_audio(c, pb, st, sc);
2527  if (st->codecpar->sample_rate < 0) {
2528  av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2529  return AVERROR_INVALIDDATA;
2530  }
2531  if (st->codecpar->channels < 0) {
2532  av_log(c->fc, AV_LOG_ERROR, "Invalid channels %d\n", st->codecpar->channels);
2533  return AVERROR_INVALIDDATA;
2534  }
2535  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2536  mov_parse_stsd_subtitle(c, pb, st, sc,
2537  size - (avio_tell(pb) - start_pos));
2538  } else {
2539  ret = mov_parse_stsd_data(c, pb, st, sc,
2540  size - (avio_tell(pb) - start_pos));
2541  if (ret < 0)
2542  return ret;
2543  }
2544  /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2545  a.size = size - (avio_tell(pb) - start_pos);
2546  if (a.size > 8) {
2547  if ((ret = mov_read_default(c, pb, a)) < 0)
2548  return ret;
2549  } else if (a.size > 0)
2550  avio_skip(pb, a.size);
2551 
2552  if (sc->extradata && st->codecpar->extradata) {
2553  int extra_size = st->codecpar->extradata_size;
2554 
2555  /* Move the current stream extradata to the stream context one. */
2556  sc->extradata_size[pseudo_stream_id] = extra_size;
2557  sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2558  if (!sc->extradata[pseudo_stream_id])
2559  return AVERROR(ENOMEM);
2560  memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2561  av_freep(&st->codecpar->extradata);
2562  st->codecpar->extradata_size = 0;
2563  }
2564  sc->stsd_count++;
2565  }
2566 
2567  if (pb->eof_reached) {
2568  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
2569  return AVERROR_EOF;
2570  }
2571 
2572  return 0;
2573 }
2574 
2576 {
2577  AVStream *st;
2578  MOVStreamContext *sc;
2579  int ret, entries;
2580 
2581  if (c->fc->nb_streams < 1)
2582  return 0;
2583  st = c->fc->streams[c->fc->nb_streams - 1];
2584  sc = st->priv_data;
2585 
2586  sc->stsd_version = avio_r8(pb);
2587  avio_rb24(pb); /* flags */
2588  entries = avio_rb32(pb);
2589 
2590  /* Each entry contains a size (4 bytes) and format (4 bytes). */
2591  if (entries <= 0 || entries > atom.size / 8) {
2592  av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2593  return AVERROR_INVALIDDATA;
2594  }
2595 
2596  if (sc->extradata) {
2597  av_log(c->fc, AV_LOG_ERROR,
2598  "Duplicate stsd found in this track.\n");
2599  return AVERROR_INVALIDDATA;
2600  }
2601 
2602  /* Prepare space for hosting multiple extradata. */
2603  sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2604  if (!sc->extradata)
2605  return AVERROR(ENOMEM);
2606 
2607  sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2608  if (!sc->extradata_size) {
2609  ret = AVERROR(ENOMEM);
2610  goto fail;
2611  }
2612 
2613  ret = ff_mov_read_stsd_entries(c, pb, entries);
2614  if (ret < 0)
2615  goto fail;
2616 
2617  /* Restore back the primary extradata. */
2618  av_freep(&st->codecpar->extradata);
2619  st->codecpar->extradata_size = sc->extradata_size[0];
2620  if (sc->extradata_size[0]) {
2622  if (!st->codecpar->extradata)
2623  return AVERROR(ENOMEM);
2624  memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2625  }
2626 
2627  return mov_finalize_stsd_codec(c, pb, st, sc);
2628 fail:
2629  if (sc->extradata) {
2630  int j;
2631  for (j = 0; j < sc->stsd_count; j++)
2632  av_freep(&sc->extradata[j]);
2633  }
2634 
2635  av_freep(&sc->extradata);
2636  av_freep(&sc->extradata_size);
2637  return ret;
2638 }
2639 
2641 {
2642  AVStream *st;
2643  MOVStreamContext *sc;
2644  unsigned int i, entries;
2645 
2646  if (c->fc->nb_streams < 1)
2647  return 0;
2648  st = c->fc->streams[c->fc->nb_streams-1];
2649  sc = st->priv_data;
2650 
2651  avio_r8(pb); /* version */
2652  avio_rb24(pb); /* flags */
2653 
2654  entries = avio_rb32(pb);
2655  if ((uint64_t)entries * 12 + 4 > atom.size)
2656  return AVERROR_INVALIDDATA;
2657 
2658  av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2659 
2660  if (!entries)
2661  return 0;
2662  if (sc->stsc_data) {
2663  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicated STSC atom\n");
2664  return 0;
2665  }
2666  av_free(sc->stsc_data);
2667  sc->stsc_count = 0;
2668  sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2669  if (!sc->stsc_data)
2670  return AVERROR(ENOMEM);
2671 
2672  for (i = 0; i < entries && !pb->eof_reached; i++) {
2673  sc->stsc_data[i].first = avio_rb32(pb);
2674  sc->stsc_data[i].count = avio_rb32(pb);
2675  sc->stsc_data[i].id = avio_rb32(pb);
2676  }
2677 
2678  sc->stsc_count = i;
2679  for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
2680  int64_t first_min = i + 1;
2681  if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
2682  (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
2683  sc->stsc_data[i].first < first_min ||
2684  sc->stsc_data[i].count < 1 ||
2685  sc->stsc_data[i].id < 1) {
2686  av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
2687  if (i+1 >= sc->stsc_count) {
2688  sc->stsc_data[i].first = FFMAX(sc->stsc_data[i].first, first_min);
2689  if (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first)
2690  sc->stsc_data[i].first = FFMIN(sc->stsc_data[i-1].first + 1LL, INT_MAX);
2691  sc->stsc_data[i].count = FFMAX(sc->stsc_data[i].count, 1);
2692  sc->stsc_data[i].id = FFMAX(sc->stsc_data[i].id, 1);
2693  continue;
2694  }
2695  av_assert0(sc->stsc_data[i+1].first >= 2);
2696  // We replace this entry by the next valid
2697  sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
2698  sc->stsc_data[i].count = sc->stsc_data[i+1].count;
2699  sc->stsc_data[i].id = sc->stsc_data[i+1].id;
2700  }
2701  }
2702 
2703  if (pb->eof_reached) {
2704  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2705  return AVERROR_EOF;
2706  }
2707 
2708  return 0;
2709 }
2710 
2711 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2712 {
2713  return index < count - 1;
2714 }
2715 
2716 /* Compute the samples value for the stsc entry at the given index. */
2717 static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2718 {
2719  int chunk_count;
2720 
2721  if (mov_stsc_index_valid(index, sc->stsc_count))
2722  chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2723  else {
2724  // Validation for stsc / stco happens earlier in mov_read_stsc + mov_read_trak.
2725  av_assert0(sc->stsc_data[index].first <= sc->chunk_count);
2726  chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2727  }
2728 
2729  return sc->stsc_data[index].count * (int64_t)chunk_count;
2730 }
2731 
2733 {
2734  AVStream *st;
2735  MOVStreamContext *sc;
2736  unsigned i, entries;
2737 
2738  if (c->fc->nb_streams < 1)
2739  return 0;
2740  st = c->fc->streams[c->fc->nb_streams-1];
2741  sc = st->priv_data;
2742 
2743  avio_rb32(pb); // version + flags
2744 
2745  entries = avio_rb32(pb);
2746  if (sc->stps_data)
2747  av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2748  av_free(sc->stps_data);
2749  sc->stps_count = 0;
2750  sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2751  if (!sc->stps_data)
2752  return AVERROR(ENOMEM);
2753 
2754  for (i = 0; i < entries && !pb->eof_reached; i++) {
2755  sc->stps_data[i] = avio_rb32(pb);
2756  }
2757 
2758  sc->stps_count = i;
2759 
2760  if (pb->eof_reached) {
2761  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2762  return AVERROR_EOF;
2763  }
2764 
2765  return 0;
2766 }
2767 
2769 {
2770  AVStream *st;
2771  MOVStreamContext *sc;
2772  unsigned int i, entries;
2773 
2774  if (c->fc->nb_streams < 1)
2775  return 0;
2776  st = c->fc->streams[c->fc->nb_streams-1];
2777  sc = st->priv_data;
2778 
2779  avio_r8(pb); /* version */
2780  avio_rb24(pb); /* flags */
2781 
2782  entries = avio_rb32(pb);
2783 
2784  av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2785 
2786  if (!entries)
2787  {
2788  sc->keyframe_absent = 1;
2789  if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2791  return 0;
2792  }
2793  if (sc->keyframes)
2794  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2795  if (entries >= UINT_MAX / sizeof(int))
2796  return AVERROR_INVALIDDATA;
2797  av_freep(&sc->keyframes);
2798  sc->keyframe_count = 0;
2799  sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2800  if (!sc->keyframes)
2801  return AVERROR(ENOMEM);
2802 
2803  for (i = 0; i < entries && !pb->eof_reached; i++) {
2804  sc->keyframes[i] = avio_rb32(pb);
2805  }
2806 
2807  sc->keyframe_count = i;
2808 
2809  if (pb->eof_reached) {
2810  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2811  return AVERROR_EOF;
2812  }
2813 
2814  return 0;
2815 }
2816 
2818 {
2819  AVStream *st;
2820  MOVStreamContext *sc;
2821  unsigned int i, entries, sample_size, field_size, num_bytes;
2822  GetBitContext gb;
2823  unsigned char* buf;
2824  int ret;
2825 
2826  if (c->fc->nb_streams < 1)
2827  return 0;
2828  st = c->fc->streams[c->fc->nb_streams-1];
2829  sc = st->priv_data;
2830 
2831  avio_r8(pb); /* version */
2832  avio_rb24(pb); /* flags */
2833 
2834  if (atom.type == MKTAG('s','t','s','z')) {
2835  sample_size = avio_rb32(pb);
2836  if (!sc->sample_size) /* do not overwrite value computed in stsd */
2837  sc->sample_size = sample_size;
2838  sc->stsz_sample_size = sample_size;
2839  field_size = 32;
2840  } else {
2841  sample_size = 0;
2842  avio_rb24(pb); /* reserved */
2843  field_size = avio_r8(pb);
2844  }
2845  entries = avio_rb32(pb);
2846 
2847  av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2848 
2849  sc->sample_count = entries;
2850  if (sample_size)
2851  return 0;
2852 
2853  if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2854  av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2855  return AVERROR_INVALIDDATA;
2856  }
2857 
2858  if (!entries)
2859  return 0;
2860  if (entries >= (UINT_MAX - 4) / field_size)
2861  return AVERROR_INVALIDDATA;
2862  if (sc->sample_sizes)
2863  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2864  av_free(sc->sample_sizes);
2865  sc->sample_count = 0;
2866  sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2867  if (!sc->sample_sizes)
2868  return AVERROR(ENOMEM);
2869 
2870  num_bytes = (entries*field_size+4)>>3;
2871 
2872  buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2873  if (!buf) {
2874  av_freep(&sc->sample_sizes);
2875  return AVERROR(ENOMEM);
2876  }
2877 
2878  ret = ffio_read_size(pb, buf, num_bytes);
2879  if (ret < 0) {
2880  av_freep(&sc->sample_sizes);
2881  av_free(buf);
2882  av_log(c->fc, AV_LOG_WARNING, "STSZ atom truncated\n");
2883  return 0;
2884  }
2885 
2886  init_get_bits(&gb, buf, 8*num_bytes);
2887 
2888  for (i = 0; i < entries && !pb->eof_reached; i++) {
2889  sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2890  if (sc->sample_sizes[i] < 0) {
2891  av_log(c->fc, AV_LOG_ERROR, "Invalid sample size %d\n", sc->sample_sizes[i]);
2892  return AVERROR_INVALIDDATA;
2893  }
2894  sc->data_size += sc->sample_sizes[i];
2895  }
2896 
2897  sc->sample_count = i;
2898 
2899  av_free(buf);
2900 
2901  if (pb->eof_reached) {
2902  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2903  return AVERROR_EOF;
2904  }
2905 
2906  return 0;
2907 }
2908 
2910 {
2911  AVStream *st;
2912  MOVStreamContext *sc;
2913  unsigned int i, entries, alloc_size = 0;
2914  int64_t duration=0;
2915  int64_t total_sample_count=0;
2916 
2917  if (c->fc->nb_streams < 1)
2918  return 0;
2919  st = c->fc->streams[c->fc->nb_streams-1];
2920  sc = st->priv_data;
2921 
2922  avio_r8(pb); /* version */
2923  avio_rb24(pb); /* flags */
2924  entries = avio_rb32(pb);
2925 
2926  av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2927  c->fc->nb_streams-1, entries);
2928 
2929  if (sc->stts_data)
2930  av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2931  av_freep(&sc->stts_data);
2932  sc->stts_count = 0;
2933  if (entries >= INT_MAX / sizeof(*sc->stts_data))
2934  return AVERROR(ENOMEM);
2935 
2936  for (i = 0; i < entries && !pb->eof_reached; i++) {
2937  int sample_duration;
2938  unsigned int sample_count;
2939  unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
2940  MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2941  min_entries * sizeof(*sc->stts_data));
2942  if (!stts_data) {
2943  av_freep(&sc->stts_data);
2944  sc->stts_count = 0;
2945  return AVERROR(ENOMEM);
2946  }
2947  sc->stts_count = min_entries;
2948  sc->stts_data = stts_data;
2949 
2950  sample_count=avio_rb32(pb);
2951  sample_duration = avio_rb32(pb);
2952 
2953  sc->stts_data[i].count= sample_count;
2954  sc->stts_data[i].duration= sample_duration;
2955 
2956  av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2957  sample_count, sample_duration);
2958 
2959  if ( i+1 == entries
2960  && i
2961  && sample_count == 1
2962  && total_sample_count > 100
2963  && sample_duration/10 > duration / total_sample_count)
2964  sample_duration = duration / total_sample_count;
2965  duration+=(int64_t)sample_duration*(uint64_t)sample_count;
2966  total_sample_count+=sample_count;
2967  }
2968 
2969  sc->stts_count = i;
2970 
2971  if (duration > 0 &&
2972  duration <= INT64_MAX - sc->duration_for_fps &&
2973  total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
2974  ) {
2975  sc->duration_for_fps += duration;
2976  sc->nb_frames_for_fps += total_sample_count;
2977  }
2978 
2979  if (pb->eof_reached) {
2980  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2981  return AVERROR_EOF;
2982  }
2983 
2984  st->nb_frames= total_sample_count;
2985  if (duration)
2986  st->duration= FFMIN(st->duration, duration);
2987  sc->track_end = duration;
2988  return 0;
2989 }
2990 
2992 {
2993  if (duration < 0) {
2994  if (duration == INT_MIN) {
2995  av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2996  duration++;
2997  }
2998  sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2999  }
3000 }
3001 
3003 {
3004  AVStream *st;
3005  MOVStreamContext *sc;
3006  unsigned int i, entries, ctts_count = 0;
3007 
3008  if (c->fc->nb_streams < 1)
3009  return 0;
3010  st = c->fc->streams[c->fc->nb_streams-1];
3011  sc = st->priv_data;
3012 
3013  avio_r8(pb); /* version */
3014  avio_rb24(pb); /* flags */
3015  entries = avio_rb32(pb);
3016 
3017  av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
3018 
3019  if (!entries)
3020  return 0;
3021  if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
3022  return AVERROR_INVALIDDATA;
3023  av_freep(&sc->ctts_data);
3024  sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
3025  if (!sc->ctts_data)
3026  return AVERROR(ENOMEM);
3027 
3028  for (i = 0; i < entries && !pb->eof_reached; i++) {
3029  int count =avio_rb32(pb);
3030  int duration =avio_rb32(pb);
3031 
3032  if (count <= 0) {
3033  av_log(c->fc, AV_LOG_TRACE,
3034  "ignoring CTTS entry with count=%d duration=%d\n",
3035  count, duration);
3036  continue;
3037  }
3038 
3039  add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
3040  count, duration);
3041 
3042  av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
3043  count, duration);
3044 
3045  if (FFNABS(duration) < -(1<<28) && i+2<entries) {
3046  av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
3047  av_freep(&sc->ctts_data);
3048  sc->ctts_count = 0;
3049  return 0;
3050  }
3051 
3052  if (i+2<entries)
3053  mov_update_dts_shift(sc, duration);
3054  }
3055 
3056  sc->ctts_count = ctts_count;
3057 
3058  if (pb->eof_reached) {
3059  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
3060  return AVERROR_EOF;
3061  }
3062 
3063  av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
3064 
3065  return 0;
3066 }
3067 
3069 {
3070  AVStream *st;
3071  MOVStreamContext *sc;
3072  unsigned int i, entries;
3073  uint8_t version;
3074  uint32_t grouping_type;
3075 
3076  if (c->fc->nb_streams < 1)
3077  return 0;
3078  st = c->fc->streams[c->fc->nb_streams-1];
3079  sc = st->priv_data;
3080 
3081  version = avio_r8(pb); /* version */
3082  avio_rb24(pb); /* flags */
3083  grouping_type = avio_rl32(pb);
3084  if (grouping_type != MKTAG( 'r','a','p',' '))
3085  return 0; /* only support 'rap ' grouping */
3086  if (version == 1)
3087  avio_rb32(pb); /* grouping_type_parameter */
3088 
3089  entries = avio_rb32(pb);
3090  if (!entries)
3091  return 0;
3092  if (sc->rap_group)
3093  av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3094  av_free(sc->rap_group);
3095  sc->rap_group_count = 0;
3096  sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3097  if (!sc->rap_group)
3098  return AVERROR(ENOMEM);
3099 
3100  for (i = 0; i < entries && !pb->eof_reached; i++) {
3101  sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3102  sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3103  }
3104 
3105  sc->rap_group_count = i;
3106 
3107  if (pb->eof_reached) {
3108  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3109  return AVERROR_EOF;
3110  }
3111 
3112  return 0;
3113 }
3114 
3115 /**
3116  * Get ith edit list entry (media time, duration).
3117  */
3119  const MOVStreamContext *msc,
3120  unsigned int edit_list_index,
3121  int64_t *edit_list_media_time,
3122  int64_t *edit_list_duration,
3123  int64_t global_timescale)
3124 {
3125  if (edit_list_index == msc->elst_count) {
3126  return 0;
3127  }
3128  *edit_list_media_time = msc->elst_data[edit_list_index].time;
3129  *edit_list_duration = msc->elst_data[edit_list_index].duration;
3130 
3131  /* duration is in global timescale units;convert to msc timescale */
3132  if (global_timescale == 0) {
3133  avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3134  return 0;
3135  }
3136  *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3137  global_timescale);
3138  return 1;
3139 }
3140 
3141 /**
3142  * Find the closest previous frame to the timestamp_pts, in e_old index
3143  * entries. Searching for just any frame / just key frames can be controlled by
3144  * last argument 'flag'.
3145  * Note that if ctts_data is not NULL, we will always search for a key frame
3146  * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3147  * return the first frame of the video.
3148  *
3149  * Here the timestamp_pts is considered to be a presentation timestamp and
3150  * the timestamp of index entries are considered to be decoding timestamps.
3151  *
3152  * Returns 0 if successful in finding a frame, else returns -1.
3153  * Places the found index corresponding output arg.
3154  *
3155  * If ctts_old is not NULL, then refines the searched entry by searching
3156  * backwards from the found timestamp, to find the frame with correct PTS.
3157  *
3158  * Places the found ctts_index and ctts_sample in corresponding output args.
3159  */
3161  AVIndexEntry *e_old,
3162  int nb_old,
3163  MOVStts* ctts_data,
3164  int64_t ctts_count,
3165  int64_t timestamp_pts,
3166  int flag,
3167  int64_t* index,
3168  int64_t* ctts_index,
3169  int64_t* ctts_sample)
3170 {
3171  MOVStreamContext *msc = st->priv_data;
3172  AVIndexEntry *e_keep = st->index_entries;
3173  int nb_keep = st->nb_index_entries;
3174  int64_t i = 0;
3175  int64_t index_ctts_count;
3176 
3177  av_assert0(index);
3178 
3179  // If dts_shift > 0, then all the index timestamps will have to be offset by
3180  // at least dts_shift amount to obtain PTS.
3181  // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3182  if (msc->dts_shift > 0) {
3183  timestamp_pts -= msc->dts_shift;
3184  }
3185 
3186  st->index_entries = e_old;
3187  st->nb_index_entries = nb_old;
3188  *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3189 
3190  // Keep going backwards in the index entries until the timestamp is the same.
3191  if (*index >= 0) {
3192  for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3193  i--) {
3194  if ((flag & AVSEEK_FLAG_ANY) ||
3195  (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3196  *index = i - 1;
3197  }
3198  }
3199  }
3200 
3201  // If we have CTTS then refine the search, by searching backwards over PTS
3202  // computed by adding corresponding CTTS durations to index timestamps.
3203  if (ctts_data && *index >= 0) {
3204  av_assert0(ctts_index);
3205  av_assert0(ctts_sample);
3206  // Find out the ctts_index for the found frame.
3207  *ctts_index = 0;
3208  *ctts_sample = 0;
3209  for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3210  if (*ctts_index < ctts_count) {
3211  (*ctts_sample)++;
3212  if (ctts_data[*ctts_index].count == *ctts_sample) {
3213  (*ctts_index)++;
3214  *ctts_sample = 0;
3215  }
3216  }
3217  }
3218 
3219  while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
3220  // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3221  // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3222  // compensated by dts_shift above.
3223  if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3224  (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3225  break;
3226  }
3227 
3228  (*index)--;
3229  if (*ctts_sample == 0) {
3230  (*ctts_index)--;
3231  if (*ctts_index >= 0)
3232  *ctts_sample = ctts_data[*ctts_index].count - 1;
3233  } else {
3234  (*ctts_sample)--;
3235  }
3236  }
3237  }
3238 
3239  /* restore AVStream state*/
3240  st->index_entries = e_keep;
3241  st->nb_index_entries = nb_keep;
3242  return *index >= 0 ? 0 : -1;
3243 }
3244 
3245 /**
3246  * Add index entry with the given values, to the end of st->index_entries.
3247  * Returns the new size st->index_entries if successful, else returns -1.
3248  *
3249  * This function is similar to ff_add_index_entry in libavformat/utils.c
3250  * except that here we are always unconditionally adding an index entry to
3251  * the end, instead of searching the entries list and skipping the add if
3252  * there is an existing entry with the same timestamp.
3253  * This is needed because the mov_fix_index calls this func with the same
3254  * unincremented timestamp for successive discarded frames.
3255  */
3256 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3257  int size, int distance, int flags)
3258 {
3259  AVIndexEntry *entries, *ie;
3260  int64_t index = -1;
3261  const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3262 
3263  // Double the allocation each time, to lower memory fragmentation.
3264  // Another difference from ff_add_index_entry function.
3265  const size_t requested_size =
3266  min_size_needed > st->index_entries_allocated_size ?
3267  FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3268  min_size_needed;
3269 
3270  if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3271  return -1;
3272 
3273  entries = av_fast_realloc(st->index_entries,
3275  requested_size);
3276  if(!entries)
3277  return -1;
3278 
3279  st->index_entries= entries;
3280 
3281  index= st->nb_index_entries++;
3282  ie= &entries[index];
3283 
3284  ie->pos = pos;
3285  ie->timestamp = timestamp;
3286  ie->min_distance= distance;
3287  ie->size= size;
3288  ie->flags = flags;
3289  return index;
3290 }
3291 
3292 /**
3293  * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3294  * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3295  */
3296 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3297  int64_t* frame_duration_buffer,
3298  int frame_duration_buffer_size) {
3299  int i = 0;
3300  av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3301  for (i = 0; i < frame_duration_buffer_size; i++) {
3302  end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3303  st->index_entries[end_index - 1 - i].timestamp = end_ts;
3304  }
3305 }
3306 
3307 /**
3308  * Append a new ctts entry to ctts_data.
3309  * Returns the new ctts_count if successful, else returns -1.
3310  */
3311 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3312  int count, int duration)
3313 {
3314  MOVStts *ctts_buf_new;
3315  const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3316  const size_t requested_size =
3317  min_size_needed > *allocated_size ?
3318  FFMAX(min_size_needed, 2 * (*allocated_size)) :
3319  min_size_needed;
3320 
3321  if((unsigned)(*ctts_count) >= UINT_MAX / sizeof(MOVStts) - 1)
3322  return -1;
3323 
3324  ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3325 
3326  if(!ctts_buf_new)
3327  return -1;
3328 
3329  *ctts_data = ctts_buf_new;
3330 
3331  ctts_buf_new[*ctts_count].count = count;
3332  ctts_buf_new[*ctts_count].duration = duration;
3333 
3334  *ctts_count = (*ctts_count) + 1;
3335  return *ctts_count;
3336 }
3337 
3338 #define MAX_REORDER_DELAY 16
3340  MOVStreamContext *msc = st->priv_data;
3341  int ind;
3342  int ctts_ind = 0;
3343  int ctts_sample = 0;
3344  int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3345  int buf_start = 0;
3346  int j, r, num_swaps;
3347 
3348  for (j = 0; j < MAX_REORDER_DELAY + 1; j++)
3349  pts_buf[j] = INT64_MIN;
3350 
3351  if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3353  st->codecpar->video_delay = 0;
3354  for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3355  // Point j to the last elem of the buffer and insert the current pts there.
3356  j = buf_start;
3357  buf_start = (buf_start + 1);
3358  if (buf_start == MAX_REORDER_DELAY + 1)
3359  buf_start = 0;
3360 
3361  pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3362 
3363  // The timestamps that are already in the sorted buffer, and are greater than the
3364  // current pts, are exactly the timestamps that need to be buffered to output PTS
3365  // in correct sorted order.
3366  // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3367  // can be computed as the maximum no. of swaps any particular timestamp needs to
3368  // go through, to keep this buffer in sorted order.
3369  num_swaps = 0;
3370  while (j != buf_start) {
3371  r = j - 1;
3372  if (r < 0) r = MAX_REORDER_DELAY;
3373  if (pts_buf[j] < pts_buf[r]) {
3374  FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3375  ++num_swaps;
3376  } else {
3377  break;
3378  }
3379  j = r;
3380  }
3381  st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3382 
3383  ctts_sample++;
3384  if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3385  ctts_ind++;
3386  ctts_sample = 0;
3387  }
3388  }
3389  av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3390  st->codecpar->video_delay, st->index);
3391  }
3392 }
3393 
3395 {
3396  sc->current_sample++;
3397  sc->current_index++;
3398  if (sc->index_ranges &&
3399  sc->current_index >= sc->current_index_range->end &&
3400  sc->current_index_range->end) {
3401  sc->current_index_range++;
3403  }
3404 }
3405 
3407 {
3408  sc->current_sample--;
3409  sc->current_index--;
3410  if (sc->index_ranges &&
3412  sc->current_index_range > sc->index_ranges) {
3413  sc->current_index_range--;
3414  sc->current_index = sc->current_index_range->end - 1;
3415  }
3416 }
3417 
3418 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3419 {
3420  int64_t range_size;
3421 
3422  sc->current_sample = current_sample;
3423  sc->current_index = current_sample;
3424  if (!sc->index_ranges) {
3425  return;
3426  }
3427 
3428  for (sc->current_index_range = sc->index_ranges;
3429  sc->current_index_range->end;
3430  sc->current_index_range++) {
3431  range_size = sc->current_index_range->end - sc->current_index_range->start;
3432  if (range_size > current_sample) {
3433  sc->current_index = sc->current_index_range->start + current_sample;
3434  break;
3435  }
3436  current_sample -= range_size;
3437  }
3438 }
3439 
3440 /**
3441  * Fix st->index_entries, so that it contains only the entries (and the entries
3442  * which are needed to decode them) that fall in the edit list time ranges.
3443  * Also fixes the timestamps of the index entries to match the timeline
3444  * specified the edit lists.
3445  */
3446 static void mov_fix_index(MOVContext *mov, AVStream *st)
3447 {
3448  MOVStreamContext *msc = st->priv_data;
3449  AVIndexEntry *e_old = st->index_entries;
3450  int nb_old = st->nb_index_entries;
3451  const AVIndexEntry *e_old_end = e_old + nb_old;
3452  const AVIndexEntry *current = NULL;
3453  MOVStts *ctts_data_old = msc->ctts_data;
3454  int64_t ctts_index_old = 0;
3455  int64_t ctts_sample_old = 0;
3456  int64_t ctts_count_old = msc->ctts_count;
3457  int64_t edit_list_media_time = 0;
3458  int64_t edit_list_duration = 0;
3459  int64_t frame_duration = 0;
3460  int64_t edit_list_dts_counter = 0;
3461  int64_t edit_list_dts_entry_end = 0;
3462  int64_t edit_list_start_ctts_sample = 0;
3463  int64_t curr_cts;
3464  int64_t curr_ctts = 0;
3465  int64_t empty_edits_sum_duration = 0;
3466  int64_t edit_list_index = 0;
3467  int64_t index;
3468  int flags;
3469  int64_t start_dts = 0;
3470  int64_t edit_list_start_encountered = 0;
3471  int64_t search_timestamp = 0;
3472  int64_t* frame_duration_buffer = NULL;
3473  int num_discarded_begin = 0;
3474  int first_non_zero_audio_edit = -1;
3475  int packet_skip_samples = 0;
3476  MOVIndexRange *current_index_range;
3477  int i;
3478  int found_keyframe_after_edit = 0;
3479 
3480  if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3481  return;
3482  }
3483 
3484  // allocate the index ranges array
3485  msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3486  if (!msc->index_ranges) {
3487  av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3488  return;
3489  }
3490  msc->current_index_range = msc->index_ranges;
3491  current_index_range = msc->index_ranges - 1;
3492 
3493  // Clean AVStream from traces of old index
3494  st->index_entries = NULL;
3496  st->nb_index_entries = 0;
3497 
3498  // Clean ctts fields of MOVStreamContext
3499  msc->ctts_data = NULL;
3500  msc->ctts_count = 0;
3501  msc->ctts_index = 0;
3502  msc->ctts_sample = 0;
3503  msc->ctts_allocated_size = 0;
3504 
3505  // Reinitialize min_corrected_pts so that it can be computed again.
3506  msc->min_corrected_pts = -1;
3507 
3508  // If the dts_shift is positive (in case of negative ctts values in mov),
3509  // then negate the DTS by dts_shift
3510  if (msc->dts_shift > 0) {
3511  edit_list_dts_entry_end -= msc->dts_shift;
3512  av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3513  }
3514 
3515  start_dts = edit_list_dts_entry_end;
3516 
3517  while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3518  &edit_list_duration, mov->time_scale)) {
3519  av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3520  st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3521  edit_list_index++;
3522  edit_list_dts_counter = edit_list_dts_entry_end;
3523  edit_list_dts_entry_end += edit_list_duration;
3524  num_discarded_begin = 0;
3525  if (edit_list_media_time == -1) {
3526  empty_edits_sum_duration += edit_list_duration;
3527  continue;
3528  }
3529 
3530  // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3531  // according to the edit list below.
3532  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3533  if (first_non_zero_audio_edit < 0) {
3534  first_non_zero_audio_edit = 1;
3535  } else {
3536  first_non_zero_audio_edit = 0;
3537  }
3538 
3539  if (first_non_zero_audio_edit > 0)
3540  st->skip_samples = msc->start_pad = 0;
3541  }
3542 
3543  // While reordering frame index according to edit list we must handle properly
3544  // the scenario when edit list entry starts from none key frame.
3545  // We find closest previous key frame and preserve it and consequent frames in index.
3546  // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3547  search_timestamp = edit_list_media_time;
3548  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3549  // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3550  // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3551  // edit_list_media_time to cover the decoder delay.
3552  search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3553  }
3554 
3555  if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3556  &index, &ctts_index_old, &ctts_sample_old) < 0) {
3557  av_log(mov->fc, AV_LOG_WARNING,
3558  "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3559  st->index, edit_list_index, search_timestamp);
3560  if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3561  &index, &ctts_index_old, &ctts_sample_old) < 0) {
3562  av_log(mov->fc, AV_LOG_WARNING,
3563  "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3564  st->index, edit_list_index, search_timestamp);
3565  index = 0;
3566  ctts_index_old = 0;
3567  ctts_sample_old = 0;
3568  }
3569  }
3570  current = e_old + index;
3571  edit_list_start_ctts_sample = ctts_sample_old;
3572 
3573  // Iterate over index and arrange it according to edit list
3574  edit_list_start_encountered = 0;
3575  found_keyframe_after_edit = 0;
3576  for (; current < e_old_end; current++, index++) {
3577  // check if frame outside edit list mark it for discard
3578  frame_duration = (current + 1 < e_old_end) ?
3579  ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3580 
3581  flags = current->flags;
3582 
3583  // frames (pts) before or after edit list
3584  curr_cts = current->timestamp + msc->dts_shift;
3585  curr_ctts = 0;
3586 
3587  if (ctts_data_old && ctts_index_old < ctts_count_old) {
3588  curr_ctts = ctts_data_old[ctts_index_old].duration;
3589  av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3590  curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3591  curr_cts += curr_ctts;
3592  ctts_sample_old++;
3593  if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3594  if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3595  &msc->ctts_allocated_size,
3596  ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3597  ctts_data_old[ctts_index_old].duration) == -1) {
3598  av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3599  ctts_index_old,
3600  ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3601  ctts_data_old[ctts_index_old].duration);
3602  break;
3603  }
3604  ctts_index_old++;
3605  ctts_sample_old = 0;
3606  edit_list_start_ctts_sample = 0;
3607  }
3608  }
3609 
3610  if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3612  curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3613  first_non_zero_audio_edit > 0) {
3614  packet_skip_samples = edit_list_media_time - curr_cts;
3615  st->skip_samples += packet_skip_samples;
3616 
3617  // Shift the index entry timestamp by packet_skip_samples to be correct.
3618  edit_list_dts_counter -= packet_skip_samples;
3619  if (edit_list_start_encountered == 0) {
3620  edit_list_start_encountered = 1;
3621  // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3622  // discarded packets.
3623  if (frame_duration_buffer) {
3624  fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3625  frame_duration_buffer, num_discarded_begin);
3626  av_freep(&frame_duration_buffer);
3627  }
3628  }
3629 
3630  av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3631  } else {
3632  flags |= AVINDEX_DISCARD_FRAME;
3633  av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3634 
3635  if (edit_list_start_encountered == 0) {
3636  num_discarded_begin++;
3637  frame_duration_buffer = av_realloc(frame_duration_buffer,
3638  num_discarded_begin * sizeof(int64_t));
3639  if (!frame_duration_buffer) {
3640  av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3641  break;
3642  }
3643  frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3644 
3645  // Increment skip_samples for the first non-zero audio edit list
3646  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3647  first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3648  st->skip_samples += frame_duration;
3649  }
3650  }
3651  }
3652  } else {
3653  if (msc->min_corrected_pts < 0) {
3654  msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3655  } else {
3656  msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3657  }
3658  if (edit_list_start_encountered == 0) {
3659  edit_list_start_encountered = 1;
3660  // Make timestamps strictly monotonically increasing by rewriting timestamps for
3661  // discarded packets.
3662  if (frame_duration_buffer) {
3663  fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3664  frame_duration_buffer, num_discarded_begin);
3665  av_freep(&frame_duration_buffer);
3666  }
3667  }
3668  }
3669 
3670  if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3671  current->min_distance, flags) == -1) {
3672  av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3673  break;
3674  }
3675 
3676  // Update the index ranges array
3677  if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3678  current_index_range++;
3679  current_index_range->start = index;
3680  }
3681  current_index_range->end = index + 1;
3682 
3683  // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3684  if (edit_list_start_encountered > 0) {
3685  edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3686  }
3687 
3688  // Break when found first key frame after edit entry completion
3689  if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3690  ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3691  if (ctts_data_old) {
3692  // If we have CTTS and this is the first keyframe after edit elist,
3693  // wait for one more, because there might be trailing B-frames after this I-frame
3694  // that do belong to the edit.
3695  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3696  found_keyframe_after_edit = 1;
3697  continue;
3698  }
3699  if (ctts_sample_old != 0) {
3700  if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3701  &msc->ctts_allocated_size,
3702  ctts_sample_old - edit_list_start_ctts_sample,
3703  ctts_data_old[ctts_index_old].duration) == -1) {
3704  av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3705  ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3706  ctts_data_old[ctts_index_old].duration);
3707  break;
3708  }
3709  }
3710  }
3711  break;
3712  }
3713  }
3714  }
3715  // If there are empty edits, then msc->min_corrected_pts might be positive
3716  // intentionally. So we subtract the sum duration of emtpy edits here.
3717  msc->min_corrected_pts -= empty_edits_sum_duration;
3718 
3719  // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3720  // dts by that amount to make the first pts zero.
3721  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3722  if (msc->min_corrected_pts > 0) {
3723  av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
3724  for (i = 0; i < st->nb_index_entries; ++i) {
3726  }
3727  }
3728  }
3729  // Start time should be equal to zero or the duration of any empty edits.
3730  st->start_time = empty_edits_sum_duration;
3731 
3732  // Update av stream length, if it ends up shorter than the track's media duration
3733  st->duration = FFMIN(st->duration, edit_list_dts_entry_end - start_dts);
3734  msc->start_pad = st->skip_samples;
3735 
3736  // Free the old index and the old CTTS structures
3737  av_free(e_old);
3738  av_free(ctts_data_old);
3739  av_freep(&frame_duration_buffer);
3740 
3741  // Null terminate the index ranges array
3742  current_index_range++;
3743  current_index_range->start = 0;
3744  current_index_range->end = 0;
3745  msc->current_index = msc->index_ranges[0].start;
3746 }
3747 
3748 static void mov_build_index(MOVContext *mov, AVStream *st)
3749 {
3750  MOVStreamContext *sc = st->priv_data;
3751  int64_t current_offset;
3752  int64_t current_dts = 0;
3753  unsigned int stts_index = 0;
3754  unsigned int stsc_index = 0;
3755  unsigned int stss_index = 0;
3756  unsigned int stps_index = 0;
3757  unsigned int i, j;
3758  uint64_t stream_size = 0;
3759  MOVStts *ctts_data_old = sc->ctts_data;
3760  unsigned int ctts_count_old = sc->ctts_count;
3761 
3762  if (sc->elst_count) {
3763  int i, edit_start_index = 0, multiple_edits = 0;
3764  int64_t empty_duration = 0; // empty duration of the first edit list entry
3765  int64_t start_time = 0; // start time of the media
3766 
3767  for (i = 0; i < sc->elst_count; i++) {
3768  const MOVElst *e = &sc->elst_data[i];
3769  if (i == 0 && e->time == -1) {
3770  /* if empty, the first entry is the start time of the stream
3771  * relative to the presentation itself */
3772  empty_duration = e->duration;
3773  edit_start_index = 1;
3774  } else if (i == edit_start_index && e->time >= 0) {
3775  start_time = e->time;
3776  } else {
3777  multiple_edits = 1;
3778  }
3779  }
3780 
3781  if (multiple_edits && !mov->advanced_editlist)
3782  av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3783  "Use -advanced_editlist to correctly decode otherwise "
3784  "a/v desync might occur\n");
3785 
3786  /* adjust first dts according to edit list */
3787  if ((empty_duration || start_time) && mov->time_scale > 0) {
3788  if (empty_duration)
3789  empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3790  sc->time_offset = start_time - empty_duration;
3792  if (!mov->advanced_editlist)
3793  current_dts = -sc->time_offset;
3794  }
3795 
3796  if (!multiple_edits && !mov->advanced_editlist &&
3797  st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3798  sc->start_pad = start_time;
3799  }
3800 
3801  /* only use old uncompressed audio chunk demuxing when stts specifies it */
3802  if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3803  sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3804  unsigned int current_sample = 0;
3805  unsigned int stts_sample = 0;
3806  unsigned int sample_size;
3807  unsigned int distance = 0;
3808  unsigned int rap_group_index = 0;
3809  unsigned int rap_group_sample = 0;
3810  int64_t last_dts = 0;
3811  int64_t dts_correction = 0;
3812  int rap_group_present = sc->rap_group_count && sc->rap_group;
3813  int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3814 
3815  current_dts -= sc->dts_shift;
3816  last_dts = current_dts;
3817 
3818  if (!sc->sample_count || st->nb_index_entries)
3819  return;
3820  if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3821  return;
3823  st->nb_index_entries + sc->sample_count,
3824  sizeof(*st->index_entries)) < 0) {
3825  st->nb_index_entries = 0;
3826  return;
3827  }
3829 
3830  if (ctts_data_old) {
3831  // Expand ctts entries such that we have a 1-1 mapping with samples
3832  if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3833  return;
3834  sc->ctts_count = 0;
3835  sc->ctts_allocated_size = 0;
3837  sc->sample_count * sizeof(*sc->ctts_data));
3838  if (!sc->ctts_data) {
3839  av_free(ctts_data_old);
3840  return;
3841  }
3842 
3843  memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
3844 
3845  for (i = 0; i < ctts_count_old &&
3846  sc->ctts_count < sc->sample_count; i++)
3847  for (j = 0; j < ctts_data_old[i].count &&
3848  sc->ctts_count < sc->sample_count; j++)
3849  add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3850  &sc->ctts_allocated_size, 1,
3851  ctts_data_old[i].duration);
3852  av_free(ctts_data_old);
3853  }
3854 
3855  for (i = 0; i < sc->chunk_count; i++) {
3856  int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3857  current_offset = sc->chunk_offsets[i];
3858  while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3859  i + 1 == sc->stsc_data[stsc_index + 1].first)
3860  stsc_index++;
3861 
3862  if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3863  sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3864  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3865  sc->stsz_sample_size = sc->sample_size;
3866  }
3867  if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3868  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3869  sc->stsz_sample_size = sc->sample_size;
3870  }
3871 
3872  for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3873  int keyframe = 0;
3874  if (current_sample >= sc->sample_count) {
3875  av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3876  return;
3877  }
3878 
3879  if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3880  keyframe = 1;
3881  if (stss_index + 1 < sc->keyframe_count)
3882  stss_index++;
3883  } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3884  keyframe = 1;
3885  if (stps_index + 1 < sc->stps_count)
3886  stps_index++;
3887  }
3888  if (rap_group_present && rap_group_index < sc->rap_group_count) {
3889  if (sc->rap_group[rap_group_index].index > 0)
3890  keyframe = 1;
3891  if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3892  rap_group_sample = 0;
3893  rap_group_index++;
3894  }
3895  }
3896  if (sc->keyframe_absent
3897  && !sc->stps_count
3898  && !rap_group_present
3899  && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3900  keyframe = 1;
3901  if (keyframe)
3902  distance = 0;
3903  sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3904  if (current_offset > INT64_MAX - sample_size) {
3905  av_log(mov->fc, AV_LOG_ERROR, "Current offset %"PRId64" or sample size %u is too large\n",
3906  current_offset,
3907  sample_size);
3908  return;
3909  }
3910 
3911  if (sc->pseudo_stream_id == -1 ||
3912  sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3913  AVIndexEntry *e;
3914  if (sample_size > 0x3FFFFFFF) {
3915  av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3916  return;
3917  }
3918  e = &st->index_entries[st->nb_index_entries++];
3919  e->pos = current_offset;
3920  e->timestamp = current_dts;
3921  e->size = sample_size;
3922  e->min_distance = distance;
3923  e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3924  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3925  "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3926  current_offset, current_dts, sample_size, distance, keyframe);
3927  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3928  ff_rfps_add_frame(mov->fc, st, current_dts);
3929  }
3930 
3931  current_offset += sample_size;
3932  stream_size += sample_size;
3933 
3934  /* A negative sample duration is invalid based on the spec,
3935  * but some samples need it to correct the DTS. */
3936  if (sc->stts_data[stts_index].duration < 0) {
3937  av_log(mov->fc, AV_LOG_WARNING,
3938  "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3939  sc->stts_data[stts_index].duration, stts_index,
3940  st->index);
3941  dts_correction += sc->stts_data[stts_index].duration - 1;
3942  sc->stts_data[stts_index].duration = 1;
3943  }
3944  current_dts += sc->stts_data[stts_index].duration;
3945  if (!dts_correction || current_dts + dts_correction > last_dts) {
3946  current_dts += dts_correction;
3947  dts_correction = 0;
3948  } else {
3949  /* Avoid creating non-monotonous DTS */
3950  dts_correction += current_dts - last_dts - 1;
3951  current_dts = last_dts + 1;
3952  }
3953  last_dts = current_dts;
3954  distance++;
3955  stts_sample++;
3956  current_sample++;
3957  if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3958  stts_sample = 0;
3959  stts_index++;
3960  }
3961  }
3962  }
3963  if (st->duration > 0)
3964  st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3965  } else {
3966  unsigned chunk_samples, total = 0;
3967 
3968  if (!sc->chunk_count)
3969  return;
3970 
3971  // compute total chunk count
3972  for (i = 0; i < sc->stsc_count; i++) {
3973  unsigned count, chunk_count;
3974 
3975  chunk_samples = sc->stsc_data[i].count;
3976  if (i != sc->stsc_count - 1 &&
3977  sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3978  av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3979  return;
3980  }
3981 
3982  if (sc->samples_per_frame >= 160) { // gsm
3983  count = chunk_samples / sc->samples_per_frame;
3984  } else if (sc->samples_per_frame > 1) {
3985  unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3986  count = (chunk_samples+samples-1) / samples;
3987  } else {
3988  count = (chunk_samples+1023) / 1024;
3989  }
3990 
3991  if (mov_stsc_index_valid(i, sc->stsc_count))
3992  chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3993  else
3994  chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3995  total += chunk_count * count;
3996  }
3997 
3998  av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3999  if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
4000  return;
4002  st->nb_index_entries + total,
4003  sizeof(*st->index_entries)) < 0) {
4004  st->nb_index_entries = 0;
4005  return;
4006  }
4007  st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
4008 
4009  // populate index
4010  for (i = 0; i < sc->chunk_count; i++) {
4011  current_offset = sc->chunk_offsets[i];
4012  if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
4013  i + 1 == sc->stsc_data[stsc_index + 1].first)
4014  stsc_index++;
4015  chunk_samples = sc->stsc_data[stsc_index].count;
4016 
4017  while (chunk_samples > 0) {
4018  AVIndexEntry *e;
4019  unsigned size, samples;
4020 
4021  if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
4023  "Zero bytes per frame, but %d samples per frame",
4024  sc->samples_per_frame);
4025  return;
4026  }
4027 
4028  if (sc->samples_per_frame >= 160) { // gsm
4029  samples = sc->samples_per_frame;
4030  size = sc->bytes_per_frame;
4031  } else {
4032  if (sc->samples_per_frame > 1) {
4033  samples = FFMIN((1024 / sc->samples_per_frame)*
4034  sc->samples_per_frame, chunk_samples);
4035  size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
4036  } else {
4037  samples = FFMIN(1024, chunk_samples);
4038  size = samples * sc->sample_size;
4039  }
4040  }
4041 
4042  if (st->nb_index_entries >= total) {
4043  av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
4044  return;
4045  }
4046  if (size > 0x3FFFFFFF) {
4047  av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
4048  return;
4049  }
4050  e = &st->index_entries[st->nb_index_entries++];
4051  e->pos = current_offset;
4052  e->timestamp = current_dts;
4053  e->size = size;
4054  e->min_distance = 0;
4055  e->flags = AVINDEX_KEYFRAME;
4056  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
4057  "size %u, duration %u\n", st->index, i, current_offset, current_dts,
4058  size, samples);
4059 
4060  current_offset += size;
4061  current_dts += samples;
4062  chunk_samples -= samples;
4063  }
4064  }
4065  }
4066 
4067  if (!mov->ignore_editlist && mov->advanced_editlist) {
4068  // Fix index according to edit lists.
4069  mov_fix_index(mov, st);
4070  }
4071 
4072  // Update start time of the stream.
4074  st->start_time = st->index_entries[0].timestamp + sc->dts_shift;
4075  if (sc->ctts_data) {
4076  st->start_time += sc->ctts_data[0].duration;
4077  }
4078  }
4079 
4080  mov_estimate_video_delay(mov, st);
4081 }
4082 
4083 static int test_same_origin(const char *src, const char *ref) {
4084  char src_proto[64];
4085  char ref_proto[64];
4086  char src_auth[256];
4087  char ref_auth[256];
4088  char src_host[256];
4089  char ref_host[256];
4090  int src_port=-1;
4091  int ref_port=-1;
4092 
4093  av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
4094  av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
4095 
4096  if (strlen(src) == 0) {
4097  return -1;
4098  } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
4099  strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
4100  strlen(src_host) + 1 >= sizeof(src_host) ||
4101  strlen(ref_host) + 1 >= sizeof(ref_host)) {
4102  return 0;
4103  } else if (strcmp(src_proto, ref_proto) ||
4104  strcmp(src_auth, ref_auth) ||
4105  strcmp(src_host, ref_host) ||
4106  src_port != ref_port) {
4107  return 0;
4108  } else
4109  return 1;
4110 }
4111 
4112 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
4113 {
4114  /* try relative path, we do not try the absolute because it can leak information about our
4115  system to an attacker */
4116  if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4117  char filename[1025];
4118  const char *src_path;
4119  int i, l;
4120 
4121  /* find a source dir */
4122  src_path = strrchr(src, '/');
4123  if (src_path)
4124  src_path++;
4125  else
4126  src_path = src;
4127 
4128  /* find a next level down to target */
4129  for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4130  if (ref->path[l] == '/') {
4131  if (i == ref->nlvl_to - 1)
4132  break;
4133  else
4134  i++;
4135  }
4136 
4137  /* compose filename if next level down to target was found */
4138  if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
4139  memcpy(filename, src, src_path - src);
4140  filename[src_path - src] = 0;
4141 
4142  for (i = 1; i < ref->nlvl_from; i++)
4143  av_strlcat(filename, "../", sizeof(filename));
4144 
4145  av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4146  if (!c->use_absolute_path) {
4147  int same_origin = test_same_origin(src, filename);
4148 
4149  if (!same_origin) {
4150  av_log(c->fc, AV_LOG_ERROR,
4151  "Reference with mismatching origin, %s not tried for security reasons, "
4152  "set demuxer option use_absolute_path to allow it anyway\n",
4153  ref->path);
4154  return AVERROR(ENOENT);
4155  }
4156 
4157  if(strstr(ref->path + l + 1, "..") ||
4158  strstr(ref->path + l + 1, ":") ||
4159  (ref->nlvl_from > 1 && same_origin < 0) ||
4160  (filename[0] == '/' && src_path == src))
4161  return AVERROR(ENOENT);
4162  }
4163 
4164  if (strlen(filename) + 1 == sizeof(filename))
4165  return AVERROR(ENOENT);
4166  if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4167  return 0;
4168  }
4169  } else if (c->use_absolute_path) {
4170  av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4171  "this is a possible security issue\n");
4172  if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4173  return 0;
4174  } else {
4175  av_log(c->fc, AV_LOG_ERROR,
4176  "Absolute path %s not tried for security reasons, "
4177  "set demuxer option use_absolute_path to allow absolute paths\n",
4178  ref->path);
4179  }
4180 
4181  return AVERROR(ENOENT);
4182 }
4183 
4185 {
4186  if (sc->time_scale <= 0) {
4187  av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4188  sc->time_scale = c->time_scale;
4189  if (sc->time_scale <= 0)
4190  sc->time_scale = 1;
4191  }
4192 }
4193 
4195 {
4196  AVStream *st;
4197  MOVStreamContext *sc;
4198  int ret;
4199 
4200  st = avformat_new_stream(c->fc, NULL);
4201  if (!st) return AVERROR(ENOMEM);
4202  st->id = -1;
4203  sc = av_mallocz(sizeof(MOVStreamContext));
4204  if (!sc) return AVERROR(ENOMEM);
4205 
4206  st->priv_data = sc;
4208  sc->ffindex = st->index;
4209  c->trak_index = st->index;
4210 
4211  if ((ret = mov_read_default(c, pb, atom)) < 0)
4212  return ret;
4213 
4214  c->trak_index = -1;
4215 
4216  // Here stsc refers to a chunk not described in stco. This is technically invalid,
4217  // but we can overlook it (clearing stsc) whenever stts_count == 0 (indicating no samples).
4218  if (!sc->chunk_count && !sc->stts_count && sc->stsc_count) {
4219  sc->stsc_count = 0;
4220  av_freep(&sc->stsc_data);
4221  }
4222 
4223  /* sanity checks */
4224  if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4225  (!sc->sample_size && !sc->sample_count))) ||
4226  (!sc->chunk_count && sc->sample_count)) {
4227  av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4228  st->index);
4229  return 0;
4230  }
4231  if (sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
4232  av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
4233  st->index);
4234  return AVERROR_INVALIDDATA;
4235  }
4236 
4237  fix_timescale(c, sc);
4238 
4239  avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4240 
4241  mov_build_index(c, st);
4242 
4243  if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4244  MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4245  if (c->enable_drefs) {
4246  if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4247  av_log(c->fc, AV_LOG_ERROR,
4248  "stream %d, error opening alias: path='%s', dir='%s', "
4249  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4250  st->index, dref->path, dref->dir, dref->filename,
4251  dref->volume, dref->nlvl_from, dref->nlvl_to);
4252  } else {
4253  av_log(c->fc, AV_LOG_WARNING,
4254  "Skipped opening external track: "
4255  "stream %d, alias: path='%s', dir='%s', "
4256  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4257  "Set enable_drefs to allow this.\n",
4258  st->index, dref->path, dref->dir, dref->filename,
4259  dref->volume, dref->nlvl_from, dref->nlvl_to);
4260  }
4261  } else {
4262  sc->pb = c->fc->pb;
4263  sc->pb_is_copied = 1;
4264  }
4265 
4266  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4267  if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4268  sc->height && sc->width &&
4269  (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4270  st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4271  ((double)st->codecpar->width * sc->height), INT_MAX);
4272  }
4273 
4274 #if FF_API_R_FRAME_RATE
4275  if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4277  sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4278 #endif
4279  }
4280 
4281  // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4282  if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4283  TAG_IS_AVCI(st->codecpar->codec_tag)) {
4284  ret = ff_generate_avci_extradata(st);
4285  if (ret < 0)
4286  return ret;
4287  }
4288 
4289  switch (st->codecpar->codec_id) {
4290 #if CONFIG_H261_DECODER
4291  case AV_CODEC_ID_H261:
4292 #endif
4293 #if CONFIG_H263_DECODER
4294  case AV_CODEC_ID_H263:
4295 #endif
4296 #if CONFIG_MPEG4_DECODER
4297  case AV_CODEC_ID_MPEG4:
4298 #endif
4299  st->codecpar->width = 0; /* let decoder init width/height */
4300  st->codecpar->height= 0;
4301  break;
4302  }
4303 
4304  // If the duration of the mp3 packets is not constant, then they could need a parser
4305  if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4306  && sc->stts_count > 3
4307  && sc->stts_count*10 > st->nb_frames
4308  && sc->time_scale == st->codecpar->sample_rate) {
4310  }
4311  /* Do not need those anymore. */
4312  av_freep(&sc->chunk_offsets);
4313  av_freep(&sc->sample_sizes);
4314  av_freep(&sc->keyframes);
4315  av_freep(&sc->stts_data);
4316  av_freep(&sc->stps_data);
4317  av_freep(&sc->elst_data);
4318  av_freep(&sc->rap_group);
4319 
4320  return 0;
4321 }
4322 
4324 {
4325  int ret;
4326  c->itunes_metadata = 1;
4327  ret = mov_read_default(c, pb, atom);
4328  c->itunes_metadata = 0;
4329  return ret;
4330 }
4331 
4333 {
4334  uint32_t count;
4335  uint32_t i;
4336 
4337  if (atom.size < 8)
4338  return 0;
4339 
4340  avio_skip(pb, 4);
4341  count = avio_rb32(pb);
4342  if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4343  av_log(c->fc, AV_LOG_ERROR,
4344  "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4345  return AVERROR_INVALIDDATA;
4346  }
4347 
4348  c->meta_keys_count = count + 1;
4349  c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4350  if (!c->meta_keys)
4351  return AVERROR(ENOMEM);
4352 
4353  for (i = 1; i <= count; ++i) {
4354  uint32_t key_size = avio_rb32(pb);
4355  uint32_t type = avio_rl32(pb);
4356  if (key_size < 8) {
4357  av_log(c->fc, AV_LOG_ERROR,
4358  "The key# %"PRIu32" in meta has invalid size:"
4359  "%"PRIu32"\n", i, key_size);
4360  return AVERROR_INVALIDDATA;
4361  }
4362  key_size -= 8;
4363  if (type != MKTAG('m','d','t','a')) {
4364  avio_skip(pb, key_size);
4365  }
4366  c->meta_keys[i] = av_mallocz(key_size + 1);
4367  if (!c->meta_keys[i])
4368  return AVERROR(ENOMEM);
4369  avio_read(pb, c->meta_keys[i], key_size);
4370  }
4371 
4372  return 0;
4373 }
4374 
4376 {
4377  int64_t end = avio_tell(pb) + atom.size;
4378  uint8_t *key = NULL, *val = NULL, *mean = NULL;
4379  int i;
4380  int ret = 0;
4381  AVStream *st;
4382  MOVStreamContext *sc;
4383 
4384  if (c->fc->nb_streams < 1)
4385  return 0;
4386  st = c->fc->streams[c->fc->nb_streams-1];
4387  sc = st->priv_data;
4388 
4389  for (i = 0; i < 3; i++) {
4390  uint8_t **p;
4391  uint32_t len, tag;
4392 
4393  if (end - avio_tell(pb) <= 12)
4394  break;
4395 
4396  len = avio_rb32(pb);
4397  tag = avio_rl32(pb);
4398  avio_skip(pb, 4); // flags
4399 
4400  if (len < 12 || len - 12 > end - avio_tell(pb))
4401  break;
4402  len -= 12;
4403 
4404  if (tag == MKTAG('m', 'e', 'a', 'n'))
4405  p = &mean;
4406  else if (tag == MKTAG('n', 'a', 'm', 'e'))
4407  p = &key;
4408  else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4409  avio_skip(pb, 4);
4410  len -= 4;
4411  p = &val;
4412  } else
4413  break;
4414 
4415  if (*p)
4416  break;
4417 
4418  *p = av_malloc(len + 1);
4419  if (!*p) {
4420  ret = AVERROR(ENOMEM);
4421  break;
4422  }
4423  ret = ffio_read_size(pb, *p, len);
4424  if (ret < 0) {
4425  av_freep(p);
4426  break;
4427  }
4428  (*p)[len] = 0;
4429  }
4430 
4431  if (mean && key && val) {
4432  if (strcmp(key, "iTunSMPB") == 0) {
4433  int priming, remainder, samples;
4434  if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4435  if(priming>0 && priming<16384)
4436  sc->start_pad = priming;
4437  }
4438  }
4439  if (strcmp(key, "cdec") != 0) {
4440  av_dict_set(&c->fc->metadata, key, val,
4442  key = val = NULL;
4443  }
4444  } else {
4445  av_log(c->fc, AV_LOG_VERBOSE,
4446  "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4447  }
4448 
4449  avio_seek(pb, end, SEEK_SET);
4450  av_freep(&key);
4451  av_freep(&val);
4452  av_freep(&mean);
4453  return ret;
4454 }
4455 
4457 {
4458  while (atom.size > 8) {
4459  uint32_t tag;
4460  if (avio_feof(pb))
4461  return AVERROR_EOF;
4462  tag = avio_rl32(pb);
4463  atom.size -= 4;
4464  if (tag == MKTAG('h','d','l','r')) {
4465  avio_seek(pb, -8, SEEK_CUR);
4466  atom.size += 8;
4467  return mov_read_default(c, pb, atom);
4468  }
4469  }
4470  return 0;
4471 }
4472 
4473 // return 1 when matrix is identity, 0 otherwise
4474 #define IS_MATRIX_IDENT(matrix) \
4475  ( (matrix)[0][0] == (1 << 16) && \
4476  (matrix)[1][1] == (1 << 16) && \
4477  (matrix)[2][2] == (1 << 30) && \
4478  !(matrix)[0][1] && !(matrix)[0][2] && \
4479  !(matrix)[1][0] && !(matrix)[1][2] && \
4480  !(matrix)[2][0] && !(matrix)[2][1])
4481 
4483 {
4484  int i, j, e;
4485  int width;
4486  int height;
4487  int display_matrix[3][3];
4488  int res_display_matrix[3][3] = { { 0 } };
4489  AVStream *st;
4490  MOVStreamContext *sc;
4491  int version;
4492  int flags;
4493 
4494  if (c->fc->nb_streams < 1)
4495  return 0;
4496  st = c->fc->streams[c->fc->nb_streams-1];
4497  sc = st->priv_data;
4498 
4499  // Each stream (trak) should have exactly 1 tkhd. This catches bad files and
4500  // avoids corrupting AVStreams mapped to an earlier tkhd.
4501  if (st->id != -1)
4502  return AVERROR_INVALIDDATA;
4503 
4504  version = avio_r8(pb);
4505  flags = avio_rb24(pb);
4507 
4508  if (version == 1) {
4509  avio_rb64(pb);
4510  avio_rb64(pb);
4511  } else {
4512  avio_rb32(pb); /* creation time */
4513  avio_rb32(pb); /* modification time */
4514  }
4515  st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4516  avio_rb32(pb); /* reserved */
4517 
4518  /* highlevel (considering edits) duration in movie timebase */
4519  (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4520  avio_rb32(pb); /* reserved */
4521  avio_rb32(pb); /* reserved */
4522 
4523  avio_rb16(pb); /* layer */
4524  avio_rb16(pb); /* alternate group */
4525  avio_rb16(pb); /* volume */
4526  avio_rb16(pb); /* reserved */
4527 
4528  //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4529  // they're kept in fixed point format through all calculations
4530  // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4531  // side data, but the scale factor is not needed to calculate aspect ratio
4532  for (i = 0; i < 3; i++) {
4533  display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
4534  display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
4535  display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
4536  }
4537 
4538  width = avio_rb32(pb); // 16.16 fixed point track width
4539  height = avio_rb32(pb); // 16.16 fixed point track height
4540  sc->width = width >> 16;
4541  sc->height = height >> 16;
4542 
4543  // apply the moov display matrix (after the tkhd one)
4544  for (i = 0; i < 3; i++) {
4545  const int sh[3] = { 16, 16, 30 };
4546  for (j = 0; j < 3; j++) {
4547  for (e = 0; e < 3; e++) {
4548  res_display_matrix[i][j] +=
4549  ((int64_t) display_matrix[i][e] *
4550  c->movie_display_matrix[e][j]) >> sh[e];
4551  }
4552  }
4553  }
4554 
4555  // save the matrix when it is not the default identity
4556  if (!IS_MATRIX_IDENT(res_display_matrix)) {
4557  double rotate;
4558 
4559  av_freep(&sc->display_matrix);
4560  sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4561  if (!sc->display_matrix)
4562  return AVERROR(ENOMEM);
4563 
4564  for (i = 0; i < 3; i++)
4565  for (j = 0; j < 3; j++)
4566  sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4567 
4570  if (!isnan(rotate)) {
4571  char rotate_buf[64];
4572  rotate = -rotate;
4573  if (rotate < 0) // for backward compatibility
4574  rotate += 360;
4575  snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4576  av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4577  }
4578 #endif
4579  }
4580 
4581  // transform the display width/height according to the matrix
4582  // to keep the same scale, use [width height 1<<16]
4583  if (width && height && sc->display_matrix) {
4584  double disp_transform[2];
4585 
4586  for (i = 0; i < 2; i++)
4587  disp_transform[i] = hypot(sc->display_matrix[0 + i],
4588  sc->display_matrix[3 + i]);
4589 
4590  if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
4591  disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4592  fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4594  disp_transform[0] / disp_transform[1],
4595  INT_MAX);
4596  }
4597  return 0;
4598 }
4599 
4601 {
4602  MOVFragment *frag = &c->fragment;
4603  MOVTrackExt *trex = NULL;
4604  int flags, track_id, i;
4605 
4606  avio_r8(pb); /* version */
4607  flags = avio_rb24(pb);
4608 
4609  track_id = avio_rb32(pb);
4610  if (!track_id)
4611  return AVERROR_INVALIDDATA;
4612  frag->track_id = track_id;
4613  set_frag_stream(&c->frag_index, track_id);
4614  for (i = 0; i < c->trex_count; i++)
4615  if (c->trex_data[i].track_id == frag->track_id) {
4616  trex = &c->trex_data[i];
4617  break;
4618  }
4619  if (!trex) {
4620  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4621  return AVERROR_INVALIDDATA;
4622  }
4623  c->fragment.found_tfhd = 1;
4624 
4627  frag->moof_offset : frag->implicit_offset;
4628  frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4629 
4630  frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4631  avio_rb32(pb) : trex->duration;
4632  frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
4633  avio_rb32(pb) : trex->size;
4634  frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
4635  avio_rb32(pb) : trex->flags;
4636  av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4637 
4638  return 0;
4639 }
4640 
4642 {
4643  unsigned i, num;
4644  void *new_tracks;
4645 
4646  num = atom.size / 4;
4647  if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4648  return AVERROR(ENOMEM);
4649 
4650  av_free(c->chapter_tracks);
4651  c->chapter_tracks = new_tracks;
4652  c->nb_chapter_tracks = num;
4653 
4654  for (i = 0; i < num && !pb->eof_reached; i++)
4655  c->chapter_tracks[i] = avio_rb32(pb);
4656 
4657  c->nb_chapter_tracks = i;
4658 
4659  return 0;
4660 }
4661 
4663 {
4664  MOVTrackExt *trex;
4665  int err;
4666 
4667  if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4668  return AVERROR_INVALIDDATA;
4669  if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4670  sizeof(*c->trex_data))) < 0) {
4671  c->trex_count = 0;
4672  return err;
4673  }
4674 
4675  c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4676 
4677  trex = &c->trex_data[c->trex_count++];
4678  avio_r8(pb); /* version */
4679  avio_rb24(pb); /* flags */
4680  trex->track_id = avio_rb32(pb);
4681  trex->stsd_id = avio_rb32(pb);
4682  trex->duration = avio_rb32(pb);
4683  trex->size = avio_rb32(pb);
4684  trex->flags = avio_rb32(pb);
4685  return 0;
4686 }
4687 
4689 {
4690  MOVFragment *frag = &c->fragment;
4691  AVStream *st = NULL;
4692  MOVStreamContext *sc;
4693  int version, i;
4694  MOVFragmentStreamInfo * frag_stream_info;
4695  int64_t base_media_decode_time;
4696 
4697  for (i = 0; i < c->fc->nb_streams; i++) {
4698  if (c->fc->streams[i]->id == frag->track_id) {
4699  st = c->fc->streams[i];
4700  break;
4701  }
4702  }
4703  if (!st) {
4704  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4705  return AVERROR_INVALIDDATA;
4706  }
4707  sc = st->priv_data;
4708  if (sc->pseudo_stream_id + 1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4709  return 0;
4710  version = avio_r8(pb);
4711  avio_rb24(pb); /* flags */
4712  if (version) {
4713  base_media_decode_time = avio_rb64(pb);
4714  } else {
4715  base_media_decode_time = avio_rb32(pb);
4716  }
4717 
4718  frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4719  if (frag_stream_info)
4720  frag_stream_info->tfdt_dts = base_media_decode_time;
4721  sc->track_end = base_media_decode_time;
4722 
4723  return 0;
4724 }
4725 
4727 {
4728  MOVFragment *frag = &c->fragment;
4729  AVStream *st = NULL;
4730  MOVStreamContext *sc;
4731  MOVStts *ctts_data;
4732  uint64_t offset;
4733  int64_t dts, pts = AV_NOPTS_VALUE;
4734  int data_offset = 0;
4735  unsigned entries, first_sample_flags = frag->flags;
4736  int flags, distance, i;
4737  int64_t prev_dts = AV_NOPTS_VALUE;
4738  int next_frag_index = -1, index_entry_pos;
4739  size_t requested_size;
4740  size_t old_ctts_allocated_size;
4741  AVIndexEntry *new_entries;
4742  MOVFragmentStreamInfo * frag_stream_info;
4743 
4744  if (!frag->found_tfhd) {
4745  av_log(c->fc, AV_LOG_ERROR, "trun track id unknown, no tfhd was found\n");
4746  return AVERROR_INVALIDDATA;
4747  }
4748 
4749  for (i = 0; i < c->fc->nb_streams; i++) {
4750  if (c->fc->streams[i]->id == frag->track_id) {
4751  st = c->fc->streams[i];
4752  break;
4753  }
4754  }
4755  if (!st) {
4756  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4757  return AVERROR_INVALIDDATA;
4758  }
4759  sc = st->priv_data;
4760  if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4761  return 0;
4762 
4763  // Find the next frag_index index that has a valid index_entry for
4764  // the current track_id.
4765  //
4766  // A valid index_entry means the trun for the fragment was read
4767  // and it's samples are in index_entries at the given position.
4768  // New index entries will be inserted before the index_entry found.
4769  index_entry_pos = st->nb_index_entries;
4770  for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4771  frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4772  if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4773  next_frag_index = i;
4774  index_entry_pos = frag_stream_info->index_entry;
4775  break;
4776  }
4777  }
4778  av_assert0(index_entry_pos <= st->nb_index_entries);
4779 
4780  avio_r8(pb); /* version */
4781  flags = avio_rb24(pb);
4782  entries = avio_rb32(pb);
4783  av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4784 
4785  if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4786  return AVERROR_INVALIDDATA;
4787  if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
4788  if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4789 
4790  frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4791  if (frag_stream_info)
4792  {
4793  if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4795  pts = frag_stream_info->first_tfra_pts;
4796  av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4797  ", using it for pts\n", pts);
4798  } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4799  // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4800  // pts = frag_stream_info->sidx_pts;
4801  dts = frag_stream_info->sidx_pts - sc->time_offset;
4802  av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4803  ", using it for pts\n", pts);
4804  } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4805  dts = frag_stream_info->tfdt_dts - sc->time_offset;
4806  av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4807  ", using it for dts\n", dts);
4808  } else {
4809  dts = sc->track_end - sc->time_offset;
4810  av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4811  ", using it for dts\n", dts);
4812  }
4813  } else {
4814  dts = sc->track_end - sc->time_offset;
4815  av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4816  ", using it for dts\n", dts);
4817  }
4818  offset = frag->base_data_offset + data_offset;
4819  distance = 0;
4820  av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4821 
4822  // realloc space for new index entries
4823  if((uint64_t)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4824  entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4825  av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4826  }
4827  if (entries <= 0)
4828  return -1;
4829 
4830  requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4831  new_entries = av_fast_realloc(st->index_entries,
4833  requested_size);
4834  if(!new_entries)
4835  return AVERROR(ENOMEM);
4836  st->index_entries= new_entries;
4837 
4838  requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4839  old_ctts_allocated_size = sc->ctts_allocated_size;
4840  ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4841  requested_size);
4842  if (!ctts_data)
4843  return AVERROR(ENOMEM);
4844  sc->ctts_data = ctts_data;
4845 
4846  // In case there were samples without ctts entries, ensure they get
4847  // zero valued entries. This ensures clips which mix boxes with and
4848  // without ctts entries don't pickup uninitialized data.
4849  memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
4850  sc->ctts_allocated_size - old_ctts_allocated_size);
4851 
4852  if (index_entry_pos < st->nb_index_entries) {
4853  // Make hole in index_entries and ctts_data for new samples
4854  memmove(st->index_entries + index_entry_pos + entries,
4855  st->index_entries + index_entry_pos,
4856  sizeof(*st->index_entries) *
4857  (st->nb_index_entries - index_entry_pos));
4858  memmove(sc->ctts_data + index_entry_pos + entries,
4859  sc->ctts_data + index_entry_pos,
4860  sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4861  if (index_entry_pos < sc->current_sample) {
4862  sc->current_sample += entries;
4863  }
4864  }
4865 
4866  st->nb_index_entries += entries;
4867  sc->ctts_count = st->nb_index_entries;
4868 
4869  // Record the index_entry position in frag_index of this fragment
4870  if (frag_stream_info)
4871  frag_stream_info->index_entry = index_entry_pos;
4872 
4873  if (index_entry_pos > 0)
4874  prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4875 
4876  for (i = 0; i < entries && !pb->eof_reached; i++) {
4877  unsigned sample_size = frag->size;
4878  int sample_flags = i ? frag->flags : first_sample_flags;
4879  unsigned sample_duration = frag->duration;
4880  unsigned ctts_duration = 0;
4881  int keyframe = 0;
4882  int index_entry_flags = 0;
4883 
4884  if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4885  if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
4886  if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
4887  if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
4888 
4889  mov_update_dts_shift(sc, ctts_duration);
4890  if (pts != AV_NOPTS_VALUE) {
4891  dts = pts - sc->dts_shift;
4892  if (flags & MOV_TRUN_SAMPLE_CTS) {
4893  dts -= ctts_duration;
4894  } else {
4895  dts -= sc->time_offset;
4896  }
4897  av_log(c->fc, AV_LOG_DEBUG,
4898  "pts %"PRId64" calculated dts %"PRId64
4899  " sc->dts_shift %d ctts.duration %d"
4900  " sc->time_offset %"PRId64
4901  " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4902  pts, dts,
4903  sc->dts_shift, ctts_duration,
4904  sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4905  pts = AV_NOPTS_VALUE;
4906  }
4907 
4909  keyframe = 1;
4910  else
4911  keyframe =
4912  !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4914  if (keyframe) {
4915  distance = 0;
4916  index_entry_flags |= AVINDEX_KEYFRAME;
4917  }
4918  // Fragments can overlap in time. Discard overlapping frames after
4919  // decoding.
4920  if (prev_dts >= dts)
4921  index_entry_flags |= AVINDEX_DISCARD_FRAME;
4922 
4923  st->index_entries[index_entry_pos].pos = offset;
4924  st->index_entries[index_entry_pos].timestamp = dts;
4925  st->index_entries[index_entry_pos].size= sample_size;
4926  st->index_entries[index_entry_pos].min_distance= distance;
4927  st->index_entries[index_entry_pos].flags = index_entry_flags;
4928 
4929  sc->ctts_data[index_entry_pos].count = 1;
4930  sc->ctts_data[index_entry_pos].duration = ctts_duration;
4931  index_entry_pos++;
4932 
4933  av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4934  "size %u, distance %d, keyframe %d\n", st->index,
4935  index_entry_pos, offset, dts, sample_size, distance, keyframe);
4936  distance++;
4937  dts += sample_duration;
4938  offset += sample_size;
4939  sc->data_size += sample_size;
4940 
4941  if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
4942  1 <= INT64_MAX - sc->nb_frames_for_fps
4943  ) {
4944  sc->duration_for_fps += sample_duration;
4945  sc->nb_frames_for_fps ++;
4946  }
4947  }
4948  if (i < entries) {
4949  // EOF found before reading all entries. Fix the hole this would
4950  // leave in index_entries and ctts_data
4951  int gap = entries - i;
4952  memmove(st->index_entries + index_entry_pos,
4953  st->index_entries + index_entry_pos + gap,
4954  sizeof(*st->index_entries) *
4955  (st->nb_index_entries - (index_entry_pos + gap)));
4956  memmove(sc->ctts_data + index_entry_pos,
4957  sc->ctts_data + index_entry_pos + gap,
4958  sizeof(*sc->ctts_data) *
4959  (sc->ctts_count - (index_entry_pos + gap)));
4960 
4961  st->nb_index_entries -= gap;
4962  sc->ctts_count -= gap;
4963  if (index_entry_pos < sc->current_sample) {
4964  sc->current_sample -= gap;
4965  }
4966  entries = i;
4967  }
4968 
4969  // The end of this new fragment may overlap in time with the start
4970  // of the next fragment in index_entries. Mark the samples in the next
4971  // fragment that overlap with AVINDEX_DISCARD_FRAME
4972  prev_dts = AV_NOPTS_VALUE;
4973  if (index_entry_pos > 0)
4974  prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4975  for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4976  if (prev_dts < st->index_entries[i].timestamp)
4977  break;
4979  }
4980 
4981  // If a hole was created to insert the new index_entries into,
4982  // the index_entry recorded for all subsequent moof must
4983  // be incremented by the number of entries inserted.
4984  fix_frag_index_entries(&c->frag_index, next_frag_index,
4985  frag->track_id, entries);
4986 
4987  if (pb->eof_reached) {
4988  av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4989  return AVERROR_EOF;
4990  }
4991 
4992  frag->implicit_offset = offset;
4993 
4994  sc->track_end = dts + sc->time_offset;
4995  if (st->duration < sc->track_end)
4996  st->duration = sc->track_end;
4997 
4998  return 0;
4999 }
5000 
5002 {
5003  int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
5004  uint8_t version;
5005  unsigned i, j, track_id, item_count;
5006  AVStream *st = NULL;
5007  AVStream *ref_st = NULL;
5008  MOVStreamContext *sc, *ref_sc = NULL;
5009  AVRational timescale;
5010 
5011  version = avio_r8(pb);
5012  if (version > 1) {
5013  avpriv_request_sample(c->fc, "sidx version %u", version);
5014  return 0;
5015  }
5016 
5017  avio_rb24(pb); // flags
5018 
5019  track_id = avio_rb32(pb); // Reference ID
5020  for (i = 0; i < c->fc->nb_streams; i++) {
5021  if (c->fc->streams[i]->id == track_id) {
5022  st = c->fc->streams[i];
5023  break;
5024  }
5025  }
5026  if (!st) {
5027  av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
5028  return 0;
5029  }
5030 
5031  sc = st->priv_data;
5032 
5033  timescale = av_make_q(1, avio_rb32(pb));
5034 
5035  if (timescale.den <= 0) {
5036  av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
5037  return AVERROR_INVALIDDATA;
5038  }
5039 
5040  if (version == 0) {
5041  pts = avio_rb32(pb);
5042  offset += avio_rb32(pb);
5043  } else {
5044  pts = avio_rb64(pb);
5045  offset += avio_rb64(pb);
5046  }
5047 
5048  avio_rb16(pb); // reserved
5049 
5050  item_count = avio_rb16(pb);
5051  if (item_count == 0)
5052  return AVERROR_INVALIDDATA;
5053 
5054  for (i = 0; i < item_count; i++) {
5055  int index;
5056  MOVFragmentStreamInfo * frag_stream_info;
5057  uint32_t size = avio_rb32(pb);
5058  uint32_t duration = avio_rb32(pb);
5059  if (size & 0x80000000) {
5060  avpriv_request_sample(c->fc, "sidx reference_type 1");
5061  return AVERROR_PATCHWELCOME;
5062  }
5063  avio_rb32(pb); // sap_flags
5064  timestamp = av_rescale_q(pts, st->time_base, timescale);
5065 
5066  index = update_frag_index(c, offset);
5067  frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
5068  if (frag_stream_info)
5069  frag_stream_info->sidx_pts = timestamp;
5070 
5071  offset += size;
5072  pts += duration;
5073  }
5074 
5075  st->duration = sc->track_end = pts;
5076 
5077  sc->has_sidx = 1;
5078 
5079  if (offset == avio_size(pb)) {
5080  // Find first entry in fragment index that came from an sidx.
5081  // This will pretty much always be the first entry.
5082  for (i = 0; i < c->frag_index.nb_items; i++) {
5083  MOVFragmentIndexItem * item = &c->frag_index.item[i];
5084  for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
5085  MOVFragmentStreamInfo * si;
5086  si = &item->stream_info[j];
5087  if (si->sidx_pts != AV_NOPTS_VALUE) {
5088  ref_st = c->fc->streams[j];
5089  ref_sc = ref_st->priv_data;
5090  break;
5091  }
5092  }
5093  }
5094  if (ref_st) for (i = 0; i < c->fc->nb_streams; i++) {
5095  st = c->fc->streams[i];
5096  sc = st->priv_data;
5097  if (!sc->has_sidx) {
5098  st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
5099  }
5100  }
5101 
5102  c->frag_index.complete = 1;
5103  }
5104 
5105  return 0;
5106 }
5107 
5108 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
5109 /* like the files created with Adobe Premiere 5.0, for samples see */
5110 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
5112 {
5113  int err;
5114 
5115  if (atom.size < 8)
5116  return 0; /* continue */
5117  if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
5118  avio_skip(pb, atom.size - 4);
5119  return 0;
5120  }
5121  atom.type = avio_rl32(pb);
5122  atom.size -= 8;
5123  if (atom.type != MKTAG('m','d','a','t')) {
5124  avio_skip(pb, atom.size);
5125  return 0;
5126  }
5127  err = mov_read_mdat(c, pb, atom);
5128  return err;
5129 }
5130 
5132 {
5133 #if CONFIG_ZLIB
5134  AVIOContext ctx;
5135  uint8_t *cmov_data;
5136  uint8_t *moov_data; /* uncompressed data */
5137  long cmov_len, moov_len;
5138  int ret = -1;
5139 
5140  avio_rb32(pb); /* dcom atom */
5141  if (avio_rl32(pb) != MKTAG('d','c','o','m'))
5142  return AVERROR_INVALIDDATA;
5143  if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
5144  av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
5145  return AVERROR_INVALIDDATA;
5146  }
5147  avio_rb32(pb); /* cmvd atom */
5148  if (avio_rl32(pb) != MKTAG('c','m','v','d'))
5149  return AVERROR_INVALIDDATA;
5150  moov_len = avio_rb32(pb); /* uncompressed size */
5151  cmov_len = atom.size - 6 * 4;
5152 
5153  cmov_data = av_malloc(cmov_len);
5154  if (!cmov_data)
5155  return AVERROR(ENOMEM);
5156  moov_data = av_malloc(moov_len);
5157  if (!moov_data) {
5158  av_free(cmov_data);
5159  return AVERROR(ENOMEM);
5160  }
5161  ret = ffio_read_size(pb, cmov_data, cmov_len);
5162  if (ret < 0)
5163  goto free_and_return;
5164 
5165  ret = AVERROR_INVALIDDATA;
5166  if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5167  goto free_and_return;
5168  if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5169  goto free_and_return;
5171  atom.type = MKTAG('m','o','o','v');
5172  atom.size = moov_len;
5173  ret = mov_read_default(c, &ctx, atom);
5174 free_and_return:
5175  av_free(moov_data);
5176  av_free(cmov_data);
5177  return ret;
5178 #else
5179  av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5180  return AVERROR(ENOSYS);
5181 #endif
5182 }
5183 
5184 /* edit list atom */
5186 {
5187  MOVStreamContext *sc;
5188  int i, edit_count, version;
5189  int64_t elst_entry_size;
5190 
5191  if (c->fc->nb_streams < 1 || c->ignore_editlist)
5192  return 0;
5193  sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5194 
5195  version = avio_r8(pb); /* version */
5196  avio_rb24(pb); /* flags */
5197  edit_count = avio_rb32(pb); /* entries */
5198  atom.size -= 8;
5199 
5200  elst_entry_size = version == 1 ? 20 : 12;
5201  if (atom.size != edit_count * elst_entry_size) {
5203  av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5204  edit_count, atom.size + 8);
5205  return AVERROR_INVALIDDATA;
5206  } else {
5207  edit_count = atom.size / elst_entry_size;
5208  if (edit_count * elst_entry_size != atom.size) {
5209  av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5210  }
5211  }
5212  }
5213 
5214  if (!edit_count)
5215  return 0;
5216  if (sc->elst_data)
5217  av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5218  av_free(sc->elst_data);
5219  sc->elst_count = 0;
5220  sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5221  if (!sc->elst_data)
5222  return AVERROR(ENOMEM);
5223 
5224  av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5225  for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5226  MOVElst *e = &sc->elst_data[i];
5227 
5228  if (version == 1) {
5229  e->duration = avio_rb64(pb);
5230  e->time = avio_rb64(pb);
5231  atom.size -= 16;
5232  } else {
5233  e->duration = avio_rb32(pb); /* segment duration */
5234  e->time = (int32_t)avio_rb32(pb); /* media time */
5235  atom.size -= 8;
5236  }
5237  e->rate = avio_rb32(pb) / 65536.0;
5238  atom.size -= 4;
5239  av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5240  e->duration, e->time, e->rate);
5241 
5242  if (e->time < 0 && e->time != -1 &&
5244  av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5245  c->fc->nb_streams-1, i, e->time);
5246  return AVERROR_INVALIDDATA;
5247  }
5248  }
5249  sc->elst_count = i;
5250 
5251  return 0;
5252 }
5253 
5255 {
5256  MOVStreamContext *sc;
5257 
5258  if (c->fc->nb_streams < 1)
5259  return AVERROR_INVALIDDATA;
5260  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5261  sc->timecode_track = avio_rb32(pb);
5262  return 0;
5263 }
5264 
5266 {
5267  AVStream *st;
5268  int ret;
5269 
5270  if (c->fc->nb_streams < 1)
5271  return 0;
5272  st = c->fc->streams[c->fc->nb_streams - 1];
5273 
5274  if (atom.size < 4) {
5275  av_log(c->fc, AV_LOG_ERROR, "Empty AV1 Codec Configuration Box\n");
5276  return AVERROR_INVALIDDATA;
5277  }
5278 
5279  /* For now, propagate only the OBUs, if any. Once libavcodec is
5280  updated to handle isobmff style extradata this can be removed. */
5281  avio_skip(pb, 4);
5282 
5283  if (atom.size == 4)
5284  return 0;
5285 
5286  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 4);
5287  if (ret < 0)
5288  return ret;
5289 
5290  return 0;
5291 }
5292 
5294 {
5295  AVStream *st;
5296  int version, color_range, color_primaries, color_trc, color_space;
5297 
5298  if (c->fc->nb_streams < 1)
5299  return 0;
5300  st = c->fc->streams[c->fc->nb_streams - 1];
5301 
5302  if (atom.size < 5) {
5303  av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5304  return AVERROR_INVALIDDATA;
5305  }
5306 
5307  version = avio_r8(pb);
5308  if (version != 1) {
5309  av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5310  return 0;
5311  }
5312  avio_skip(pb, 3); /* flags */
5313 
5314  avio_skip(pb, 2); /* profile + level */
5315  color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5316  color_primaries = avio_r8(pb);
5317  color_trc = avio_r8(pb);
5318  color_space = avio_r8(pb);
5319  if (avio_rb16(pb)) /* codecIntializationDataSize */
5320  return AVERROR_INVALIDDATA;
5321 
5322  if (!av_color_primaries_name(color_primaries))
5323  color_primaries = AVCOL_PRI_UNSPECIFIED;
5324  if (!av_color_transfer_name(color_trc))
5325  color_trc = AVCOL_TRC_UNSPECIFIED;
5326  if (!av_color_space_name(color_space))
5327  color_space = AVCOL_SPC_UNSPECIFIED;
5328 
5329  st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5331  st->codecpar->color_trc = color_trc;
5332  st->codecpar->color_space = color_space;
5333 
5334  return 0;
5335 }
5336 
5338 {
5339  MOVStreamContext *sc;
5340  const int chroma_den = 50000;
5341  const int luma_den = 10000;
5342  int i, j, version;
5343 
5344  if (c->fc->nb_streams < 1)
5345  return AVERROR_INVALIDDATA;
5346 
5347  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5348 
5349  if (atom.size < 5) {
5350  av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5351  return AVERROR_INVALIDDATA;
5352  }
5353 
5354  version = avio_r8(pb);
5355  if (version) {
5356  av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5357  return 0;
5358  }
5359  if (sc->mastering)
5360  return AVERROR_INVALIDDATA;
5361 
5362  avio_skip(pb, 3); /* flags */
5363 
5365  if (!sc->mastering)
5366  return AVERROR(ENOMEM);
5367 
5368  for (i = 0; i < 3; i++)
5369  for (j = 0; j < 2; j++)
5370  sc->mastering->display_primaries[i][j] =
5371  av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5372  for (i = 0; i < 2; i++)
5373  sc->mastering->white_point[i] =
5374  av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5375  sc->mastering->max_luminance =
5376  av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
5377  sc->mastering->min_luminance =
5378  av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5379 
5380  sc->mastering->has_primaries = 1;
5381  sc->mastering->has_luminance = 1;
5382 
5383  return 0;
5384 }
5385 
5387 {
5388  MOVStreamContext *sc;
5389  const int mapping[3] = {1, 2, 0};
5390  const int chroma_den = 50000;
5391  const int luma_den = 10000;
5392  int i;
5393 
5394  if (c->fc->nb_streams < 1)
5395  return AVERROR_INVALIDDATA;
5396 
5397  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5398 
5399  if (atom.size < 24 || sc->mastering) {
5400  av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5401  return AVERROR_INVALIDDATA;
5402  }
5403 
5405  if (!sc->mastering)
5406  return AVERROR(ENOMEM);
5407 
5408  for (i = 0; i < 3; i++) {
5409  const int j = mapping[i];
5410  sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5411  sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5412  }
5413  sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5414  sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5415 
5416  sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5417  sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5418 
5419  sc->mastering->has_luminance = 1;
5420  sc->mastering->has_primaries = 1;
5421 
5422  return 0;
5423 }
5424 
5426 {
5427  MOVStreamContext *sc;
5428  int version;
5429 
5430  if (c->fc->nb_streams < 1)
5431  return AVERROR_INVALIDDATA;
5432 
5433  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5434 
5435  if (atom.size < 5) {
5436  av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5437  return AVERROR_INVALIDDATA;
5438  }
5439 
5440  version = avio_r8(pb);
5441  if (version) {
5442  av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5443  return 0;
5444  }
5445  avio_skip(pb, 3); /* flags */
5446 
5447  if (sc->coll){
5448  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate COLL\n");
5449  return 0;
5450  }
5451 
5453  if (!sc->coll)
5454  return AVERROR(ENOMEM);
5455 
5456  sc->coll->MaxCLL = avio_rb16(pb);
5457  sc->coll->MaxFALL = avio_rb16(pb);
5458 
5459  return 0;
5460 }
5461 
5463 {
5464  MOVStreamContext *sc;
5465 
5466  if (c->fc->nb_streams < 1)
5467  return AVERROR_INVALIDDATA;
5468 
5469  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5470 
5471  if (atom.size < 4) {
5472  av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5473  return AVERROR_INVALIDDATA;
5474  }
5475 
5476  if (sc->coll){
5477  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate CLLI/COLL\n");
5478  return 0;
5479  }
5480 
5482  if (!sc->coll)
5483  return AVERROR(ENOMEM);
5484 
5485  sc->coll->MaxCLL = avio_rb16(pb);
5486  sc->coll->MaxFALL = avio_rb16(pb);
5487 
5488  return 0;
5489 }
5490 
5492 {
5493  AVStream *st;
5494  MOVStreamContext *sc;
5495  enum AVStereo3DType type;
5496  int mode;
5497 
5498  if (c->fc->nb_streams < 1)
5499  return 0;
5500 
5501  st = c->fc->streams[c->fc->nb_streams - 1];
5502  sc = st->priv_data;
5503 
5504  if (atom.size < 5) {
5505  av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5506  return AVERROR_INVALIDDATA;
5507  }
5508 
5509  if (sc->stereo3d)
5510  return AVERROR_INVALIDDATA;
5511 
5512  avio_skip(pb, 4); /* version + flags */
5513 
5514  mode = avio_r8(pb);
5515  switch (mode) {
5516  case 0:
5517  type = AV_STEREO3D_2D;
5518  break;
5519  case 1:
5520  type = AV_STEREO3D_TOPBOTTOM;
5521  break;
5522  case 2:
5523  type = AV_STEREO3D_SIDEBYSIDE;
5524  break;
5525  default:
5526  av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5527  return 0;
5528  }
5529 
5530  sc->stereo3d = av_stereo3d_alloc();
5531  if (!sc->stereo3d)
5532  return AVERROR(ENOMEM);
5533 
5534  sc->stereo3d->type = type;
5535  return 0;
5536 }
5537 
5539 {
5540  AVStream *st;
5541  MOVStreamContext *sc;
5542  int size, version, layout;
5543  int32_t yaw, pitch, roll;
5544  uint32_t l = 0, t = 0, r = 0, b = 0;
5545  uint32_t tag, padding = 0;
5546  enum AVSphericalProjection projection;
5547 
5548  if (c->fc->nb_streams < 1)
5549  return 0;
5550 
5551  st = c->fc->streams[c->fc->nb_streams - 1];
5552  sc = st->priv_data;
5553 
5554  if (atom.size < 8) {
5555  av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5556  return AVERROR_INVALIDDATA;
5557  }
5558 
5559  size = avio_rb32(pb);
5560  if (size <= 12 || size > atom.size)
5561  return AVERROR_INVALIDDATA;
5562 
5563  tag = avio_rl32(pb);
5564  if (tag != MKTAG('s','v','h','d')) {
5565  av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5566  return 0;
5567  }
5568  version = avio_r8(pb);
5569  if (version != 0) {
5570  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5571  version);
5572  return 0;
5573  }
5574  avio_skip(pb, 3); /* flags */
5575  avio_skip(pb, size - 12); /* metadata_source */
5576 
5577  size = avio_rb32(pb);
5578  if (size > atom.size)
5579  return AVERROR_INVALIDDATA;
5580 
5581  tag = avio_rl32(pb);
5582  if (tag != MKTAG('p','r','o','j')) {
5583  av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5584  return 0;
5585  }
5586 
5587  size = avio_rb32(pb);
5588  if (size > atom.size)
5589  return AVERROR_INVALIDDATA;
5590 
5591  tag = avio_rl32(pb);
5592  if (tag != MKTAG('p','r','h','d')) {
5593  av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5594  return 0;
5595  }
5596  version = avio_r8(pb);
5597  if (version != 0) {
5598  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5599  version);
5600  return 0;
5601  }
5602  avio_skip(pb, 3); /* flags */
5603 
5604  /* 16.16 fixed point */
5605  yaw = avio_rb32(pb);
5606  pitch = avio_rb32(pb);
5607  roll = avio_rb32(pb);
5608 
5609  size = avio_rb32(pb);
5610  if (size > atom.size)
5611  return AVERROR_INVALIDDATA;
5612 
5613  tag = avio_rl32(pb);
5614  version = avio_r8(pb);
5615  if (version != 0) {
5616  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5617  version);
5618  return 0;
5619  }
5620  avio_skip(pb, 3); /* flags */
5621  switch (tag) {
5622  case MKTAG('c','b','m','p'):
5623  layout = avio_rb32(pb);
5624  if (layout) {
5625  av_log(c->fc, AV_LOG_WARNING,
5626  "Unsupported cubemap layout %d\n", layout);
5627  return 0;
5628  }
5629  projection = AV_SPHERICAL_CUBEMAP;
5630  padding = avio_rb32(pb);
5631  break;
5632  case MKTAG('e','q','u','i'):
5633  t = avio_rb32(pb);
5634  b = avio_rb32(pb);
5635  l = avio_rb32(pb);
5636  r = avio_rb32(pb);
5637 
5638  if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5639  av_log(c->fc, AV_LOG_ERROR,
5640  "Invalid bounding rectangle coordinates "
5641  "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5642  return AVERROR_INVALIDDATA;
5643  }
5644 
5645  if (l || t || r || b)
5646  projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5647  else
5648  projection = AV_SPHERICAL_EQUIRECTANGULAR;
5649  break;
5650  default:
5651  av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5652  return 0;
5653  }
5654 
5656  if (!sc->spherical)
5657  return AVERROR(ENOMEM);
5658 
5659  sc->spherical->projection = projection;
5660 
5661  sc->spherical->yaw = yaw;
5662  sc->spherical->pitch = pitch;
5663  sc->spherical->roll = roll;
5664 
5665  sc->spherical->padding = padding;
5666 
5667  sc->spherical->bound_left = l;
5668  sc->spherical->bound_top = t;
5669  sc->spherical->bound_right = r;
5670  sc->spherical->bound_bottom = b;
5671 
5672  return 0;
5673 }
5674 
5676 {
5677  int ret = 0;
5678  uint8_t *buffer = av_malloc(len + 1);
5679  const char *val;
5680 
5681  if (!buffer)
5682  return AVERROR(ENOMEM);
5683  buffer[len] = '\0';
5684 
5685  ret = ffio_read_size(pb, buffer, len);
5686  if (ret < 0)
5687  goto out;
5688 
5689  /* Check for mandatory keys and values, try to support XML as best-effort */
5690  if (!sc->spherical &&
5691  av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5692  (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5693  av_stristr(val, "true") &&
5694  (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5695  av_stristr(val, "true") &&
5696  (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5697  av_stristr(val, "equirectangular")) {
5699  if (!sc->spherical)
5700  goto out;
5701 
5703 
5704  if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5705  enum AVStereo3DType mode;
5706 
5707  if (av_stristr(buffer, "left-right"))
5708  mode = AV_STEREO3D_SIDEBYSIDE;
5709  else if (av_stristr(buffer, "top-bottom"))
5710  mode = AV_STEREO3D_TOPBOTTOM;
5711  else
5712  mode = AV_STEREO3D_2D;
5713 
5714  sc->stereo3d = av_stereo3d_alloc();
5715  if (!sc->stereo3d)
5716  goto out;
5717 
5718  sc->stereo3d->type = mode;
5719  }
5720 
5721  /* orientation */
5722  val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5723  if (val)
5724  sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5725  val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5726  if (val)
5727  sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5728  val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5729  if (val)
5730  sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5731  }
5732 
5733 out:
5734  av_free(buffer);
5735  return ret;
5736 }
5737 
5739 {
5740  AVStream *st;
5741  MOVStreamContext *sc;
5742  int64_t ret;
5743  uint8_t uuid[16];
5744  static const uint8_t uuid_isml_manifest[] = {
5745  0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5746  0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5747  };
5748  static const uint8_t uuid_xmp[] = {
5749  0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5750  0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5751  };
5752  static const uint8_t uuid_spherical[] = {
5753  0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5754  0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5755  };
5756 
5757  if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5758  return AVERROR_INVALIDDATA;
5759 
5760  if (c->fc->nb_streams < 1)
5761  return 0;
5762  st = c->fc->streams[c->fc->nb_streams - 1];
5763  sc = st->priv_data;
5764 
5765  ret = avio_read(pb, uuid, sizeof(uuid));
5766  if (ret < 0) {
5767  return ret;
5768  } else if (ret != sizeof(uuid)) {
5769  return AVERROR_INVALIDDATA;
5770  }
5771  if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5772  uint8_t *buffer, *ptr;
5773  char *endptr;
5774  size_t len = atom.size - sizeof(uuid);
5775 
5776  if (len < 4) {
5777  return AVERROR_INVALIDDATA;
5778  }
5779  ret = avio_skip(pb, 4); // zeroes
5780  len -= 4;
5781 
5782  buffer = av_mallocz(len + 1);
5783  if (!buffer) {
5784  return AVERROR(ENOMEM);
5785  }
5786  ret = avio_read(pb, buffer, len);
5787  if (ret < 0) {
5788  av_free(buffer);
5789  return ret;
5790  } else if (ret != len) {
5791  av_free(buffer);
5792  return AVERROR_INVALIDDATA;
5793  }
5794 
5795  ptr = buffer;
5796  while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5797  ptr += sizeof("systemBitrate=\"") - 1;
5798  c->bitrates_count++;
5799  c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5800  if (!c->bitrates) {
5801  c->bitrates_count = 0;
5802  av_free(buffer);
5803  return AVERROR(ENOMEM);
5804  }
5805  errno = 0;
5806  ret = strtol(ptr, &endptr, 10);
5807  if (ret < 0 || errno || *endptr != '"') {
5808  c->bitrates[c->bitrates_count - 1] = 0;
5809  } else {
5810  c->bitrates[c->bitrates_count - 1] = ret;
5811  }
5812  }
5813 
5814  av_free(buffer);
5815  } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5816  uint8_t *buffer;
5817  size_t len = atom.size - sizeof(uuid);
5818  if (c->export_xmp) {
5819  buffer = av_mallocz(len + 1);
5820  if (!buffer) {
5821  return AVERROR(ENOMEM);
5822  }
5823  ret = avio_read(pb, buffer, len);
5824  if (ret < 0) {
5825  av_free(buffer);
5826  return ret;
5827  } else if (ret != len) {
5828  av_free(buffer);
5829  return AVERROR_INVALIDDATA;
5830  }
5831  buffer[len] = '\0';
5832  av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5833  av_free(buffer);
5834  } else {
5835  // skip all uuid atom, which makes it fast for long uuid-xmp file
5836  ret = avio_skip(pb, len);
5837  if (ret < 0)
5838  return ret;
5839  }
5840  } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5841  size_t len = atom.size - sizeof(uuid);
5842  ret = mov_parse_uuid_spherical(sc, pb, len);
5843  if (ret < 0)
5844  return ret;
5845  if (!sc->spherical)
5846  av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5847  }
5848 
5849  return 0;
5850 }
5851 
5853 {
5854  int ret;
5855  uint8_t content[16];
5856 
5857  if (atom.size < 8)
5858  return 0;
5859 
5860  ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5861  if (ret < 0)
5862  return ret;
5863 
5864  if ( !c->found_moov
5865  && !c->found_mdat
5866  && !memcmp(content, "Anevia\x1A\x1A", 8)
5869  }
5870 
5871  return 0;
5872 }
5873 
5875 {
5876  uint32_t format = avio_rl32(pb);
5877  MOVStreamContext *sc;
5878  enum AVCodecID id;
5879  AVStream *st;
5880 
5881  if (c->fc->nb_streams < 1)
5882  return 0;
5883  st = c->fc->streams[c->fc->nb_streams - 1];
5884  sc = st->priv_data;
5885 
5886  switch (sc->format)
5887  {
5888  case MKTAG('e','n','c','v'): // encrypted video
5889  case MKTAG('e','n','c','a'): // encrypted audio
5890  id = mov_codec_id(st, format);
5891  if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5892  st->codecpar->codec_id != id) {
5893  av_log(c->fc, AV_LOG_WARNING,
5894  "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5895  (char*)&format, st->codecpar->codec_id);
5896  break;
5897  }
5898 
5899  st->codecpar->codec_id = id;
5900  sc->format = format;
5901  break;
5902 
5903  default:
5904  if (format != sc->format) {
5905  av_log(c->fc, AV_LOG_WARNING,
5906  "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5907  (char*)&format, (char*)&sc->format);
5908  }
5909  break;
5910  }
5911 
5912  return 0;
5913 }
5914 
5915 /**
5916  * Gets the current encryption info and associated current stream context. If
5917  * we are parsing a track fragment, this will return the specific encryption
5918  * info for this fragment; otherwise this will return the global encryption
5919  * info for the current stream.
5920  */
5922 {
5923  MOVFragmentStreamInfo *frag_stream_info;
5924  AVStream *st;
5925  int i;
5926 
5927  frag_stream_info = get_current_frag_stream_info(&c->frag_index);
5928  if (frag_stream_info) {
5929  for (i = 0; i < c->fc->nb_streams; i++) {
5930  if (c->fc->streams[i]->id == frag_stream_info->id) {
5931  st = c->fc->streams[i];
5932  break;
5933  }
5934  }
5935  if (i == c->fc->nb_streams)
5936  return 0;
5937  *sc = st->priv_data;
5938 
5939  if (!frag_stream_info->encryption_index) {
5940  // If this stream isn't encrypted, don't create the index.
5941  if (!(*sc)->cenc.default_encrypted_sample)
5942  return 0;
5943  frag_stream_info->encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
5944  if (!frag_stream_info->encryption_index)
5945  return AVERROR(ENOMEM);
5946  }
5947  *encryption_index = frag_stream_info->encryption_index;
5948  return 1;
5949  } else {
5950  // No current track fragment, using stream level encryption info.
5951 
5952  if (c->fc->nb_streams < 1)
5953  return 0;
5954  st = c->fc->streams[c->fc->nb_streams - 1];
5955  *sc = st->priv_data;
5956 
5957  if (!(*sc)->cenc.encryption_index) {
5958  // If this stream isn't encrypted, don't create the index.
5959  if (!(*sc)->cenc.default_encrypted_sample)
5960  return 0;
5961  (*sc)->cenc.encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
5962  if (!(*sc)->cenc.encryption_index)
5963  return AVERROR(ENOMEM);
5964  }
5965 
5966  *encryption_index = (*sc)->cenc.encryption_index;
5967  return 1;
5968  }
5969 }
5970 
5972 {
5973  int i;
5974  unsigned int subsample_count;
5975  AVSubsampleEncryptionInfo *subsamples;
5976 
5977  if (!sc->cenc.default_encrypted_sample) {
5978  av_log(c->fc, AV_LOG_ERROR, "Missing schm or tenc\n");
5979  return AVERROR_INVALIDDATA;
5980  }
5981 
5983  if (!*sample)
5984  return AVERROR(ENOMEM);
5985 
5986  if (sc->cenc.per_sample_iv_size != 0) {
5987  if (avio_read(pb, (*sample)->iv, sc->cenc.per_sample_iv_size) != sc->cenc.per_sample_iv_size) {
5988  av_log(c->fc, AV_LOG_ERROR, "failed to read the initialization vector\n");
5989  av_encryption_info_free(*sample);
5990  *sample = NULL;
5991  return AVERROR_INVALIDDATA;
5992  }
5993  }
5994 
5995  if (use_subsamples) {
5996  subsample_count = avio_rb16(pb);
5997  av_free((*sample)->subsamples);
5998  (*sample)->subsamples = av_mallocz_array(subsample_count, sizeof(*subsamples));
5999  if (!(*sample)->subsamples) {
6000  av_encryption_info_free(*sample);
6001  *sample = NULL;
6002  return AVERROR(ENOMEM);
6003  }
6004 
6005  for (i = 0; i < subsample_count && !pb->eof_reached; i++) {
6006  (*sample)->subsamples[i].bytes_of_clear_data = avio_rb16(pb);
6007  (*sample)->subsamples[i].bytes_of_protected_data = avio_rb32(pb);
6008  }
6009 
6010  if (pb->eof_reached) {
6011  av_log(c->fc, AV_LOG_ERROR, "hit EOF while reading sub-sample encryption info\n");
6012  av_encryption_info_free(*sample);
6013  *sample = NULL;
6014  return AVERROR_INVALIDDATA;
6015  }
6016  (*sample)->subsample_count = subsample_count;
6017  }
6018 
6019  return 0;
6020 }
6021 
6023 {
6024  AVEncryptionInfo **encrypted_samples;
6025  MOVEncryptionIndex *encryption_index;
6026  MOVStreamContext *sc;
6027  int use_subsamples, ret;
6028  unsigned int sample_count, i, alloc_size = 0;
6029 
6030  ret = get_current_encryption_info(c, &encryption_index, &sc);
6031  if (ret != 1)
6032  return ret;
6033 
6034  if (encryption_index->nb_encrypted_samples) {
6035  // This can happen if we have both saio/saiz and senc atoms.
6036  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in senc\n");
6037  return 0;
6038  }
6039 
6040  avio_r8(pb); /* version */
6041  use_subsamples = avio_rb24(pb) & 0x02; /* flags */
6042 
6043  sample_count = avio_rb32(pb);
6044  if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
6045  return AVERROR(ENOMEM);
6046 
6047  for (i = 0; i < sample_count; i++) {
6048  unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
6049  encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
6050  min_samples * sizeof(*encrypted_samples));
6051  if (encrypted_samples) {
6052  encryption_index->encrypted_samples = encrypted_samples;
6053 
6055  c, pb, sc, &encryption_index->encrypted_samples[i], use_subsamples);
6056  } else {
6057  ret = AVERROR(ENOMEM);
6058  }
6059  if (pb->eof_reached) {
6060  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading senc\n");
6061  if (ret >= 0)
6062  av_encryption_info_free(encryption_index->encrypted_samples[i]);
6063  ret = AVERROR_INVALIDDATA;
6064  }
6065 
6066  if (ret < 0) {
6067  for (; i > 0; i--)
6068  av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
6069  av_freep(&encryption_index->encrypted_samples);
6070  return ret;
6071  }
6072  }
6073  encryption_index->nb_encrypted_samples = sample_count;
6074 
6075  return 0;
6076 }
6077 
6079 {
6080  AVEncryptionInfo **sample, **encrypted_samples;
6081  int64_t prev_pos;
6082  size_t sample_count, sample_info_size, i;
6083  int ret = 0;
6084  unsigned int alloc_size = 0;
6085 
6086  if (encryption_index->nb_encrypted_samples)
6087  return 0;
6088  sample_count = encryption_index->auxiliary_info_sample_count;
6089  if (encryption_index->auxiliary_offsets_count != 1) {
6090  av_log(c->fc, AV_LOG_ERROR, "Multiple auxiliary info chunks are not supported\n");
6091  return AVERROR_PATCHWELCOME;
6092  }
6093  if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
6094  return AVERROR(ENOMEM);
6095 
6096  prev_pos = avio_tell(pb);
6097  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
6098  avio_seek(pb, encryption_index->auxiliary_offsets[0], SEEK_SET) != encryption_index->auxiliary_offsets[0]) {
6099  av_log(c->fc, AV_LOG_INFO, "Failed to seek for auxiliary info, will only parse senc atoms for encryption info\n");
6100  goto finish;
6101  }
6102 
6103  for (i = 0; i < sample_count && !pb->eof_reached; i++) {
6104  unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
6105  encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
6106  min_samples * sizeof(*encrypted_samples));
6107  if (!encrypted_samples) {
6108  ret = AVERROR(ENOMEM);
6109  goto finish;
6110  }
6111  encryption_index->encrypted_samples = encrypted_samples;
6112 
6113  sample = &encryption_index->encrypted_samples[i];
6114  sample_info_size = encryption_index->auxiliary_info_default_size
6115  ? encryption_index->auxiliary_info_default_size
6116  : encryption_index->auxiliary_info_sizes[i];
6117 
6118  ret = mov_read_sample_encryption_info(c, pb, sc, sample, sample_info_size > sc->cenc.per_sample_iv_size);
6119  if (ret < 0)
6120  goto finish;
6121  }
6122  if (pb->eof_reached) {
6123  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading auxiliary info\n");
6124  ret = AVERROR_INVALIDDATA;
6125  } else {
6126  encryption_index->nb_encrypted_samples = sample_count;
6127  }
6128 
6129 finish:
6130  avio_seek(pb, prev_pos, SEEK_SET);
6131  if (ret < 0) {
6132  for (; i > 0; i--) {
6133  av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
6134  }
6135  av_freep(&encryption_index->encrypted_samples);
6136  }
6137  return ret;
6138 }
6139 
6140 /**
6141  * Tries to read the given number of bytes from the stream and puts it in a
6142  * newly allocated buffer. This reads in small chunks to avoid allocating large
6143  * memory if the file contains an invalid/malicious size value.
6144  */
6145 static int mov_try_read_block(AVIOContext *pb, size_t size, uint8_t **data)
6146 {
6147  const unsigned int block_size = 1024 * 1024;
6148  uint8_t *buffer = NULL;
6149  unsigned int alloc_size = 0, offset = 0;
6150  while (offset < size) {
6151  unsigned int new_size =
6152  alloc_size >= INT_MAX - block_size ? INT_MAX : alloc_size + block_size;
6153  uint8_t *new_buffer = av_fast_realloc(buffer, &alloc_size, new_size);
6154  unsigned int to_read = FFMIN(size, alloc_size) - offset;
6155  if (!new_buffer) {
6156  av_free(buffer);
6157  return AVERROR(ENOMEM);
6158  }
6159  buffer = new_buffer;
6160 
6161  if (avio_read(pb, buffer + offset, to_read) != to_read) {
6162  av_free(buffer);
6163  return AVERROR_INVALIDDATA;
6164  }
6165  offset += to_read;
6166  }
6167 
6168  *data = buffer;
6169  return 0;
6170 }
6171 
6173 {
6174  MOVEncryptionIndex *encryption_index;
6175  MOVStreamContext *sc;
6176  int ret;
6177  unsigned int sample_count, aux_info_type, aux_info_param;
6178 
6179  ret = get_current_encryption_info(c, &encryption_index, &sc);
6180  if (ret != 1)
6181  return ret;
6182 
6183  if (encryption_index->nb_encrypted_samples) {
6184  // This can happen if we have both saio/saiz and senc atoms.
6185  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saiz\n");
6186  return 0;
6187  }
6188 
6189  if (encryption_index->auxiliary_info_sample_count) {
6190  av_log(c->fc, AV_LOG_ERROR, "Duplicate saiz atom\n");
6191  return AVERROR_INVALIDDATA;
6192  }
6193 
6194  avio_r8(pb); /* version */
6195  if (avio_rb24(pb) & 0x01) { /* flags */
6196  aux_info_type = avio_rb32(pb);
6197  aux_info_param = avio_rb32(pb);
6198  if (sc->cenc.default_encrypted_sample) {
6199  if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
6200  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type\n");
6201  return 0;
6202  }
6203  if (aux_info_param != 0) {
6204  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type_parameter\n");
6205  return 0;
6206  }
6207  } else {
6208  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6209  if ((aux_info_type == MKBETAG('c','e','n','c') ||
6210  aux_info_type == MKBETAG('c','e','n','s') ||
6211  aux_info_type == MKBETAG('c','b','c','1') ||
6212  aux_info_type == MKBETAG('c','b','c','s')) &&
6213  aux_info_param == 0) {
6214  av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saiz without schm/tenc\n");
6215  return AVERROR_INVALIDDATA;
6216  } else {
6217  return 0;
6218  }
6219  }
6220  } else if (!sc->cenc.default_encrypted_sample) {
6221  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6222  return 0;
6223  }
6224 
6225  encryption_index->auxiliary_info_default_size = avio_r8(pb);
6226  sample_count = avio_rb32(pb);
6227  encryption_index->auxiliary_info_sample_count = sample_count;
6228 
6229  if (encryption_index->auxiliary_info_default_size == 0) {
6230  ret = mov_try_read_block(pb, sample_count, &encryption_index->auxiliary_info_sizes);
6231  if (ret < 0) {
6232  av_log(c->fc, AV_LOG_ERROR, "Failed to read the auxiliary info\n");
6233  return ret;
6234  }
6235  }
6236 
6237  if (encryption_index->auxiliary_offsets_count) {
6238  return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6239  }
6240 
6241  return 0;
6242 }
6243 
6245 {
6246  uint64_t *auxiliary_offsets;
6247  MOVEncryptionIndex *encryption_index;
6248  MOVStreamContext *sc;
6249  int i, ret;
6250  unsigned int version, entry_count, aux_info_type, aux_info_param;
6251  unsigned int alloc_size = 0;
6252 
6253  ret = get_current_encryption_info(c, &encryption_index, &sc);
6254  if (ret != 1)
6255  return ret;
6256 
6257  if (encryption_index->nb_encrypted_samples) {
6258  // This can happen if we have both saio/saiz and senc atoms.
6259  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saio\n");
6260  return 0;
6261  }
6262 
6263  if (encryption_index->auxiliary_offsets_count) {
6264  av_log(c->fc, AV_LOG_ERROR, "Duplicate saio atom\n");
6265  return AVERROR_INVALIDDATA;
6266  }
6267 
6268  version = avio_r8(pb); /* version */
6269  if (avio_rb24(pb) & 0x01) { /* flags */
6270  aux_info_type = avio_rb32(pb);
6271  aux_info_param = avio_rb32(pb);
6272  if (sc->cenc.default_encrypted_sample) {
6273  if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
6274  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type\n");
6275  return 0;
6276  }
6277  if (aux_info_param != 0) {
6278  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type_parameter\n");
6279  return 0;
6280  }
6281  } else {
6282  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6283  if ((aux_info_type == MKBETAG('c','e','n','c') ||
6284  aux_info_type == MKBETAG('c','e','n','s') ||
6285  aux_info_type == MKBETAG('c','b','c','1') ||
6286  aux_info_type == MKBETAG('c','b','c','s')) &&
6287  aux_info_param == 0) {
6288  av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saio without schm/tenc\n");
6289  return AVERROR_INVALIDDATA;
6290  } else {
6291  return 0;
6292  }
6293  }
6294  } else if (!sc->cenc.default_encrypted_sample) {
6295  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6296  return 0;
6297  }
6298 
6299  entry_count = avio_rb32(pb);
6300  if (entry_count >= INT_MAX / sizeof(*auxiliary_offsets))
6301  return AVERROR(ENOMEM);
6302 
6303  for (i = 0; i < entry_count && !pb->eof_reached; i++) {
6304  unsigned int min_offsets = FFMIN(FFMAX(i + 1, 1024), entry_count);
6305  auxiliary_offsets = av_fast_realloc(
6306  encryption_index->auxiliary_offsets, &alloc_size,
6307  min_offsets * sizeof(*auxiliary_offsets));
6308  if (!auxiliary_offsets) {
6309  av_freep(&encryption_index->auxiliary_offsets);
6310  return AVERROR(ENOMEM);
6311  }
6312  encryption_index->auxiliary_offsets = auxiliary_offsets;
6313 
6314  if (version == 0) {
6315  encryption_index->auxiliary_offsets[i] = avio_rb32(pb);
6316  } else {
6317  encryption_index->auxiliary_offsets[i] = avio_rb64(pb);
6318  }
6319  if (c->frag_index.current >= 0) {
6320  encryption_index->auxiliary_offsets[i] += c->fragment.base_data_offset;
6321  }
6322  }
6323 
6324  if (pb->eof_reached) {
6325  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading saio\n");
6326  av_freep(&encryption_index->auxiliary_offsets);
6327  return AVERROR_INVALIDDATA;
6328  }
6329 
6330  encryption_index->auxiliary_offsets_count = entry_count;
6331 
6332  if (encryption_index->auxiliary_info_sample_count) {
6333  return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6334  }
6335 
6336  return 0;
6337 }
6338 
6340 {
6341  AVEncryptionInitInfo *info, *old_init_info;
6342  uint8_t **key_ids;
6343  AVStream *st;
6344  uint8_t *side_data, *extra_data, *old_side_data;
6345  size_t side_data_size;
6346  int ret = 0, old_side_data_size;
6347  unsigned int version, kid_count, extra_data_size, alloc_size = 0;
6348 
6349  if (c->fc->nb_streams < 1)
6350  return 0;
6351  st = c->fc->streams[c->fc->nb_streams-1];
6352 
6353  version = avio_r8(pb); /* version */
6354  avio_rb24(pb); /* flags */
6355 
6356  info = av_encryption_init_info_alloc(/* system_id_size */ 16, /* num_key_ids */ 0,
6357  /* key_id_size */ 16, /* data_size */ 0);
6358  if (!info)
6359  return AVERROR(ENOMEM);
6360 
6361  if (avio_read(pb, info->system_id, 16) != 16) {
6362  av_log(c->fc, AV_LOG_ERROR, "Failed to read the system id\n");
6363  ret = AVERROR_INVALIDDATA;
6364  goto finish;
6365  }
6366 
6367  if (version > 0) {
6368  kid_count = avio_rb32(pb);
6369  if (kid_count >= INT_MAX / sizeof(*key_ids)) {
6370  ret = AVERROR(ENOMEM);
6371  goto finish;
6372  }
6373 
6374  for (unsigned int i = 0; i < kid_count && !pb->eof_reached; i++) {
6375  unsigned int min_kid_count = FFMIN(FFMAX(i + 1, 1024), kid_count);
6376  key_ids = av_fast_realloc(info->key_ids, &alloc_size,
6377  min_kid_count * sizeof(*key_ids));
6378  if (!key_ids) {
6379  ret = AVERROR(ENOMEM);
6380  goto finish;
6381  }
6382  info->key_ids = key_ids;
6383 
6384  info->key_ids[i] = av_mallocz(16);
6385  if (!info->key_ids[i]) {
6386  ret = AVERROR(ENOMEM);
6387  goto finish;
6388  }
6389  info->num_key_ids = i + 1;
6390 
6391  if (avio_read(pb, info->key_ids[i], 16) != 16) {
6392  av_log(c->fc, AV_LOG_ERROR, "Failed to read the key id\n");
6393  ret = AVERROR_INVALIDDATA;
6394  goto finish;
6395  }
6396  }
6397 
6398  if (pb->eof_reached) {
6399  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading pssh\n");
6400  ret = AVERROR_INVALIDDATA;
6401  goto finish;
6402  }
6403  }
6404 
6405  extra_data_size = avio_rb32(pb);
6406  ret = mov_try_read_block(pb, extra_data_size, &extra_data);
6407  if (ret < 0)
6408  goto finish;
6409 
6410  av_freep(&info->data); // malloc(0) may still allocate something.
6411  info->data = extra_data;
6412  info->data_size = extra_data_size;
6413 
6414  // If there is existing initialization data, append to the list.
6415  old_side_data = av_stream_get_side_data(st, AV_PKT_DATA_ENCRYPTION_INIT_INFO, &old_side_data_size);
6416  if (old_side_data) {
6417  old_init_info = av_encryption_init_info_get_side_data(old_side_data, old_side_data_size);
6418  if (old_init_info) {
6419  // Append to the end of the list.
6420  for (AVEncryptionInitInfo *cur = old_init_info;; cur = cur->next) {
6421  if (!cur->next) {
6422  cur->next = info;
6423  break;
6424  }
6425  }
6426  info = old_init_info;
6427  } else {
6428  // Assume existing side-data will be valid, so the only error we could get is OOM.
6429  ret = AVERROR(ENOMEM);
6430  goto finish;
6431  }
6432  }
6433 
6434  side_data = av_encryption_init_info_add_side_data(info, &side_data_size);
6435  if (!side_data) {
6436  ret = AVERROR(ENOMEM);
6437  goto finish;
6438  }
6440  side_data, side_data_size);
6441  if (ret < 0)
6442  av_free(side_data);
6443 
6444 finish:
6446  return ret;
6447 }
6448 
6450 {
6451  AVStream *st;
6452  MOVStreamContext *sc;
6453 
6454  if (c->fc->nb_streams < 1)
6455  return 0;
6456  st = c->fc->streams[c->fc->nb_streams-1];
6457  sc = st->priv_data;
6458 
6459  if (sc->pseudo_stream_id != 0) {
6460  av_log(c->fc, AV_LOG_ERROR, "schm boxes are only supported in first sample descriptor\n");
6461  return AVERROR_PATCHWELCOME;
6462  }
6463 
6464  if (atom.size < 8)
6465  return AVERROR_INVALIDDATA;
6466 
6467  avio_rb32(pb); /* version and flags */
6468 
6469  if (!sc->cenc.default_encrypted_sample) {
6471  if (!sc->cenc.default_encrypted_sample) {
6472  return AVERROR(ENOMEM);
6473  }
6474  }
6475 
6477  return 0;
6478 }
6479 
6481 {
6482  AVStream *st;
6483  MOVStreamContext *sc;
6484  unsigned int version, pattern, is_protected, iv_size;
6485 
6486  if (c->fc->nb_streams < 1)
6487  return 0;
6488  st = c->fc->streams[c->fc->nb_streams-1];
6489  sc = st->priv_data;
6490 
6491  if (sc->pseudo_stream_id != 0) {
6492  av_log(c->fc, AV_LOG_ERROR, "tenc atom are only supported in first sample descriptor\n");
6493  return AVERROR_PATCHWELCOME;
6494  }
6495 
6496  if (!sc->cenc.default_encrypted_sample) {
6498  if (!sc->cenc.default_encrypted_sample) {
6499  return AVERROR(ENOMEM);
6500  }
6501  }
6502 
6503  if (atom.size < 20)
6504  return AVERROR_INVALIDDATA;
6505 
6506  version = avio_r8(pb); /* version */
6507  avio_rb24(pb); /* flags */
6508 
6509  avio_r8(pb); /* reserved */
6510  pattern = avio_r8(pb);
6511 
6512  if (version > 0) {
6513  sc->cenc.default_encrypted_sample->crypt_byte_block = pattern >> 4;
6514  sc->cenc.default_encrypted_sample->skip_byte_block = pattern & 0xf;
6515  }
6516 
6517  is_protected = avio_r8(pb);
6518  if (is_protected && !sc->cenc.encryption_index) {
6519  // The whole stream should be by-default encrypted.
6521  if (!sc->cenc.encryption_index)
6522  return AVERROR(ENOMEM);
6523  }
6524  sc->cenc.per_sample_iv_size = avio_r8(pb);
6525  if (sc->cenc.per_sample_iv_size != 0 && sc->cenc.per_sample_iv_size != 8 &&
6526  sc->cenc.per_sample_iv_size != 16) {
6527  av_log(c->fc, AV_LOG_ERROR, "invalid per-sample IV size value\n");
6528  return AVERROR_INVALIDDATA;
6529  }
6530  if (avio_read(pb, sc->cenc.default_encrypted_sample->key_id, 16) != 16) {
6531  av_log(c->fc, AV_LOG_ERROR, "failed to read the default key ID\n");
6532  return AVERROR_INVALIDDATA;
6533  }
6534 
6535  if (is_protected && !sc->cenc.per_sample_iv_size) {
6536  iv_size = avio_r8(pb);
6537  if (iv_size != 8 && iv_size != 16) {
6538  av_log(c->fc, AV_LOG_ERROR, "invalid default_constant_IV_size in tenc atom\n");
6539  return AVERROR_INVALIDDATA;
6540  }
6541 
6542  if (avio_read(pb, sc->cenc.default_encrypted_sample->iv, iv_size) != iv_size) {
6543  av_log(c->fc, AV_LOG_ERROR, "failed to read the default IV\n");
6544  return AVERROR_INVALIDDATA;
6545  }
6546  }
6547 
6548  return 0;
6549 }
6550 
6552 {
6553  AVStream *st;
6554  int last, type, size, ret;
6555  uint8_t buf[4];
6556 
6557  if (c->fc->nb_streams < 1)
6558  return 0;
6559  st = c->fc->streams[c->fc->nb_streams-1];
6560 
6561  if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
6562  return AVERROR_INVALIDDATA;
6563 
6564  /* Check FlacSpecificBox version. */
6565  if (avio_r8(pb) != 0)
6566  return AVERROR_INVALIDDATA;
6567 
6568  avio_rb24(pb); /* Flags */
6569 
6570  avio_read(pb, buf, sizeof(buf));
6571  flac_parse_block_header(buf, &last, &type, &size);
6572 
6573  if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
6574  av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
6575  return AVERROR_INVALIDDATA;
6576  }
6577 
6578  ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
6579  if (ret < 0)
6580  return ret;
6581 
6582  if (!last)
6583  av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
6584 
6585  return 0;
6586 }
6587 
6589 {
6590  int i, ret;
6591 
6592  if (sample->scheme != MKBETAG('c','e','n','c') || sample->crypt_byte_block != 0 || sample->skip_byte_block != 0) {
6593  av_log(c->fc, AV_LOG_ERROR, "Only the 'cenc' encryption scheme is supported\n");
6594  return AVERROR_PATCHWELCOME;
6595  }
6596 
6597  if (!sc->cenc.aes_ctr) {
6598  /* initialize the cipher */
6599  sc->cenc.aes_ctr = av_aes_ctr_alloc();
6600  if (!sc->cenc.aes_ctr) {
6601  return AVERROR(ENOMEM);
6602  }
6603 
6604  ret = av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
6605  if (ret < 0) {
6606  return ret;
6607  }
6608  }
6609 
6610  av_aes_ctr_set_full_iv(sc->cenc.aes_ctr, sample->iv);
6611 
6612  if (!sample->subsample_count)
6613  {
6614  /* decrypt the whole packet */
6615  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
6616  return 0;
6617  }
6618 
6619  for (i = 0; i < sample->subsample_count; i++)
6620  {
6621  if (sample->subsamples[i].bytes_of_clear_data + sample->subsamples[i].bytes_of_protected_data > size) {
6622  av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
6623  return AVERROR_INVALIDDATA;
6624  }
6625 
6626  /* skip the clear bytes */
6627  input += sample->subsamples[i].bytes_of_clear_data;
6628  size -= sample->subsamples[i].bytes_of_clear_data;
6629 
6630  /* decrypt the encrypted bytes */
6631  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, sample->subsamples[i].bytes_of_protected_data);
6632  input += sample->subsamples[i].bytes_of_protected_data;
6633  size -= sample->subsamples[i].bytes_of_protected_data;
6634  }
6635 
6636  if (size > 0) {
6637  av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
6638  return AVERROR_INVALIDDATA;
6639  }
6640 
6641  return 0;
6642 }
6643 
6644 static int cenc_filter(MOVContext *mov, AVStream* st, MOVStreamContext *sc, AVPacket *pkt, int current_index)
6645 {
6646  MOVFragmentStreamInfo *frag_stream_info;
6647  MOVEncryptionIndex *encryption_index;
6648  AVEncryptionInfo *encrypted_sample;
6649  int encrypted_index, ret;
6650 
6651  frag_stream_info = get_frag_stream_info(&mov->frag_index, mov->frag_index.current, st->id);
6652  encrypted_index = current_index;
6653  encryption_index = NULL;
6654  if (frag_stream_info) {
6655  // Note this only supports encryption info in the first sample descriptor.
6656  if (mov->fragment.stsd_id == 1) {
6657  if (frag_stream_info->encryption_index) {
6658  encrypted_index = current_index - frag_stream_info->index_entry;
6659  encryption_index = frag_stream_info->encryption_index;
6660  } else {
6661  encryption_index = sc->cenc.encryption_index;
6662  }
6663  }
6664  } else {
6665  encryption_index = sc->cenc.encryption_index;
6666  }
6667 
6668  if (encryption_index) {
6669  if (encryption_index->auxiliary_info_sample_count &&
6670  !encryption_index->nb_encrypted_samples) {
6671  av_log(mov->fc, AV_LOG_ERROR, "saiz atom found without saio\n");
6672  return AVERROR_INVALIDDATA;
6673  }
6674  if (encryption_index->auxiliary_offsets_count &&
6675  !encryption_index->nb_encrypted_samples) {
6676  av_log(mov->fc, AV_LOG_ERROR, "saio atom found without saiz\n");
6677  return AVERROR_INVALIDDATA;
6678  }
6679 
6680  if (!encryption_index->nb_encrypted_samples) {
6681  // Full-sample encryption with default settings.
6682  encrypted_sample = sc->cenc.default_encrypted_sample;
6683  } else if (encrypted_index >= 0 && encrypted_index < encryption_index->nb_encrypted_samples) {
6684  // Per-sample setting override.
6685  encrypted_sample = encryption_index->encrypted_samples[encrypted_index];
6686  } else {
6687  av_log(mov->fc, AV_LOG_ERROR, "Incorrect number of samples in encryption info\n");
6688  return AVERROR_INVALIDDATA;
6689  }
6690 
6691  if (mov->decryption_key) {
6692  return cenc_decrypt(mov, sc, encrypted_sample, pkt->data, pkt->size);
6693  } else {
6694  size_t size;
6695  uint8_t *side_data = av_encryption_info_add_side_data(encrypted_sample, &size);
6696  if (!side_data)
6697  return AVERROR(ENOMEM);
6698  ret = av_packet_add_side_data(pkt, AV_PKT_DATA_ENCRYPTION_INFO, side_data, size);
6699  if (ret < 0)
6700  av_free(side_data);
6701  return ret;
6702  }
6703  }
6704 
6705  return 0;
6706 }
6707 
6709 {
6710  const int OPUS_SEEK_PREROLL_MS = 80;
6711  AVStream *st;
6712  size_t size;
6713  uint16_t pre_skip;
6714 
6715  if (c->fc->nb_streams < 1)
6716  return 0;
6717  st = c->fc->streams[c->fc->nb_streams-1];
6718 
6719  if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6720  return AVERROR_INVALIDDATA;
6721 
6722  /* Check OpusSpecificBox version. */
6723  if (avio_r8(pb) != 0) {
6724  av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6725  return AVERROR_INVALIDDATA;
6726  }
6727 
6728  /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6729  size = atom.size + 8;
6730 
6731  if (ff_alloc_extradata(st->codecpar, size))
6732  return AVERROR(ENOMEM);
6733 
6734  AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6735  AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6736  AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6737  avio_read(pb, st->codecpar->extradata + 9, size - 9);
6738 
6739  /* OpusSpecificBox is stored in big-endian, but OpusHead is
6740  little-endian; aside from the preceeding magic and version they're
6741  otherwise currently identical. Data after output gain at offset 16
6742  doesn't need to be bytewapped. */
6743  pre_skip = AV_RB16(st->codecpar->extradata + 10);
6744  AV_WL16(st->codecpar->extradata + 10, pre_skip);
6745  AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6746  AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6747 
6748  st->codecpar->initial_padding = pre_skip;
6749  st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6750  (AVRational){1, 1000},
6751  (AVRational){1, 48000});
6752 
6753  return 0;
6754 }
6755 
6757 { MKTAG('A','C','L','R'), mov_read_aclr },
6758 { MKTAG('A','P','R','G'), mov_read_avid },
6759 { MKTAG('A','A','L','P'), mov_read_avid },
6760 { MKTAG('A','R','E','S'), mov_read_ares },
6761 { MKTAG('a','v','s','s'), mov_read_avss },
6762 { MKTAG('a','v','1','C'), mov_read_av1c },
6763 { MKTAG('c','h','p','l'), mov_read_chpl },
6764 { MKTAG('c','o','6','4'), mov_read_stco },
6765 { MKTAG('c','o','l','r'), mov_read_colr },
6766 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6767 { MKTAG('d','i','n','f'), mov_read_default },
6768 { MKTAG('D','p','x','E'), mov_read_dpxe },
6769 { MKTAG('d','r','e','f'), mov_read_dref },
6770 { MKTAG('e','d','t','s'), mov_read_default },
6771 { MKTAG('e','l','s','t'), mov_read_elst },
6772 { MKTAG('e','n','d','a'), mov_read_enda },
6773 { MKTAG('f','i','e','l'), mov_read_fiel },
6774 { MKTAG('a','d','r','m'), mov_read_adrm },
6775 { MKTAG('f','t','y','p'), mov_read_ftyp },
6776 { MKTAG('g','l','b','l'), mov_read_glbl },
6777 { MKTAG('h','d','l','r'), mov_read_hdlr },
6778 { MKTAG('i','l','s','t'), mov_read_ilst },
6779 { MKTAG('j','p','2','h'), mov_read_jp2h },
6780 { MKTAG('m','d','a','t'), mov_read_mdat },
6781 { MKTAG('m','d','h','d'), mov_read_mdhd },
6782 { MKTAG('m','d','i','a'), mov_read_default },
6783 { MKTAG('m','e','t','a'), mov_read_meta },
6784 { MKTAG('m','i','n','f'), mov_read_default },
6785 { MKTAG('m','o','o','f'), mov_read_moof },
6786 { MKTAG('m','o','o','v'), mov_read_moov },
6787 { MKTAG('m','v','e','x'), mov_read_default },
6788 { MKTAG('m','v','h','d'), mov_read_mvhd },
6789 { MKTAG('S','M','I',' '), mov_read_svq3 },
6790 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6791 { MKTAG('a','v','c','C'), mov_read_glbl },
6792 { MKTAG('p','a','s','p'), mov_read_pasp },
6793 { MKTAG('s','i','d','x'), mov_read_sidx },
6794 { MKTAG('s','t','b','l'), mov_read_default },
6795 { MKTAG('s','t','c','o'), mov_read_stco },
6796 { MKTAG('s','t','p','s'), mov_read_stps },
6797 { MKTAG('s','t','r','f'), mov_read_strf },
6798 { MKTAG('s','t','s','c'), mov_read_stsc },
6799 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6800 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6801 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6802 { MKTAG('s','t','t','s'), mov_read_stts },
6803 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6804 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6805 { MKTAG('t','f','d','t'), mov_read_tfdt },
6806 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6807 { MKTAG('t','r','a','k'), mov_read_trak },
6808 { MKTAG('t','r','a','f'), mov_read_default },
6809 { MKTAG('t','r','e','f'), mov_read_default },
6810 { MKTAG('t','m','c','d'), mov_read_tmcd },
6811 { MKTAG('c','h','a','p'), mov_read_chap },
6812 { MKTAG('t','r','e','x'), mov_read_trex },
6813 { MKTAG('t','r','u','n'), mov_read_trun },
6814 { MKTAG('u','d','t','a'), mov_read_default },
6815 { MKTAG('w','a','v','e'), mov_read_wave },
6816 { MKTAG('e','s','d','s'), mov_read_esds },
6817 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6818 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6819 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6820 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6821 { MKTAG('w','f','e','x'), mov_read_wfex },
6822 { MKTAG('c','m','o','v'), mov_read_cmov },
6823 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6824 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6825 { MKTAG('s','b','g','p'), mov_read_sbgp },
6826 { MKTAG('h','v','c','C'), mov_read_glbl },
6827 { MKTAG('u','u','i','d'), mov_read_uuid },
6828 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6829 { MKTAG('f','r','e','e'), mov_read_free },
6830 { MKTAG('-','-','-','-'), mov_read_custom },
6831 { MKTAG('s','i','n','f'), mov_read_default },
6832 { MKTAG('f','r','m','a'), mov_read_frma },
6833 { MKTAG('s','e','n','c'), mov_read_senc },
6834 { MKTAG('s','a','i','z'), mov_read_saiz },
6835 { MKTAG('s','a','i','o'), mov_read_saio },
6836 { MKTAG('p','s','s','h'), mov_read_pssh },
6837 { MKTAG('s','c','h','m'), mov_read_schm },
6838 { MKTAG('s','c','h','i'), mov_read_default },
6839 { MKTAG('t','e','n','c'), mov_read_tenc },
6840 { MKTAG('d','f','L','a'), mov_read_dfla },
6841 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6842 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6843 { MKTAG('d','O','p','s'), mov_read_dops },
6844 { MKTAG('S','m','D','m'), mov_read_smdm },
6845 { MKTAG('C','o','L','L'), mov_read_coll },
6846 { MKTAG('v','p','c','C'), mov_read_vpcc },
6847 { MKTAG('m','d','c','v'), mov_read_mdcv },
6848 { MKTAG('c','l','l','i'), mov_read_clli },
6849 { 0, NULL }
6850 };
6851 
6853 {
6854  int64_t total_size = 0;
6855  MOVAtom a;
6856  int i;
6857 
6858  if (c->atom_depth > 10) {
6859  av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6860  return AVERROR_INVALIDDATA;
6861  }
6862  c->atom_depth ++;
6863 
6864  if (atom.size < 0)
6865  atom.size = INT64_MAX;
6866  while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6868  a.size = atom.size;
6869  a.type=0;
6870  if (atom.size >= 8) {
6871  a.size = avio_rb32(pb);
6872  a.type = avio_rl32(pb);
6873  if (a.type == MKTAG('f','r','e','e') &&
6874  a.size >= 8 &&
6876  c->moov_retry) {
6877  uint32_t type;
6878  avio_skip(pb, 4);
6879  type = avio_rl32(pb);
6880  if (avio_feof(pb))
6881  break;
6882  avio_seek(pb, -8, SEEK_CUR);
6883  if (type == MKTAG('m','v','h','d') ||
6884  type == MKTAG('c','m','o','v')) {
6885  av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6886  a.type = MKTAG('m','o','o','v');
6887  }
6888  }
6889  if (atom.type != MKTAG('r','o','o','t') &&
6890  atom.type != MKTAG('m','o','o','v'))
6891  {
6892  if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6893  {
6894  av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6895  avio_skip(pb, -8);
6896  c->atom_depth --;
6897  return 0;
6898  }
6899  }
6900  total_size += 8;
6901  if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6902  a.size = avio_rb64(pb) - 8;
6903  total_size += 8;
6904  }
6905  }
6906  av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6907  av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6908  if (a.size == 0) {
6909  a.size = atom.size - total_size + 8;
6910  }
6911  if (a.size < 0)
6912  break;
6913  a.size -= 8;
6914  if (a.size < 0)
6915  break;
6916  a.size = FFMIN(a.size, atom.size - total_size);
6917 
6918  for (i = 0; mov_default_parse_table[i].type; i++)
6919  if (mov_default_parse_table[i].type == a.type) {
6920  parse = mov_default_parse_table[i].parse;
6921  break;
6922  }
6923 
6924  // container is user data
6925  if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6926  atom.type == MKTAG('i','l','s','t')))
6928 
6929  // Supports parsing the QuickTime Metadata Keys.
6930  // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6931  if (!parse && c->found_hdlr_mdta &&
6932  atom.type == MKTAG('m','e','t','a') &&
6933  a.type == MKTAG('k','e','y','s')) {
6934  parse = mov_read_keys;
6935  }
6936 
6937  if (!parse) { /* skip leaf atoms data */
6938  avio_skip(pb, a.size);
6939  } else {
6940  int64_t start_pos = avio_tell(pb);
6941  int64_t left;
6942  int err = parse(c, pb, a);
6943  if (err < 0) {
6944  c->atom_depth --;
6945  return err;
6946  }
6947  if (c->found_moov && c->found_mdat && a.size <= INT64_MAX - start_pos &&
6949  start_pos + a.size == avio_size(pb))) {
6951  c->next_root_atom = start_pos + a.size;
6952  c->atom_depth --;
6953  return 0;
6954  }
6955  left = a.size - avio_tell(pb) + start_pos;
6956  if (left > 0) /* skip garbage at atom end */
6957  avio_skip(pb, left);
6958  else if (left < 0) {
6959  av_log(c->fc, AV_LOG_WARNING,
6960  "overread end of atom '%.4s' by %"PRId64" bytes\n",
6961  (char*)&a.type, -left);
6962  avio_seek(pb, left, SEEK_CUR);
6963  }
6964  }
6965 
6966  total_size += a.size;
6967  }
6968 
6969  if (total_size < atom.size && atom.size < 0x7ffff)
6970  avio_skip(pb, atom.size - total_size);
6971 
6972  c->atom_depth --;
6973  return 0;
6974 }
6975 
6976 static int mov_probe(AVProbeData *p)
6977 {
6978  int64_t offset;
6979  uint32_t tag;
6980  int score = 0;
6981  int moov_offset = -1;
6982 
6983  /* check file header */
6984  offset = 0;
6985  for (;;) {
6986  /* ignore invalid offset */
6987  if ((offset + 8) > (unsigned int)p->buf_size)
6988  break;
6989  tag = AV_RL32(p->buf + offset + 4);
6990  switch(tag) {
6991  /* check for obvious tags */
6992  case MKTAG('m','o','o','v'):
6993  moov_offset = offset + 4;
6994  case MKTAG('m','d','a','t'):
6995  case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6996  case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6997  case MKTAG('f','t','y','p'):
6998  if (AV_RB32(p->buf+offset) < 8 &&
6999  (AV_RB32(p->buf+offset) != 1 ||
7000  offset + 12 > (unsigned int)p->buf_size ||
7001  AV_RB64(p->buf+offset + 8) == 0)) {
7002  score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
7003  } else if (tag == MKTAG('f','t','y','p') &&
7004  ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
7005  || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
7006  )) {
7007  score = FFMAX(score, 5);
7008  } else {
7009  score = AVPROBE_SCORE_MAX;
7010  }
7011  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
7012  break;
7013  /* those are more common words, so rate then a bit less */
7014  case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
7015  case MKTAG('w','i','d','e'):
7016  case MKTAG('f','r','e','e'):
7017  case MKTAG('j','u','n','k'):
7018  case MKTAG('p','i','c','t'):
7019  score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
7020  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
7021  break;
7022  case MKTAG(0x82,0x82,0x7f,0x7d):
7023  case MKTAG('s','k','i','p'):
7024  case MKTAG('u','u','i','d'):
7025  case MKTAG('p','r','f','l'):
7026  /* if we only find those cause probedata is too small at least rate them */
7027  score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
7028  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
7029  break;
7030  default:
7031  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
7032  }
7033  }
7034  if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
7035  /* moov atom in the header - we should make sure that this is not a
7036  * MOV-packed MPEG-PS */
7037  offset = moov_offset;
7038 
7039  while(offset < (p->buf_size - 16)){ /* Sufficient space */
7040  /* We found an actual hdlr atom */
7041  if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
7042  AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
7043  AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
7044  av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
7045  /* We found a media handler reference atom describing an
7046  * MPEG-PS-in-MOV, return a
7047  * low score to force expanding the probe window until
7048  * mpegps_probe finds what it needs */
7049  return 5;
7050  }else
7051  /* Keep looking */
7052  offset+=2;
7053  }
7054  }
7055 
7056  return score;
7057 }
7058 
7059 // must be done after parsing all trak because there's no order requirement
7061 {
7062  MOVContext *mov = s->priv_data;
7063  AVStream *st;
7064  MOVStreamContext *sc;
7065  int64_t cur_pos;
7066  int i, j;
7067  int chapter_track;
7068 
7069  for (j = 0; j < mov->nb_chapter_tracks; j++) {
7070  chapter_track = mov->chapter_tracks[j];
7071  st = NULL;
7072  for (i = 0; i < s->nb_streams; i++)
7073  if (s->streams[i]->id == chapter_track) {
7074  st = s->streams[i];
7075  break;
7076  }
7077  if (!st) {
7078  av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
7079  continue;
7080  }
7081 
7082  sc = st->priv_data;
7083  cur_pos = avio_tell(sc->pb);
7084 
7085  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
7087  if (st->nb_index_entries) {
7088  // Retrieve the first frame, if possible
7089  AVPacket pkt;
7090  AVIndexEntry *sample = &st->index_entries[0];
7091  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7092  av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
7093  goto finish;
7094  }
7095 
7096  if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
7097  goto finish;
7098 
7099  st->attached_pic = pkt;
7100  st->attached_pic.stream_index = st->index;
7102  }
7103  } else {
7106  st->discard = AVDISCARD_ALL;
7107  for (i = 0; i < st->nb_index_entries; i++) {
7109  int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
7110  uint8_t *title;
7111  uint16_t ch;
7112  int len, title_len;
7113 
7114  if (end < sample->timestamp) {
7115  av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
7116  end = AV_NOPTS_VALUE;
7117  }
7118 
7119  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7120  av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
7121  goto finish;
7122  }
7123 
7124  // the first two bytes are the length of the title
7125  len = avio_rb16(sc->pb);
7126  if (len > sample->size-2)
7127  continue;
7128  title_len = 2*len + 1;
7129  if (!(title = av_mallocz(title_len)))
7130  goto finish;
7131 
7132  // The samples could theoretically be in any encoding if there's an encd
7133  // atom following, but in practice are only utf-8 or utf-16, distinguished
7134  // instead by the presence of a BOM
7135  if (!len) {
7136  title[0] = 0;
7137  } else {
7138  ch = avio_rb16(sc->pb);
7139  if (ch == 0xfeff)
7140  avio_get_str16be(sc->pb, len, title, title_len);
7141  else if (ch == 0xfffe)
7142  avio_get_str16le(sc->pb, len, title, title_len);
7143  else {
7144  AV_WB16(title, ch);
7145  if (len == 1 || len == 2)
7146  title[len] = 0;
7147  else
7148  avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
7149  }
7150  }
7151 
7152  avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
7153  av_freep(&title);
7154  }
7155  }
7156 finish:
7157  avio_seek(sc->pb, cur_pos, SEEK_SET);
7158  }
7159 }
7160 
7162  uint32_t value, int flags)
7163 {
7164  AVTimecode tc;
7165  char buf[AV_TIMECODE_STR_SIZE];
7166  AVRational rate = st->avg_frame_rate;
7167  int ret = av_timecode_init(&tc, rate, flags, 0, s);
7168  if (ret < 0)
7169  return ret;
7170  av_dict_set(&st->metadata, "timecode",
7171  av_timecode_make_string(&tc, buf, value), 0);
7172  return 0;
7173 }
7174 
7176 {
7177  MOVStreamContext *sc = st->priv_data;
7178  char buf[AV_TIMECODE_STR_SIZE];
7179  int64_t cur_pos = avio_tell(sc->pb);
7180  int hh, mm, ss, ff, drop;
7181 
7182  if (!st->nb_index_entries)
7183  return -1;
7184 
7185  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
7186  avio_skip(s->pb, 13);
7187  hh = avio_r8(s->pb);
7188  mm = avio_r8(s->pb);
7189  ss = avio_r8(s->pb);
7190  drop = avio_r8(s->pb);
7191  ff = avio_r8(s->pb);
7192  snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
7193  hh, mm, ss, drop ? ';' : ':', ff);
7194  av_dict_set(&st->metadata, "timecode", buf, 0);
7195 
7196  avio_seek(sc->pb, cur_pos, SEEK_SET);
7197  return 0;
7198 }
7199 
7201 {
7202  MOVStreamContext *sc = st->priv_data;
7203  int flags = 0;
7204  int64_t cur_pos = avio_tell(sc->pb);
7205  uint32_t value;
7206 
7207  if (!st->nb_index_entries)
7208  return -1;
7209 
7210  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
7211  value = avio_rb32(s->pb);
7212 
7213  if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
7214  if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
7215  if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
7216 
7217  /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
7218  * not the case) and thus assume "frame number format" instead of QT one.
7219  * No sample with tmcd track can be found with a QT timecode at the moment,
7220  * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
7221  * format). */
7222  parse_timecode_in_framenum_format(s, st, value, flags);
7223 
7224  avio_seek(sc->pb, cur_pos, SEEK_SET);
7225  return 0;
7226 }
7227 
7229  int i;
7230  if (!index || !*index) return;
7231  for (i = 0; i < (*index)->nb_encrypted_samples; i++) {
7232  av_encryption_info_free((*index)->encrypted_samples[i]);
7233  }
7234  av_freep(&(*index)->encrypted_samples);
7235  av_freep(&(*index)->auxiliary_info_sizes);
7236  av_freep(&(*index)->auxiliary_offsets);
7237  av_freep(index);
7238 }
7239 
7241 {
7242  MOVContext *mov = s->priv_data;
7243  int i, j;
7244 
7245  for (i = 0; i < s->nb_streams; i++) {
7246  AVStream *st = s->streams[i];
7247  MOVStreamContext *sc = st->priv_data;
7248 
7249  if (!sc)
7250  continue;
7251 
7252  av_freep(&sc->ctts_data);
7253  for (j = 0; j < sc->drefs_count; j++) {
7254  av_freep(&sc->drefs[j].path);
7255  av_freep(&sc->drefs[j].dir);
7256  }
7257  av_freep(&sc->drefs);
7258 
7259  sc->drefs_count = 0;
7260 
7261  if (!sc->pb_is_copied)
7262  ff_format_io_close(s, &sc->pb);
7263 
7264  sc->pb = NULL;
7265  av_freep(&sc->chunk_offsets);
7266  av_freep(&sc->stsc_data);
7267  av_freep(&sc->sample_sizes);
7268  av_freep(&sc->keyframes);
7269  av_freep(&sc->stts_data);
7270  av_freep(&sc->stps_data);
7271  av_freep(&sc->elst_data);
7272  av_freep(&sc->rap_group);
7273  av_freep(&sc->display_matrix);
7274  av_freep(&sc->index_ranges);
7275 
7276  if (sc->extradata)
7277  for (j = 0; j < sc->stsd_count; j++)
7278  av_free(sc->extradata[j]);
7279  av_freep(&sc->extradata);
7280  av_freep(&sc->extradata_size);
7281 
7285 
7286  av_freep(&sc->stereo3d);
7287  av_freep(&sc->spherical);
7288  av_freep(&sc->mastering);
7289  av_freep(&sc->coll);
7290  }
7291 
7292  av_freep(&mov->dv_demux);
7294  mov->dv_fctx = NULL;
7295 
7296  if (mov->meta_keys) {
7297  for (i = 1; i < mov->meta_keys_count; i++) {
7298  av_freep(&mov->meta_keys[i]);
7299  }
7300  av_freep(&mov->meta_keys);
7301  }
7302 
7303  av_freep(&mov->trex_data);
7304  av_freep(&mov->bitrates);
7305 
7306  for (i = 0; i < mov->frag_index.nb_items; i++) {
7308  for (j = 0; j < mov->frag_index.item[i].nb_stream_info; j++) {
7309  mov_free_encryption_index(&frag[j].encryption_index);
7310  }
7311  av_freep(&mov->frag_index.item[i].stream_info);
7312  }
7313  av_freep(&mov->frag_index.item);
7314 
7315  av_freep(&mov->aes_decrypt);
7316  av_freep(&mov->chapter_tracks);
7317 
7318  return 0;
7319 }
7320 
7321 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
7322 {
7323  int i;
7324 
7325  for (i = 0; i < s->nb_streams; i++) {
7326  AVStream *st = s->streams[i];
7327  MOVStreamContext *sc = st->priv_data;
7328 
7329  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
7330  sc->timecode_track == tmcd_id)
7331  return 1;
7332  }
7333  return 0;
7334 }
7335 
7336 /* look for a tmcd track not referenced by any video track, and export it globally */
7338 {
7339  int i;
7340 
7341  for (i = 0; i < s->nb_streams; i++) {
7342  AVStream *st = s->streams[i];
7343 
7344  if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
7345  !tmcd_is_referenced(s, i + 1)) {
7346  AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
7347  if (tcr) {
7348  av_dict_set(&s->metadata, "timecode", tcr->value, 0);
7349  break;
7350  }
7351  }
7352  }
7353 }
7354 
7355 static int read_tfra(MOVContext *mov, AVIOContext *f)
7356 {
7357  int version, fieldlength, i, j;
7358  int64_t pos = avio_tell(f);
7359  uint32_t size = avio_rb32(f);
7360  unsigned track_id, item_count;
7361 
7362  if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
7363  return 1;
7364  }
7365  av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
7366 
7367  version = avio_r8(f);
7368  avio_rb24(f);
7369  track_id = avio_rb32(f);
7370  fieldlength = avio_rb32(f);
7371  item_count = avio_rb32(f);
7372  for (i = 0; i < item_count; i++) {
7373  int64_t time, offset;
7374  int index;
7375  MOVFragmentStreamInfo * frag_stream_info;
7376 
7377  if (avio_feof(f)) {
7378  return AVERROR_INVALIDDATA;
7379  }
7380 
7381  if (version == 1) {
7382  time = avio_rb64(f);
7383  offset = avio_rb64(f);
7384  } else {
7385  time = avio_rb32(f);
7386  offset = avio_rb32(f);
7387  }
7388 
7389  // The first sample of each stream in a fragment is always a random
7390  // access sample. So it's entry in the tfra can be used as the
7391  // initial PTS of the fragment.
7392  index = update_frag_index(mov, offset);
7393  frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
7394  if (frag_stream_info &&
7395  frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
7396  frag_stream_info->first_tfra_pts = time;
7397 
7398  for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
7399  avio_r8(f);
7400  for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
7401  avio_r8(f);
7402  for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
7403  avio_r8(f);
7404  }
7405 
7406  avio_seek(f, pos + size, SEEK_SET);
7407  return 0;
7408 }
7409 
7411 {
7412  int64_t stream_size = avio_size(f);
7413  int64_t original_pos = avio_tell(f);
7414  int64_t seek_ret;
7415  int32_t mfra_size;
7416  int ret = -1;
7417  if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
7418  ret = seek_ret;
7419  goto fail;
7420  }
7421  mfra_size = avio_rb32(f);
7422  if (mfra_size < 0 || mfra_size > stream_size) {
7423  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
7424  goto fail;
7425  }
7426  if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
7427  ret = seek_ret;
7428  goto fail;
7429  }
7430  if (avio_rb32(f) != mfra_size) {
7431  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
7432  goto fail;
7433  }
7434  if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
7435  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
7436  goto fail;
7437  }
7438  av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
7439  do {
7440  ret = read_tfra(c, f);
7441  if (ret < 0)
7442  goto fail;
7443  } while (!ret);
7444  ret = 0;
7445 fail:
7446  seek_ret = avio_seek(f, original_pos, SEEK_SET);
7447  if (seek_ret < 0) {
7448  av_log(c->fc, AV_LOG_ERROR,
7449  "failed to seek back after looking for mfra\n");
7450  ret = seek_ret;
7451  }
7452  return ret;
7453 }
7454 
7456 {
7457  MOVContext *mov = s->priv_data;
7458  AVIOContext *pb = s->pb;
7459  int j, err;
7460  MOVAtom atom = { AV_RL32("root") };
7461  int i;
7462 
7463  if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
7464  av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
7466  return AVERROR(EINVAL);
7467  }
7468 
7469  mov->fc = s;
7470  mov->trak_index = -1;
7471  /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
7472  if (pb->seekable & AVIO_SEEKABLE_NORMAL)
7473  atom.size = avio_size(pb);
7474  else
7475  atom.size = INT64_MAX;
7476 
7477  /* check MOV header */
7478  do {
7479  if (mov->moov_retry)
7480  avio_seek(pb, 0, SEEK_SET);
7481  if ((err = mov_read_default(mov, pb, atom)) < 0) {
7482  av_log(s, AV_LOG_ERROR, "error reading header\n");
7483  goto fail;
7484  }
7485  } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
7486  if (!mov->found_moov) {
7487  av_log(s, AV_LOG_ERROR, "moov atom not found\n");
7488  err = AVERROR_INVALIDDATA;
7489  goto fail;
7490  }
7491  av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
7492 
7493  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
7494  if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
7495  mov_read_chapters(s);
7496  for (i = 0; i < s->nb_streams; i++)
7497  if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
7498  mov_read_timecode_track(s, s->streams[i]);
7499  } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
7500  mov_read_rtmd_track(s, s->streams[i]);
7501  }
7502  }
7503 
7504  /* copy timecode metadata from tmcd tracks to the related video streams */
7505  for (i = 0; i < s->nb_streams; i++) {
7506  AVStream *st = s->streams[i];
7507  MOVStreamContext *sc = st->priv_data;
7508  if (sc->timecode_track > 0) {
7509  AVDictionaryEntry *tcr;
7510  int tmcd_st_id = -1;
7511 
7512  for (j = 0; j < s->nb_streams; j++)
7513  if (s->streams[j]->id == sc->timecode_track)
7514  tmcd_st_id = j;
7515 
7516  if (tmcd_st_id < 0 || tmcd_st_id == i)
7517  continue;
7518  tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
7519  if (tcr)
7520  av_dict_set(&st->metadata, "timecode", tcr->value, 0);
7521  }
7522  }
7524 
7525  for (i = 0; i < s->nb_streams; i++) {
7526  AVStream *st = s->streams[i];
7527  MOVStreamContext *sc = st->priv_data;
7528  fix_timescale(mov, sc);
7530  st->skip_samples = sc->start_pad;
7531  }
7532  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
7534  sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
7536  if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
7537  st->codecpar->width = sc->width;
7538  st->codecpar->height = sc->height;
7539  }
7541  if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
7542  goto fail;
7543  }
7544  }
7545  if (mov->handbrake_version &&
7546  mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
7548  ) {
7549  av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
7551  }
7552  }
7553 
7554  if (mov->trex_data) {
7555  for (i = 0; i < s->nb_streams; i++) {
7556  AVStream *st = s->streams[i];
7557  MOVStreamContext *sc = st->priv_data;
7558  if (st->duration > 0) {
7559  if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7560  av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7561  sc->data_size, sc->time_scale);
7562  err = AVERROR_INVALIDDATA;
7563  goto fail;
7564  }
7565  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
7566  }
7567  }
7568  }
7569 
7570  if (mov->use_mfra_for > 0) {
7571  for (i = 0; i < s->nb_streams; i++) {
7572  AVStream *st = s->streams[i];
7573  MOVStreamContext *sc = st->priv_data;
7574  if (sc->duration_for_fps > 0) {
7575  if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7576  av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7577  sc->data_size, sc->time_scale);
7578  err = AVERROR_INVALIDDATA;
7579  goto fail;
7580  }
7581  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
7582  sc->duration_for_fps;
7583  }
7584  }
7585  }
7586 
7587  for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
7588  if (mov->bitrates[i]) {
7589  s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
7590  }
7591  }
7592 
7593  ff_rfps_calculate(s);
7594 
7595  for (i = 0; i < s->nb_streams; i++) {
7596  AVStream *st = s->streams[i];
7597  MOVStreamContext *sc = st->priv_data;
7598 
7599  switch (st->codecpar->codec_type) {
7600  case AVMEDIA_TYPE_AUDIO:
7601  err = ff_replaygain_export(st, s->metadata);
7602  if (err < 0) {
7603  goto fail;
7604  }
7605  break;
7606  case AVMEDIA_TYPE_VIDEO:
7607  if (sc->display_matrix) {
7609  sizeof(int32_t) * 9);
7610  if (err < 0)
7611  goto fail;
7612 
7613  sc->display_matrix = NULL;
7614  }
7615  if (sc->stereo3d) {
7617  (uint8_t *)sc->stereo3d,
7618  sizeof(*sc->stereo3d));
7619  if (err < 0)
7620  goto fail;
7621 
7622  sc->stereo3d = NULL;
7623  }
7624  if (sc->spherical) {
7626  (uint8_t *)sc->spherical,
7627  sc->spherical_size);
7628  if (err < 0)
7629  goto fail;
7630 
7631  sc->spherical = NULL;
7632  }
7633  if (sc->mastering) {
7635  (uint8_t *)sc->mastering,
7636  sizeof(*sc->mastering));
7637  if (err < 0)
7638  goto fail;
7639 
7640  sc->mastering = NULL;
7641  }
7642  if (sc->coll) {
7644  (uint8_t *)sc->coll,
7645  sc->coll_size);
7646  if (err < 0)
7647  goto fail;
7648 
7649  sc->coll = NULL;
7650  }
7651  break;
7652  }
7653  }
7655 
7656  for (i = 0; i < mov->frag_index.nb_items; i++)
7657  if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
7658  mov->frag_index.item[i].headers_read = 1;
7659 
7660  return 0;
7661 fail:
7662  mov_read_close(s);
7663  return err;
7664 }
7665 
7667 {
7669  int64_t best_dts = INT64_MAX;
7670  int i;
7671  for (i = 0; i < s->nb_streams; i++) {
7672  AVStream *avst = s->streams[i];
7673  MOVStreamContext *msc = avst->priv_data;
7674  if (msc->pb && msc->current_sample < avst->nb_index_entries) {
7675  AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
7676  int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
7677  av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
7678  if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
7679  ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
7680  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && dts != AV_NOPTS_VALUE &&
7681  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
7682  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
7683  sample = current_sample;
7684  best_dts = dts;
7685  *st = avst;
7686  }
7687  }
7688  }
7689  return sample;
7690 }
7691 
7692 static int should_retry(AVIOContext *pb, int error_code) {
7693  if (error_code == AVERROR_EOF || avio_feof(pb))
7694  return 0;
7695 
7696  return 1;
7697 }
7698 
7699 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
7700 {
7701  int ret;
7702  MOVContext *mov = s->priv_data;
7703 
7704  if (index >= 0 && index < mov->frag_index.nb_items)
7705  target = mov->frag_index.item[index].moof_offset;
7706  if (avio_seek(s->pb, target, SEEK_SET) != target) {
7707  av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
7708  return AVERROR_INVALIDDATA;
7709  }
7710 
7711  mov->next_root_atom = 0;
7712  if (index < 0 || index >= mov->frag_index.nb_items)
7713  index = search_frag_moof_offset(&mov->frag_index, target);
7714  if (index < mov->frag_index.nb_items) {
7715  if (index + 1 < mov->frag_index.nb_items)
7716  mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7717  if (mov->frag_index.item[index].headers_read)
7718  return 0;
7719  mov->frag_index.item[index].headers_read = 1;
7720  }
7721 
7722  mov->found_mdat = 0;
7723 
7724  ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
7725  if (ret < 0)
7726  return ret;
7727  if (avio_feof(s->pb))
7728  return AVERROR_EOF;
7729  av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
7730 
7731  return 1;
7732 }
7733 
7735 {
7736  uint8_t *side, *extradata;
7737  int extradata_size;
7738 
7739  /* Save the current index. */
7740  sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
7741 
7742  /* Notify the decoder that extradata changed. */
7743  extradata_size = sc->extradata_size[sc->last_stsd_index];
7744  extradata = sc->extradata[sc->last_stsd_index];
7745  if (extradata_size > 0 && extradata) {
7746  side = av_packet_new_side_data(pkt,
7748  extradata_size);
7749  if (!side)
7750  return AVERROR(ENOMEM);
7751  memcpy(side, extradata, extradata_size);
7752  }
7753 
7754  return 0;
7755 }
7756 
7758 {
7759  MOVContext *mov = s->priv_data;
7760  MOVStreamContext *sc;
7762  AVStream *st = NULL;
7763  int64_t current_index;
7764  int ret;
7765  mov->fc = s;
7766  retry:
7767  sample = mov_find_next_sample(s, &st);
7768  if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7769  if (!mov->next_root_atom)
7770  return AVERROR_EOF;
7771  if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7772  return ret;
7773  goto retry;
7774  }
7775  sc = st->priv_data;
7776  /* must be done just before reading, to avoid infinite loop on sample */
7777  current_index = sc->current_index;
7779 
7780  if (mov->next_root_atom) {
7781  sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7782  sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7783  }
7784 
7785  if (st->discard != AVDISCARD_ALL) {
7786  int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7787  if (ret64 != sample->pos) {
7788  av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7789  sc->ffindex, sample->pos);
7790  if (should_retry(sc->pb, ret64)) {
7792  }
7793  return AVERROR_INVALIDDATA;
7794  }
7795 
7796  if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7797  av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7798  goto retry;
7799  }
7800 
7801  ret = av_get_packet(sc->pb, pkt, sample->size);
7802  if (ret < 0) {
7803  if (should_retry(sc->pb, ret)) {
7805  }
7806  return ret;
7807  }
7808 #if CONFIG_DV_DEMUXER
7809  if (mov->dv_demux && sc->dv_audio_container) {
7810  AVBufferRef *buf = pkt->buf;
7811  ret = avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7812  pkt->buf = buf;
7813  av_packet_unref(pkt);
7814  if (ret < 0)
7815  return ret;
7816  ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7817  if (ret < 0)
7818  return ret;
7819  }
7820 #endif
7821  if (sc->has_palette) {
7822  uint8_t *pal;
7823 
7825  if (!pal) {
7826  av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7827  } else {
7828  memcpy(pal, sc->palette, AVPALETTE_SIZE);
7829  sc->has_palette = 0;
7830  }
7831  }
7832  if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7833  if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7835  }
7836  }
7837 
7838  pkt->stream_index = sc->ffindex;
7839  pkt->dts = sample->timestamp;
7840  if (sample->flags & AVINDEX_DISCARD_FRAME) {
7841  pkt->flags |= AV_PKT_FLAG_DISCARD;
7842  }
7843  if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7844  pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7845  /* update ctts context */
7846  sc->ctts_sample++;
7847  if (sc->ctts_index < sc->ctts_count &&
7848  sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7849  sc->ctts_index++;
7850  sc->ctts_sample = 0;
7851  }
7852  } else {
7853  int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7855 
7856  if (next_dts >= pkt->dts)
7857  pkt->duration = next_dts - pkt->dts;
7858  pkt->pts = pkt->dts;
7859  }
7860  if (st->discard == AVDISCARD_ALL)
7861  goto retry;
7862  pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7863  pkt->pos = sample->pos;
7864 
7865  /* Multiple stsd handling. */
7866  if (sc->stsc_data) {
7867  /* Keep track of the stsc index for the given sample, then check
7868  * if the stsd index is different from the last used one. */
7869  sc->stsc_sample++;
7870  if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7871  mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7872  sc->stsc_index++;
7873  sc->stsc_sample = 0;
7874  /* Do not check indexes after a switch. */
7875  } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7876  sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7877  sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7878  ret = mov_change_extradata(sc, pkt);
7879  if (ret < 0)
7880  return ret;
7881  }
7882  }
7883 
7884  if (mov->aax_mode)
7885  aax_filter(pkt->data, pkt->size, mov);
7886 
7887  ret = cenc_filter(mov, st, sc, pkt, current_index);
7888  if (ret < 0) {
7889  av_packet_unref(pkt);
7890  return ret;
7891  }
7892 
7893  return 0;
7894 }
7895 
7896 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7897 {
7898  MOVContext *mov = s->priv_data;
7899  int index;
7900 
7901  if (!mov->frag_index.complete)
7902  return 0;
7903 
7904  index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7905  if (index < 0)
7906  index = 0;
7907  if (!mov->frag_index.item[index].headers_read)
7908  return mov_switch_root(s, -1, index);
7909  if (index + 1 < mov->frag_index.nb_items)
7910  mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7911 
7912  return 0;
7913 }
7914 
7915 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7916 {
7917  MOVStreamContext *sc = st->priv_data;
7918  int sample, time_sample, ret;
7919  unsigned int i;
7920 
7921  // Here we consider timestamp to be PTS, hence try to offset it so that we
7922  // can search over the DTS timeline.
7923  timestamp -= (sc->min_corrected_pts + sc->dts_shift);
7924 
7925  ret = mov_seek_fragment(s, st, timestamp);
7926  if (ret < 0)
7927  return ret;
7928 
7929  sample = av_index_search_timestamp(st, timestamp, flags);
7930  av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7931  if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7932  sample = 0;
7933  if (sample < 0) /* not sure what to do */
7934  return AVERROR_INVALIDDATA;
7935  mov_current_sample_set(sc, sample);
7936  av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7937  /* adjust ctts index */
7938  if (sc->ctts_data) {
7939  time_sample = 0;
7940  for (i = 0; i < sc->ctts_count; i++) {
7941  int next = time_sample + sc->ctts_data[i].count;
7942  if (next > sc->current_sample) {
7943  sc->ctts_index = i;
7944  sc->ctts_sample = sc->current_sample - time_sample;
7945  break;
7946  }
7947  time_sample = next;
7948  }
7949  }
7950 
7951  /* adjust stsd index */
7952  if (sc->chunk_count) {
7953  time_sample = 0;
7954  for (i = 0; i < sc->stsc_count; i++) {
7955  int64_t next = time_sample + mov_get_stsc_samples(sc, i);
7956  if (next > sc->current_sample) {
7957  sc->stsc_index = i;
7958  sc->stsc_sample = sc->current_sample - time_sample;
7959  break;
7960  }
7961  av_assert0(next == (int)next);
7962  time_sample = next;
7963  }
7964  }
7965 
7966  return sample;
7967 }
7968 
7969 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7970 {
7971  MOVContext *mc = s->priv_data;
7972  AVStream *st;
7973  int sample;
7974  int i;
7975 
7976  if (stream_index >= s->nb_streams)
7977  return AVERROR_INVALIDDATA;
7978 
7979  st = s->streams[stream_index];
7980  sample = mov_seek_stream(s, st, sample_time, flags);
7981  if (sample < 0)
7982  return sample;
7983 
7984  if (mc->seek_individually) {
7985  /* adjust seek timestamp to found sample timestamp */
7986  int64_t seek_timestamp = st->index_entries[sample].timestamp;
7987 
7988  for (i = 0; i < s->nb_streams; i++) {
7989  int64_t timestamp;
7990  MOVStreamContext *sc = s->streams[i]->priv_data;
7991  st = s->streams[i];
7992  st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7993 
7994  if (stream_index == i)
7995  continue;
7996 
7997  timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7998  mov_seek_stream(s, st, timestamp, flags);
7999  }
8000  } else {
8001  for (i = 0; i < s->nb_streams; i++) {
8002  MOVStreamContext *sc;
8003  st = s->streams[i];
8004  sc = st->priv_data;
8005  mov_current_sample_set(sc, 0);
8006  }
8007  while (1) {
8008  MOVStreamContext *sc;
8009  AVIndexEntry *entry = mov_find_next_sample(s, &st);
8010  if (!entry)
8011  return AVERROR_INVALIDDATA;
8012  sc = st->priv_data;
8013  if (sc->ffindex == stream_index && sc->current_sample == sample)
8014  break;
8016  }
8017  }
8018  return 0;
8019 }
8020 
8021 #define OFFSET(x) offsetof(MOVContext, x)
8022 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
8023 static const AVOption mov_options[] = {
8024  {"use_absolute_path",
8025  "allow using absolute path when opening alias, this is a possible security issue",
8026  OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
8027  0, 1, FLAGS},
8028  {"seek_streams_individually",
8029  "Seek each stream individually to the to the closest point",
8030  OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
8031  0, 1, FLAGS},
8032  {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
8033  0, 1, FLAGS},
8034  {"advanced_editlist",
8035  "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
8036  OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
8037  0, 1, FLAGS},
8038  {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
8039  0, 1, FLAGS},
8040  {"use_mfra_for",
8041  "use mfra for fragment timestamps",
8042  OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
8044  "use_mfra_for"},
8045  {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
8046  FLAGS, "use_mfra_for" },
8047  {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
8048  FLAGS, "use_mfra_for" },
8049  {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
8050  FLAGS, "use_mfra_for" },
8051  { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
8052  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
8053  { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
8054  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
8055  { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
8057  { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
8058  "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
8059  AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
8060  .flags = AV_OPT_FLAG_DECODING_PARAM },
8061  { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
8062  { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
8063  {.i64 = 0}, 0, 1, FLAGS },
8064 
8065  { NULL },
8066 };
8067 
8068 static const AVClass mov_class = {
8069  .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
8070  .item_name = av_default_item_name,
8071  .option = mov_options,
8072  .version = LIBAVUTIL_VERSION_INT,
8073 };
8074 
8076  .name = "mov,mp4,m4a,3gp,3g2,mj2",
8077  .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
8078  .priv_class = &mov_class,
8079  .priv_data_size = sizeof(MOVContext),
8080  .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
8081  .read_probe = mov_probe,
8087 };
int32_t pitch
Rotation around the right vector [-90, 90].
Definition: spherical.h:127
static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1734
int itunes_metadata
metadata are itunes style
Definition: isom.h:260
int * bitrates
bitrates read before streams creation
Definition: isom.h:272
static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1383
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition: sha.c:345
#define AVINDEX_DISCARD_FRAME
Definition: avformat.h:811
int64_t current_index
Definition: isom.h:190
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:4745
AVSphericalMapping * av_spherical_alloc(size_t *size)
Allocate a AVSphericalVideo structure and initialize its fields to default values.
Definition: spherical.c:24
int cid
Definition: mxfenc.c:1948
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:2504
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
A callback for opening new IO streams.
Definition: avformat.h:1933
int64_t moof_offset
Definition: isom.h:137
#define AV_RB8(x)
Definition: intreadwrite.h:395
size_t auxiliary_offsets_count
Definition: isom.h:124
#define NULL
Definition: coverity.c:32
#define DRM_BLOB_SIZE
Definition: mov.c:992
const char const char void * val
Definition: avisynth_c.h:771
#define FF_API_OLD_ROTATE_API
Definition: version.h:80
enum AVFieldOrder field_order
Video only.
Definition: avcodec.h:3981
discard all frames except keyframes
Definition: avcodec.h:802
static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:783
static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1524
Bytestream IO Context.
Definition: avio.h:161
enum AVColorTransferCharacteristic color_trc
Definition: avcodec.h:3988
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
Definition: mov.c:7699
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:336
void * av_realloc(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory.
Definition: mem.c:135
static const char * format[]
Definition: af_aiir.c:330
int size
static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:824
#define av_realloc_f(p, o, n)
uint32_t tmcd_flags
tmcd track flags
Definition: isom.h:208
#define OPUS_SEEK_PREROLL_MS
Definition: oggparseopus.c:35
unsigned int rap_group_count
Definition: isom.h:211
int found_tfhd
Definition: isom.h:90
unsigned int elst_count
Definition: isom.h:176
unsigned MaxCLL
Max content light level (cd/m^2).
void av_encryption_info_free(AVEncryptionInfo *info)
Frees the given encryption info object.
static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5111
AVOption.
Definition: opt.h:246
hash context
Definition: sha.c:34
MOVTrackExt * trex_data
Definition: isom.h:258
int export_all
Definition: isom.h:270
int64_t end
Definition: isom.h:154
static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
Definition: mov.c:7734
unsigned track_id
Definition: isom.h:91
#define MOV_TFHD_DEFAULT_DURATION
Definition: isom.h:307
static AVIndexEntry * mov_find_next_sample(AVFormatContext *s, AVStream **st)
Definition: mov.c:7666
uint32_t format
Definition: isom.h:232
static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:539
static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4332
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:3136
unsigned int samples_per_frame
Definition: isom.h:194
AVEncryptionInitInfo * av_encryption_init_info_alloc(uint32_t system_id_size, uint32_t num_key_ids, uint32_t key_id_size, uint32_t data_size)
Allocates an AVEncryptionInitInfo structure and sub-pointers to hold the given sizes.
static void mov_build_index(MOVContext *mov, AVStream *st)
Definition: mov.c:3748
int dv_audio_container
Definition: isom.h:195
Definition: isom.h:56
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:381
av_cold int av_sha_init(AVSHA *ctx, int bits)
Initialize SHA-1 or SHA-2 hashing.
Definition: sha.c:273
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
float rate
Definition: isom.h:70
uint64_t base_data_offset
Definition: isom.h:92
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
int64_t duration
Definition: isom.h:68
size_t spherical_size
Definition: isom.h:227
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1465
unsigned int ctts_allocated_size
Definition: isom.h:167
#define AV_RB64
Definition: intreadwrite.h:164
#define AV_DICT_DONT_OVERWRITE
Don&#39;t overwrite existing entries.
Definition: dict.h:79
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4899
static void skip_bits_long(GetBitContext *s, int n)
Skips the specified number of bits.
Definition: get_bits.h:293
const char * g
Definition: vf_curves.c:115
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:696
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle...
Definition: avstring.c:56
int64_t pos
Definition: avformat.h:803
static void mov_free_encryption_index(MOVEncryptionIndex **index)
Definition: mov.c:7228
void av_encryption_init_info_free(AVEncryptionInitInfo *info)
Frees the given encryption init info object.
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2506
static av_always_inline float av_int2float(uint32_t i)
Reinterpret a 32-bit integer as a float.
Definition: intfloat.h:40
unsigned int stsc_count
Definition: isom.h:169
int has_palette
Definition: isom.h:206
static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:123
uint32_t crypt_byte_block
Only used for pattern encryption.
#define avpriv_request_sample(...)
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: avcodec.h:1226
static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
Definition: mov.c:1182
static MOVFragmentStreamInfo * get_current_frag_stream_info(MOVFragmentIndex *frag_index)
Definition: mov.c:1202
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection...
Definition: spherical.h:72
AVEncryptionInfo * default_encrypted_sample
Definition: isom.h:238
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3900
int allocated_size
Definition: isom.h:145
static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4194
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:936
int num
Numerator.
Definition: rational.h:59
AVMasteringDisplayMetadata * mastering
Definition: isom.h:228
int index
stream index in AVFormatContext
Definition: avformat.h:875
int size
Definition: avcodec.h:1446
uint8_t pi<< 24) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_U8,(uint64_t)((*(const uint8_t *) pi - 0x80U))<< 56) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8,(*(const uint8_t *) pi - 0x80) *(1.0f/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8,(*(const uint8_t *) pi - 0x80) *(1.0/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16,(*(const int16_t *) pi >>8)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S16,(uint64_t)(*(const int16_t *) pi)<< 48) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, *(const int16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, *(const int16_t *) pi *(1.0/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32,(*(const int32_t *) pi >>24)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S32,(uint64_t)(*(const int32_t *) pi)<< 32) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, *(const int32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, *(const int32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S64,(*(const int64_t *) pi >>56)+0x80) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S64, *(const int64_t *) pi *(1.0f/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S64, *(const int64_t *) pi *(1.0/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, av_clip_uint8(lrintf(*(const float *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, av_clip_int16(lrintf(*(const float *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, av_clipl_int32(llrintf(*(const float *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_FLT, llrintf(*(const float *) pi *(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, av_clip_uint8(lrint(*(const double *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, av_clip_int16(lrint(*(const double *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, av_clipl_int32(llrint(*(const double *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_DBL, llrint(*(const double *) pi *(INT64_C(1)<< 63))) #define FMT_PAIR_FUNC(out, in) static conv_func_type *const fmt_pair_to_conv_functions[AV_SAMPLE_FMT_NB *AV_SAMPLE_FMT_NB]={ FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S64), };static void cpy1(uint8_t **dst, const uint8_t **src, int len){ memcpy(*dst, *src, len);} static void cpy2(uint8_t **dst, const uint8_t **src, int len){ memcpy(*dst, *src, 2 *len);} static void cpy4(uint8_t **dst, const uint8_t **src, int len){ memcpy(*dst, *src, 4 *len);} static void cpy8(uint8_t **dst, const uint8_t **src, int len){ memcpy(*dst, *src, 8 *len);} AudioConvert *swri_audio_convert_alloc(enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt, int channels, const int *ch_map, int flags) { AudioConvert *ctx;conv_func_type *f=fmt_pair_to_conv_functions[av_get_packed_sample_fmt(out_fmt)+AV_SAMPLE_FMT_NB *av_get_packed_sample_fmt(in_fmt)];if(!f) return NULL;ctx=av_mallocz(sizeof(*ctx));if(!ctx) return NULL;if(channels==1){ in_fmt=av_get_planar_sample_fmt(in_fmt);out_fmt=av_get_planar_sample_fmt(out_fmt);} ctx->channels=channels;ctx->conv_f=f;ctx->ch_map=ch_map;if(in_fmt==AV_SAMPLE_FMT_U8||in_fmt==AV_SAMPLE_FMT_U8P) memset(ctx->silence, 0x80, sizeof(ctx->silence));if(out_fmt==in_fmt &&!ch_map) { switch(av_get_bytes_per_sample(in_fmt)){ case 1:ctx->simd_f=cpy1;break;case 2:ctx->simd_f=cpy2;break;case 4:ctx->simd_f=cpy4;break;case 8:ctx->simd_f=cpy8;break;} } if(HAVE_X86ASM &&HAVE_MMX) swri_audio_convert_init_x86(ctx, out_fmt, in_fmt, channels);if(ARCH_ARM) swri_audio_convert_init_arm(ctx, out_fmt, in_fmt, channels);if(ARCH_AARCH64) swri_audio_convert_init_aarch64(ctx, out_fmt, in_fmt, channels);return ctx;} void swri_audio_convert_free(AudioConvert **ctx) { av_freep(ctx);} int swri_audio_convert(AudioConvert *ctx, AudioData *out, AudioData *in, int len) { int ch;int off=0;const int os=(out->planar ? 1 :out->ch_count) *out->bps;unsigned misaligned=0;av_assert0(ctx->channels==out->ch_count);if(ctx->in_simd_align_mask) { int planes=in->planar ? in->ch_count :1;unsigned m=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) in->ch[ch];misaligned|=m &ctx->in_simd_align_mask;} if(ctx->out_simd_align_mask) { int planes=out->planar ? out->ch_count :1;unsigned m=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) out->ch[ch];misaligned|=m &ctx->out_simd_align_mask;} if(ctx->simd_f &&!ctx->ch_map &&!misaligned){ off=len &~15;av_assert1(off >=0);av_assert1(off<=len);av_assert2(ctx->channels==SWR_CH_MAX||!in->ch[ctx->channels]);if(off >0){ if(out->planar==in->planar){ int planes=out->planar ? out->ch_count :1;for(ch=0;ch< planes;ch++){ ctx->simd_f(out-> ch ch
Definition: audioconvert.c:56
const char * b
Definition: vf_curves.c:116
#define AV_WB8(p, d)
Definition: intreadwrite.h:396
#define MOV_TRUN_SAMPLE_CTS
Definition: isom.h:318
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:246
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:191
#define AVIO_FLAG_READ
read-only
Definition: avio.h:654
void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt)
Encrypt or decrypt a buffer using a previously initialized context.
Definition: aes.c:163
uint8_t * decryption_key
Definition: isom.h:287
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1103
This describes encryption info for a packet.
int ignore_chapters
Definition: isom.h:267
static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
Definition: mov.c:7321
void * activation_bytes
Definition: isom.h:282
#define tc
Definition: regdef.h:69
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1666
AVEncryptionInfo ** encrypted_samples
Definition: isom.h:118
struct MOVStreamContext::@253 cenc
static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6172
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:56
uint64_t * auxiliary_offsets
Absolute seek position.
Definition: isom.h:123
color_range
void * priv_data
Definition: avformat.h:889
uint8_t * av_encryption_init_info_add_side_data(const AVEncryptionInitInfo *info, size_t *side_data_size)
Allocates and initializes side data that holds a copy of the given encryption init info...
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:331
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
const char * key
int version
Definition: avisynth_c.h:766
int16_t audio_cid
stsd audio compression id
Definition: isom.h:197
char ** meta_keys
Definition: isom.h:252
#define PUT_UTF8(val, tmp, PUT_BYTE)
Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
Definition: common.h:438
discard all
Definition: avcodec.h:803
Views are next to each other.
Definition: stereo3d.h:67
static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
Definition: mov.c:5675
#define IS_MATRIX_IDENT(matrix)
Definition: mov.c:4474
static AVPacket pkt
int height
tkhd height
Definition: isom.h:203
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:785
int(* parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:72
#define src
Definition: vp8dsp.c:254
static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:302
#define sample
uint32_t type
Definition: isom.h:83
static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5738
uint32_t skip_byte_block
Only used for pattern encryption.
MOVElst * elst_data
Definition: isom.h:175
int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a UTF-16 string from pb and convert it to UTF-8.
AVStereo3D * av_stereo3d_alloc(void)
Allocate an AVStereo3D structure and set its fields to default values.
Definition: stereo3d.c:28
int strict_std_compliance
Allow non-standard and experimental extension.
Definition: avformat.h:1659
MOVStsc * stsc_data
Definition: isom.h:170
int nb_items
Definition: isom.h:148
static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1473
int ctts_index
Definition: isom.h:177
int complete
Definition: isom.h:146
unsigned stsd_id
Definition: isom.h:103
AVSphericalMapping * spherical
Definition: isom.h:226
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3892
int found_moov
&#39;moov&#39; atom has been found
Definition: isom.h:248
static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2732
static void export_orphan_timecode(AVFormatContext *s)
Definition: mov.c:7337
enum AVColorSpace color_space
Definition: avcodec.h:3989
static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1789
static MOVFragmentStreamInfo * get_frag_stream_info(MOVFragmentIndex *frag_index, int index, int id)
Definition: mov.c:1163
#define MOV_TFHD_DEFAULT_BASE_IS_MOOF
Definition: isom.h:311
const char * av_color_space_name(enum AVColorSpace space)
Definition: pixdesc.c:2839
Macro definitions for various function/variable attributes.
int frame_size
Audio only.
Definition: avcodec.h:4021
Mastering display metadata (based on SMPTE-2086:2014).
Definition: avcodec.h:1334
static int should_retry(AVIOContext *pb, int error_code)
Definition: mov.c:7692
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that&#39;s been allocated with av_malloc() or another memory allocation function...
Definition: dict.h:73
static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
Definition: mov.c:1643
int av_get_channel_layout_nb_channels(uint64_t channel_layout)
Return the number of channels in the channel layout.
unsigned flags
Definition: isom.h:106
#define MOV_TKHD_FLAG_ENABLED
Definition: isom.h:330
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:4597
int isom
1 if file is ISO Media (mp4/3gp)
Definition: isom.h:256
int found_mdat
&#39;mdat&#39; atom has been found
Definition: isom.h:249
int width
tkhd width
Definition: isom.h:202
unsigned drefs_count
Definition: isom.h:198
static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5491
Format I/O context.
Definition: avformat.h:1351
static int mov_probe(AVProbeData *p)
Definition: mov.c:6976
static int mov_read_header(AVFormatContext *s)
Definition: mov.c:7455
char filename[64]
Definition: isom.h:78
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define AVFMT_FLAG_IGNIDX
Ignore index.
Definition: avformat.h:1484
void av_aes_ctr_crypt(struct AVAESCTR *a, uint8_t *dst, const uint8_t *src, int count)
Process a buffer using a previously initialized context.
Definition: aes_ctr.c:111
static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition: mov.c:2304
Public dictionary API.
int avpriv_dict_set_timestamp(AVDictionary **dict, const char *key, int64_t timestamp)
Set a dictionary value to an ISO-8601 compliant timestamp string.
Definition: dict.c:258
MOVDref * drefs
Definition: isom.h:199
static double cb(void *priv, double x, double y)
Definition: vf_geq.c:112
static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1145
static char buffer[20]
Definition: seek.c:32
static const AVOption mov_options[]
Definition: mov.c:8023
static void mov_current_sample_dec(MOVStreamContext *sc)
Definition: mov.c:3406
static int64_t start_time
Definition: ffplay.c:330
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:60
int first
Definition: isom.h:62
uint8_t
uint8_t ** key_ids
An array of key IDs this initialization data is for.
AVEncryptionInfo * av_encryption_info_clone(const AVEncryptionInfo *info)
Allocates an AVEncryptionInfo structure with a copy of the given data.
#define FF_MOV_FLAG_MFRA_DTS
Definition: isom.h:363
#define av_malloc(s)
static int64_t add_ctts_entry(MOVStts **ctts_data, unsigned int *ctts_count, unsigned int *allocated_size, int count, int duration)
Append a new ctts entry to ctts_data.
Definition: mov.c:3311
Opaque data information usually continuous.
Definition: avutil.h:203
int width
Video only.
Definition: avcodec.h:3966
size_t coll_size
Definition: isom.h:230
AVOptions.
unsigned int sample_count
Definition: isom.h:181
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:75
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:800
int count
Definition: isom.h:63
int dts_shift
dts shift when ctts is negative
Definition: isom.h:204
int stsd_version
Definition: isom.h:222
static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:864
#define AVPALETTE_SIZE
Definition: pixfmt.h:32
#define f(width, name)
Definition: cbs_vp9.c:255
unsigned int bytes_of_clear_data
The number of bytes that are clear.
timecode is drop frame
Definition: timecode.h:36
#define AV_RB32
Definition: intreadwrite.h:130
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1463
static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6708
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: avcodec.h:1220
enum AVStreamParseType need_parsing
Definition: avformat.h:1092
int id
Format-specific stream ID.
Definition: avformat.h:881
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5687
AVInputFormat ff_mov_demuxer
Definition: mov.c:8075
unsigned int count
Definition: isom.h:110
static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5131
static int mov_read_sample_encryption_info(MOVContext *c, AVIOContext *pb, MOVStreamContext *sc, AVEncryptionInfo **sample, int use_subsamples)
Definition: mov.c:5971
static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add index entry with the given values, to the end of st->index_entries.
Definition: mov.c:3256
static void mov_current_sample_inc(MOVStreamContext *sc)
Definition: mov.c:3394
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4469
uint8_t * av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, int *size)
Get side information from stream.
Definition: utils.c:5493
int16_t nlvl_to
Definition: isom.h:79
uint32_t scheme
The fourcc encryption scheme, in big-endian byte order.
This file is part of FFmpeg.
This describes info used to initialize an encryption key system.
#define AV_CH_LOW_FREQUENCY
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1419
int64_t duration
Definition: movenc.c:63
char volume[28]
Definition: isom.h:77
static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:114
static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:945
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:144
static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb, int codec_tag, int format, int64_t size)
Definition: mov.c:2447
int stsd_count
Definition: isom.h:221
int activation_bytes_size
Definition: isom.h:283
int initial_padding
Audio only.
Definition: avcodec.h:4029
const char data[16]
Definition: mxf.c:91
#define height
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
static void finish(void)
Definition: movenc.c:345
#define ALAC_EXTRADATA_SIZE
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1482
DVDemuxContext * avpriv_dv_init_demux(AVFormatContext *s)
Definition: dv.c:324
uint8_t * data
Definition: avcodec.h:1445
This side data is encryption initialization data.
Definition: avcodec.h:1361
#define MOV_TRUN_SAMPLE_SIZE
Definition: isom.h:316
uint32_t tag
Definition: movenc.c:1478
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
Definition: utils.c:2100
int nb_frames_for_fps
Definition: isom.h:214
uint8_t * iv
The initialization vector.
#define ff_dlog(a,...)
#define AVERROR_EOF
End of file.
Definition: error.h:55
bitstream reader API header.
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:313
struct AVAESCTR * aes_ctr
Definition: isom.h:236
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:55
static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:717
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:921
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition: replaygain.c:91
static int get_current_encryption_info(MOVContext *c, MOVEncryptionIndex **encryption_index, MOVStreamContext **sc)
Gets the current encryption info and associated current stream context.
Definition: mov.c:5921
static int test_same_origin(const char *src, const char *ref)
Definition: mov.c:4083
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
Definition: mem.c:198
void av_aes_ctr_free(struct AVAESCTR *a)
Release an AVAESCTR context.
Definition: aes_ctr.c:84
enum AVCodecID video_codec_id
Forced video codec_id.
Definition: avformat.h:1537
uint64_t channel_layout
Audio only.
Definition: avcodec.h:4002
#define av_log(a,...)
int current_sample
Definition: isom.h:189
#define MOV_TFHD_DEFAULT_SIZE
Definition: isom.h:308
int32_t movie_display_matrix[3][3]
display matrix from mvhd
Definition: isom.h:290
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:647
int ff_get_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int size, int big_endian)
Definition: riffdec.c:91
AVEncryptionInitInfo * av_encryption_init_info_get_side_data(const uint8_t *side_data, size_t side_data_size)
Creates a copy of the AVEncryptionInitInfo that is contained in the given side data.
static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5874
unsigned track_id
Definition: isom.h:102
static int mov_try_read_block(AVIOContext *pb, size_t size, uint8_t **data)
Tries to read the given number of bytes from the stream and puts it in a newly allocated buffer...
Definition: mov.c:6145
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: avcodec.h:3929
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1477
void ff_rfps_calculate(AVFormatContext *ic)
Definition: utils.c:3393
int64_t time_offset
time offset of the edit list entries
Definition: isom.h:187
static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4375
unsigned int keyframe_count
Definition: isom.h:184
MOVIndexRange * index_ranges
Definition: isom.h:191
AVSubsampleEncryptionInfo * subsamples
An array of subsample encryption info specifying how parts of the sample are encrypted.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx)
Init a timecode struct with the passed parameters.
Definition: timecode.c:184
int64_t first_tfra_pts
Definition: isom.h:130
const uint16_t avpriv_ac3_channel_layout_tab[8]
Map audio coding mode (acmod) to channel layout mask.
Definition: ac3tab.c:89
static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1609
static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2575
uint8_t * auxiliary_info_sizes
Definition: isom.h:120
static int mov_rewrite_dvd_sub_extradata(AVStream *st)
Definition: mov.c:2269
#define AVINDEX_KEYFRAME
Definition: avformat.h:810
int * extradata_size
Definition: isom.h:219
const AVCodecTag ff_codec_movdata_tags[]
Definition: isom.c:377
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:258
static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition: mov.c:2239
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:215
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition: dict.h:69
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:1554
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1591
unsigned int ctts_count
Definition: isom.h:166
static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5293
An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE bytes worth of palette...
Definition: avcodec.h:1158
int64_t tfdt_dts
Definition: isom.h:131
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:2159
static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:960
static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5386
static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5185
static int mov_parse_auxiliary_info(MOVContext *c, MOVStreamContext *sc, AVIOContext *pb, MOVEncryptionIndex *encryption_index)
Definition: mov.c:6078
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
AVAudioServiceType
Definition: avcodec.h:806
int stsc_sample
Definition: isom.h:172
#define AV_RB16
Definition: intreadwrite.h:53
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:769
#define AVERROR(e)
Definition: error.h:43
static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3002
int atom_depth
Definition: isom.h:278
uint32_t num_key_ids
The number of key IDs.
static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5425
static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1832
static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1837
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:804
MOVIndexRange * current_index_range
Definition: isom.h:192
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:188
Display matrix.
enum AVColorPrimaries color_primaries
Definition: avcodec.h:3987
char * url
input or output URL.
Definition: avformat.h:1447
int video_delay
Video only.
Definition: avcodec.h:3995
const char * r
Definition: vf_curves.c:114
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
int * keyframes
Definition: isom.h:185
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:559
#define av_fourcc2str(fourcc)
Definition: avutil.h:348
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3896
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1428
AVFormatContext * fc
Definition: isom.h:245
static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
Definition: mov.c:4112
simple assert() macros that are a bit more flexible than ISO C assert().
static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4726
#define FFNABS(a)
Negative Absolute value.
Definition: common.h:81
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:236
int handbrake_version
Definition: isom.h:261
int ctts_sample
Definition: isom.h:178
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition: aes.c:31
static int ff_mpa_check_header(uint32_t header)
uint8_t * av_encryption_info_add_side_data(const AVEncryptionInfo *info, size_t *size)
Allocates and initializes side data that holds a copy of the given encryption info.
#define AES_CTR_KEY_SIZE
Definition: aes_ctr.h:30
int skip_samples
Number of samples to skip at the start of the frame decoded from the next packet. ...
Definition: avformat.h:1142
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
int keyframe_absent
Definition: isom.h:183
static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5001
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:947
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:481
#define FFMAX(a, b)
Definition: common.h:94
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
int16_t nlvl_from
Definition: isom.h:79
#define MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES
Definition: isom.h:328
int min_distance
Minimum distance between this and the previous keyframe, used to avoid unneeded searching.
Definition: avformat.h:816
#define fail()
Definition: checkasm.h:117
static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
Definition: mov.c:1409
AVMasteringDisplayMetadata * av_mastering_display_metadata_alloc(void)
Copyright (c) 2016 Neil Birkbeck neil.birkbeck@gmail.com
void * audible_fixed_key
Definition: isom.h:284
const AVCodecTag ff_codec_movsubtitle_tags[]
Definition: isom.c:370
int64_t min_corrected_pts
minimum Composition time shown by the edits excluding empty edits.
Definition: isom.h:188
static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:994
#define MIN_DATA_ENTRY_BOX_SIZE
Definition: mov.c:577
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1451
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
Definition: pixdesc.c:2791
static int search_frag_timestamp(MOVFragmentIndex *frag_index, AVStream *st, int64_t timestamp)
Definition: mov.c:1277
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3918
Only parse headers, do not repack.
Definition: avformat.h:794
int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
Definition: mov.c:2475
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:638
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array through a pointer to a pointer.
Definition: mem.c:205
struct AVAESCTR * av_aes_ctr_alloc(void)
Allocate an AVAESCTR context.
Definition: aes_ctr.c:36
static float distance(float x, float y, int band)
static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4482
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:451
static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6852
AVContentLightMetadata * av_content_light_metadata_alloc(size_t *size)
Allocate an AVContentLightMetadata structure and set its fields to default values.
static int aax_filter(uint8_t *input, int size, MOVContext *c)
Definition: mov.c:1094
static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1556
#define MAX_REORDER_DELAY
Definition: mov.c:3338
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:450
AVContentLightMetadata * coll
Definition: isom.h:229
common internal API header
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1407
static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1424
uint32_t bound_bottom
Distance from the bottom edge.
Definition: spherical.h:170
int ff_generate_avci_extradata(AVStream *st)
Generate standard extradata for AVC-Intra based on width/height and field order.
Definition: utils.c:5357
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
Definition: mov.c:7915
uint8_t file_key[20]
Definition: isom.h:280
static int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
Definition: mov.c:2717
static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:80
int block_align
Audio only.
Definition: avcodec.h:4017
static av_const double hypot(double x, double y)
Definition: libm.h:366
struct AVAES * aes_decrypt
Definition: isom.h:286
static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2909
#define ss(width, name, subs,...)
Definition: cbs_vp9.c:261
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5462
struct AVEncryptionInitInfo * next
An optional pointer to the next initialization info in the list.
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition: spherical.h:65
audio channel layout utility functions
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0...
Definition: utils.c:3299
unsigned int avio_rb24(AVIOContext *s)
Definition: aviobuf.c:793
static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4641
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
Spherical video.
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define FFMIN(a, b)
Definition: common.h:96
MOVFragmentStreamInfo * stream_info
Definition: isom.h:141
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as stream side data.
Definition: utils.c:5508
AVStereo3DType
List of possible 3D Types.
Definition: stereo3d.h:51
AVRational min_luminance
Min luminance of mastering display (cd/m^2).
static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1108
#define width
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that&#39;s been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:76
static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5254
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
char * dir
Definition: isom.h:76
static int mov_stsc_index_valid(unsigned int index, unsigned int count)
Definition: mov.c:2711
static int update_frag_index(MOVContext *c, int64_t offset)
Definition: mov.c:1311
void av_sha_update(struct AVSHA *ctx, const uint8_t *data, unsigned int len)
Update hash value.
Definition: sha.c:315
static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6022
int id
Definition: isom.h:64
uint8_t auxiliary_info_default_size
Definition: isom.h:122
static int cenc_filter(MOVContext *mov, AVStream *st, MOVStreamContext *sc, AVPacket *pkt, int current_index)
Definition: mov.c:6644
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition: avcodec.h:1340
int decryption_key_len
Definition: isom.h:288
static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1716
uint32_t bound_right
Distance from the right edge.
Definition: spherical.h:169
#define FLAGS
Definition: mov.c:8022
static const struct ColorPrimaries color_primaries[AVCOL_PRI_NB]
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
int32_t
static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
Definition: mov.c:7200
AVFormatContext * ctx
Definition: movenc.c:48
int audible_fixed_key_size
Definition: isom.h:285
static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4600
static void mov_fix_index(MOVContext *mov, AVStream *st)
Fix st->index_entries, so that it contains only the entries (and the entries which are needed to deco...
Definition: mov.c:3446
static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1748
int advanced_editlist
Definition: isom.h:266
static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4688
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1667
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
Definition: mov.c:1218
char * path
Definition: isom.h:75
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:72
int time_scale
Definition: isom.h:186
#define s(width, name)
Definition: cbs_vp9.c:257
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition: mem.c:476
#define AV_RL32
Definition: intreadwrite.h:146
uint64_t moof_offset
Definition: isom.h:93
MOVStts * ctts_data
Definition: isom.h:168
#define OFFSET(x)
Definition: mov.c:8021
int32_t yaw
Rotation around the up vector [-180, 180].
Definition: spherical.h:126
#define MOV_TRUN_SAMPLE_DURATION
Definition: isom.h:315
AVDictionary * metadata
Definition: avformat.h:938
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, int size)
Allocate new information from stream.
Definition: utils.c:5544
unsigned size
Definition: isom.h:105
enum AVCodecID codec_id
Definition: vaapi_decode.c:364
#define AV_CH_FRONT_CENTER
enum AVColorRange color_range
Video only.
Definition: avcodec.h:3986
int ignore_editlist
Definition: isom.h:265
MOVFragmentIndexItem * item
Definition: isom.h:149
int64_t * chunk_offsets
Definition: isom.h:163
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mov.c:7757
static int mov_read_close(AVFormatContext *s)
Definition: mov.c:7240
unsigned int index
Definition: isom.h:111
static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
This function reads atom content and puts data in extradata without tag nor size unlike mov_read_extr...
Definition: mov.c:1895
MOVFragmentIndex frag_index
Definition: isom.h:277
if(ret< 0)
Definition: vf_mcdeint.c:279
int ff_mov_read_chan(AVFormatContext *s, AVIOContext *pb, AVStream *st, int64_t size)
Read &#39;chan&#39; tag from the input stream.
Definition: mov_chan.c:547
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:842
offset must point to a pointer immediately followed by an int for the length
Definition: opt.h:229
#define FF_MOV_FLAG_MFRA_PTS
Definition: isom.h:364
static int cenc_decrypt(MOVContext *c, MOVStreamContext *sc, AVEncryptionInfo *sample, uint8_t *input, int size)
Definition: mov.c:6588
the normal 2^n-1 "JPEG" YUV ranges
Definition: pixfmt.h:512
static int mov_read_av1c(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5265
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
Definition: mov_esds.c:23
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:548
#define mc
uint32_t padding
Number of pixels to pad from the edge of each cube face.
Definition: spherical.h:182
int64_t duration
duration of the longest track
Definition: isom.h:247
int ff_mov_lang_to_iso639(unsigned code, char to[4])
Definition: isom.c:435
static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6551
Stream structure.
Definition: avformat.h:874
static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
Definition: mov.c:180
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
AVSphericalProjection
Projection of the video surface(s) on a sphere.
Definition: spherical.h:51
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
Definition: mov.c:281
Content light level (based on CTA-861.3).
Definition: avcodec.h:1347
unsigned duration
Definition: isom.h:104
DVDemuxContext * dv_demux
Definition: isom.h:254
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
int timecode_track
Definition: isom.h:201
int * sample_sizes
Definition: isom.h:182
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: avcodec.h:1167
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
Definition: mov.c:7969
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t dts)
add frame for rfps calculation.
Definition: utils.c:3333
static const uint32_t mac_to_unicode[128]
Definition: mov.c:139
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:819
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:180
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:578
#define av_bswap32
Definition: bswap.h:33
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:163
int ff_get_qtpalette(int codec_id, AVIOContext *pb, uint32_t *palette)
Retrieve the palette (or "color table" in QuickTime terms), either from the video sample description...
Definition: qtpalette.c:31
unsigned duration
Definition: isom.h:96
Views are on top of each other.
Definition: stereo3d.h:79
MOVSbgp * rap_group
Definition: isom.h:212
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t *buf, int buf_size, int64_t pos)
Definition: dv.c:364
const AVCodecTag ff_codec_movaudio_tags[]
Definition: isom.c:313
int duration
Definition: isom.h:58
static int mov_read_pssh(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6339
static void mov_read_chapters(AVFormatContext *s)
Definition: mov.c:7060
Timecode helpers header.
AVIOContext * pb
I/O context.
Definition: avformat.h:1393
static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:2074
int * chapter_tracks
Definition: isom.h:262
unsigned int stsz_sample_size
always contains sample size from stsz atom
Definition: isom.h:180
static int read_tfra(MOVContext *mov, AVIOContext *f)
Definition: mov.c:7355
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition: rational.h:71
Public header for SHA-1 & SHA-256 hash function implementations.
static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:788
unsigned trex_count
Definition: isom.h:259
#define MOV_TRUN_FIRST_SAMPLE_FLAGS
Definition: isom.h:314
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:598
#define AV_CH_FRONT_LEFT
static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4323
timecode wraps after 24 hours
Definition: timecode.h:37
int enable_drefs
Definition: isom.h:289
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition: sha.c:45
static int64_t get_frag_time(MOVFragmentIndex *frag_index, int index, int track_id)
Definition: mov.c:1256
int64_t data_size
Definition: isom.h:207
static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5852
int has_looked_for_mfra
Definition: isom.h:276
void * buf
Definition: avisynth_c.h:690
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
uint32_t type
Definition: isom.h:74
int nb_index_entries
Definition: avformat.h:1105
unsigned int count
Definition: isom.h:57
MOVStts * stts_data
Definition: isom.h:165
double value
Definition: eval.c:98
MOVEncryptionIndex * encryption_index
Definition: isom.h:133
Describe the class of an AVClass context structure.
Definition: log.h:67
static int find_prev_closest_index(AVStream *st, AVIndexEntry *e_old, int nb_old, MOVStts *ctts_data, int64_t ctts_count, int64_t timestamp_pts, int flag, int64_t *index, int64_t *ctts_index, int64_t *ctts_sample)
Find the closest previous frame to the timestamp_pts, in e_old index entries.
Definition: mov.c:3160
static void skip_bits(GetBitContext *s, int n)
Definition: get_bits.h:460
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
int index
Definition: gxfenc.c:89
unsigned int bytes_of_protected_data
The number of bytes that are protected.
int32_t roll
Rotation around the forward vector [-180, 180].
Definition: spherical.h:128
Rational number (pair of numerator and denominator).
Definition: rational.h:58
unsigned int aax_mode
&#39;aax&#39; file has been detected
Definition: isom.h:279
#define isnan(x)
Definition: libm.h:340
#define AV_DISPOSITION_TIMED_THUMBNAILS
The stream is sparse, and contains thumbnail images, often corresponding to chapter markers...
Definition: avformat.h:847
static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1721
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:277
MOVFragment fragment
current fragment in moof atom
Definition: isom.h:257
AVFieldOrder
Definition: avcodec.h:1511
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:615
static void mov_estimate_video_delay(MOVContext *c, AVStream *st)
Definition: mov.c:3339
AVRational display_aspect_ratio
display aspect ratio (0 if unknown)
Definition: avformat.h:1225
int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition: avpacket.c:295
int64_t track_end
used for dts generation in fragmented movie files
Definition: isom.h:209
Definition: isom.h:82
static enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
Compute codec id for &#39;lpcm&#39; tag.
Definition: isom.h:370
int use_mfra_for
Definition: isom.h:275
static av_always_inline void flac_parse_block_header(const uint8_t *block_header, int *last, int *type, int *size)
Parse the metadata block parameters from the header.
Definition: flac.h:145
static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:2130
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:101
static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len, char *dst, int dstlen)
Definition: mov.c:158
#define MOV_TFHD_DEFAULT_FLAGS
Definition: isom.h:309
static int mov_read_schm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6449
static int mov_read_tenc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6480
This side data contains encryption info for how to decrypt the packet.
Definition: avcodec.h:1367
#define FF_COMPLIANCE_STRICT
Strictly conform to all the things in the spec no matter what consequences.
Definition: avcodec.h:2594
#define snprintf
Definition: snprintf.h:34
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:458
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4403
#define FF_MOV_FLAG_MFRA_AUTO
Definition: isom.h:362
int64_t time
Definition: isom.h:69
int pb_is_copied
Definition: isom.h:159
#define MOV_TRUN_SAMPLE_FLAGS
Definition: isom.h:317
This structure contains the data a format has to probe a file.
Definition: avformat.h:448
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition: get_bits.h:531
#define TAG_IS_AVCI(tag)
Definition: isom.h:340
#define MOV_TFHD_STSD_ID
Definition: isom.h:306
static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2768
AVFormatContext * dv_fctx
Definition: isom.h:255
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes...
Definition: avstring.c:93
unsigned int stsc_index
Definition: isom.h:171
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
int seek_preroll
Audio only.
Definition: avcodec.h:4040
uint32_t subsample_count
uint64_t implicit_offset
Definition: isom.h:94
static int64_t pts
#define flags(name, subs,...)
Definition: cbs_av1.c:610
AVStereo3D * stereo3d
Definition: isom.h:225
static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
Definition: mov.c:2991
unsigned int per_sample_iv_size
Definition: isom.h:237
static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4456
#define AV_CH_SIDE_RIGHT
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum)
Load timecode string in buf.
Definition: timecode.c:84
unsigned * stps_data
partial sync sample for mpeg-2 open gop
Definition: isom.h:174
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition: rational.c:106
uint32_t bound_top
Distance from the top edge.
Definition: spherical.h:168
the normal 219*2^(n-8) "MPEG" YUV ranges
Definition: pixfmt.h:511
static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:984
static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:100
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition: aviobuf.c:1051
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:923
int64_t sidx_pts
Definition: isom.h:129
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
int sample_rate
Audio only.
Definition: avcodec.h:4010
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:460
static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1726
MPEG Audio header decoder.
A reference to a data buffer.
Definition: buffer.h:81
int start_pad
amount of samples to skip due to enc-dec delay
Definition: isom.h:210
int trak_index
Index of the current &#39;trak&#39;.
Definition: isom.h:251
negative time values are allowed
Definition: timecode.h:38
full parsing and repack
Definition: avformat.h:793
Main libavformat public API header.
int32_t * display_matrix
Definition: isom.h:224
int
AVIOContext * pb
Definition: isom.h:158
static void fix_index_entry_timestamps(AVStream *st, int end_index, int64_t end_ts, int64_t *frame_duration_buffer, int frame_duration_buffer_size)
Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index) by subtracting end_ts successively by the amounts given in frame_duration_buffer.
Definition: mov.c:3296
static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
An strf atom is a BITMAPINFOHEADER struct.
Definition: mov.c:1963
#define AV_PKT_FLAG_DISCARD
Flag is used to discard packets which are required to maintain valid decoder state but are not requir...
Definition: avcodec.h:1484
unsigned int bytes_per_frame
Definition: isom.h:193
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
unsigned flags
Definition: isom.h:98
int bitrates_count
Definition: isom.h:273
uint8_t * key_id
The ID of the key used to encrypt the packet.
static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
Definition: mov.c:7175
#define MOV_TFHD_BASE_DATA_OFFSET
Definition: isom.h:305
static int ref[MAX_W *MAX_W]
Definition: jpeg2000dwt.c:107
int64_t size
Definition: isom.h:84
enum AVSphericalProjection projection
Projection type.
Definition: spherical.h:86
static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5337
int export_xmp
Definition: isom.h:271
int seek_individually
Definition: isom.h:268
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:81
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
static const MOVParseTableEntry mov_default_parse_table[]
Definition: mov.c:6756
static int get_edit_list_entry(MOVContext *mov, const MOVStreamContext *msc, unsigned int edit_list_index, int64_t *edit_list_media_time, int64_t *edit_list_duration, int64_t global_timescale)
Get ith edit list entry (media time, duration).
Definition: mov.c:3118
static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, uint32_t value, int flags)
Definition: mov.c:7161
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:913
#define flag(name)
Definition: cbs_av1.c:602
static double c[64]
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
Definition: pixdesc.c:2815
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set that converts the value to a string and stores it...
Definition: dict.c:147
static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:926
unsigned int stps_count
Definition: isom.h:173
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:927
int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0 and f...
Definition: utils.c:3317
unsigned int chunk_count
Definition: isom.h:162
#define AV_WL16(p, v)
Definition: intreadwrite.h:412
Stereoscopic video.
uint8_t * data
Key-system specific initialization data.
static int mov_codec_id(AVStream *st, uint32_t format)
Definition: mov.c:2039
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:925
int den
Denominator.
Definition: rational.h:60
int avpriv_dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
Definition: dv.c:347
int64_t start
Definition: isom.h:153
unsigned meta_keys_count
Definition: isom.h:253
static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
Definition: mov.c:231
#define MKBETAG(a, b, c, d)
Definition: common.h:367
static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1986
uint32_t palette[256]
Definition: isom.h:205
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:782
unsigned stsd_id
Definition: isom.h:95
static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
Definition: mov.c:7896
unsigned int index_entries_allocated_size
Definition: avformat.h:1106
MOVEncryptionIndex * encryption_index
Definition: isom.h:239
#define av_free(p)
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition: avformat.h:477
static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index, int id, int entries)
Definition: mov.c:1368
static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:2368
char * value
Definition: dict.h:87
int eof_reached
true if eof reached
Definition: avio.h:239
static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1711
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:85
as in Berlin toast format
Definition: avcodec.h:576
int len
static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum AVCodecID codec_id)
Definition: mov.c:1680
unsigned int stts_count
Definition: isom.h:164
int av_aes_ctr_init(struct AVAESCTR *a, const uint8_t *key)
Initialize an AVAESCTR context.
Definition: aes_ctr.c:69
unsigned int sample_size
may contain value calculated from stsd or value from stsz atom
Definition: isom.h:179
static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5538
uint32_t type
Definition: mov.c:71
void * priv_data
Format private data.
Definition: avformat.h:1379
static int mov_read_mfra(MOVContext *c, AVIOContext *f)
Definition: mov.c:7410
uint8_t file_iv[20]
Definition: isom.h:281
static const AVClass mov_class
Definition: mov.c:8068
#define lrint
Definition: tablegen.h:53
uint32_t bound_left
Distance from the left edge.
Definition: spherical.h:167
static int64_t get_stream_info_time(MOVFragmentStreamInfo *frag_stream_info)
Definition: mov.c:1242
uint64_t layout
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: avcodec.h:3942
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3914
#define MOV_TRUN_DATA_OFFSET
Definition: isom.h:313
int64_t next_root_atom
offset of the next root atom
Definition: isom.h:269
int last_stsd_index
Definition: isom.h:220
unsigned int nb_encrypted_samples
Definition: isom.h:117
int channels
Audio only.
Definition: avcodec.h:4006
unsigned int nb_chapter_tracks
Definition: isom.h:263
int time_scale
Definition: isom.h:246
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1444
static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1932
Definition: isom.h:67
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
int pseudo_stream_id
-1 means demux all ids
Definition: isom.h:196
#define AV_CH_FRONT_RIGHT
static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, AVCodecParameters *par, uint8_t *buf)
Definition: mov.c:1658
double av_display_rotation_get(const int32_t matrix[9])
Extract the rotation component of the transformation matrix.
Definition: display.c:34
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1466
int ffindex
AVStream index.
Definition: isom.h:160
uint8_t ** extradata
extradata array (and size) for multiple stsd
Definition: isom.h:218
FILE * out
Definition: movenc.c:54
int use_absolute_path
Definition: isom.h:264
AVEncryptionInfo * av_encryption_info_alloc(uint32_t subsample_count, uint32_t key_id_size, uint32_t iv_size)
Allocates an AVEncryptionInfo structure and sub-pointers to hold the given number of subsamples...
#define av_freep(p)
void INT64 INT64 count
Definition: avisynth_c.h:690
static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4662
void INT64 start
Definition: avisynth_c.h:690
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:647
static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2640
static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
Definition: mov.c:3418
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:170
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1021
unsigned size
Definition: isom.h:97
#define av_malloc_array(a, b)
int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a string from pb into buf.
Definition: aviobuf.c:879
void av_aes_ctr_set_full_iv(struct AVAESCTR *a, const uint8_t *iv)
Forcefully change the "full" 16-byte iv, including the counter.
Definition: aes_ctr.c:48
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:358
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:3904
static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1706
int64_t duration_for_fps
Definition: isom.h:215
#define AV_CH_SIDE_LEFT
#define FFSWAP(type, a, b)
Definition: common.h:99
const char int length
Definition: avisynth_c.h:768
static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2817
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:329
int stream_index
Definition: avcodec.h:1447
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:903
static double cr(void *priv, double x, double y)
Definition: vf_geq.c:113
#define MKTAG(a, b, c, d)
Definition: common.h:366
int moov_retry
Definition: isom.h:274
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:929
static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
Definition: mov.c:4184
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:998
#define ID3v1_GENRE_MAX
Definition: id3v1.h:29
const char *const ff_id3v1_genre_str[ID3v1_GENRE_MAX+1]
ID3v1 genres.
Definition: id3v1.c:27
enum AVCodecID id
unsigned MaxFALL
Max average light level per frame (cd/m^2).
This structure stores compressed data.
Definition: avcodec.h:1422
static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3068
size_t auxiliary_info_sample_count
Definition: isom.h:121
mode
Use these values in ebur128_init (or&#39;ed).
Definition: ebur128.h:83
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1438
int found_hdlr_mdta
&#39;hdlr&#39; atom with type &#39;mdta&#39; has been found
Definition: isom.h:250
int has_sidx
Definition: isom.h:234
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition: avformat.h:956
uint8_t * system_id
A unique identifier for the key system this is for, can be NULL if it is not known.
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
Definition: isom.h:73
static uint32_t yuv_to_rgba(uint32_t ycbcr)
Definition: mov.c:2253
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
#define MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC
Definition: isom.h:321
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
Definition: mem.c:191
This side data should be associated with an audio stream and corresponds to enum AVAudioServiceType.
Definition: avcodec.h:1232
static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6244