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