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