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