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