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