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