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