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