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