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