FFmpeg  4.4.5
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  }
5370  sc->elst_count = i;
5371 
5372  return 0;
5373 }
5374 
5376 {
5377  MOVStreamContext *sc;
5378 
5379  if (c->fc->nb_streams < 1)
5380  return AVERROR_INVALIDDATA;
5381  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5382  sc->timecode_track = avio_rb32(pb);
5383  return 0;
5384 }
5385 
5387 {
5388  AVStream *st;
5389  int ret;
5390 
5391  if (c->fc->nb_streams < 1)
5392  return 0;
5393  st = c->fc->streams[c->fc->nb_streams - 1];
5394 
5395  if (atom.size < 4) {
5396  av_log(c->fc, AV_LOG_ERROR, "Empty AV1 Codec Configuration Box\n");
5397  return AVERROR_INVALIDDATA;
5398  }
5399 
5400  /* For now, propagate only the OBUs, if any. Once libavcodec is
5401  updated to handle isobmff style extradata this can be removed. */
5402  avio_skip(pb, 4);
5403 
5404  if (atom.size == 4)
5405  return 0;
5406 
5407  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 4);
5408  if (ret < 0)
5409  return ret;
5410 
5411  return 0;
5412 }
5413 
5415 {
5416  AVStream *st;
5417  int version, color_range, color_primaries, color_trc, color_space;
5418 
5419  if (c->fc->nb_streams < 1)
5420  return 0;
5421  st = c->fc->streams[c->fc->nb_streams - 1];
5422 
5423  if (atom.size < 5) {
5424  av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5425  return AVERROR_INVALIDDATA;
5426  }
5427 
5428  version = avio_r8(pb);
5429  if (version != 1) {
5430  av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5431  return 0;
5432  }
5433  avio_skip(pb, 3); /* flags */
5434 
5435  avio_skip(pb, 2); /* profile + level */
5436  color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5437  color_primaries = avio_r8(pb);
5438  color_trc = avio_r8(pb);
5439  color_space = avio_r8(pb);
5440  if (avio_rb16(pb)) /* codecIntializationDataSize */
5441  return AVERROR_INVALIDDATA;
5442 
5445  if (!av_color_transfer_name(color_trc))
5446  color_trc = AVCOL_TRC_UNSPECIFIED;
5447  if (!av_color_space_name(color_space))
5448  color_space = AVCOL_SPC_UNSPECIFIED;
5449 
5452  st->codecpar->color_trc = color_trc;
5453  st->codecpar->color_space = color_space;
5454 
5455  return 0;
5456 }
5457 
5459 {
5460  MOVStreamContext *sc;
5461  int i, version;
5462 
5463  if (c->fc->nb_streams < 1)
5464  return AVERROR_INVALIDDATA;
5465 
5466  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5467 
5468  if (atom.size < 5) {
5469  av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5470  return AVERROR_INVALIDDATA;
5471  }
5472 
5473  version = avio_r8(pb);
5474  if (version) {
5475  av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5476  return 0;
5477  }
5478  if (sc->mastering) {
5479  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate Mastering Display Metadata\n");
5480  return 0;
5481  }
5482 
5483  avio_skip(pb, 3); /* flags */
5484 
5486  if (!sc->mastering)
5487  return AVERROR(ENOMEM);
5488 
5489  for (i = 0; i < 3; i++) {
5490  sc->mastering->display_primaries[i][0] = av_make_q(avio_rb16(pb), 1 << 16);
5491  sc->mastering->display_primaries[i][1] = av_make_q(avio_rb16(pb), 1 << 16);
5492  }
5493  sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), 1 << 16);
5494  sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), 1 << 16);
5495 
5496  sc->mastering->max_luminance = av_make_q(avio_rb32(pb), 1 << 8);
5497  sc->mastering->min_luminance = av_make_q(avio_rb32(pb), 1 << 14);
5498 
5499  sc->mastering->has_primaries = 1;
5500  sc->mastering->has_luminance = 1;
5501 
5502  return 0;
5503 }
5504 
5506 {
5507  MOVStreamContext *sc;
5508  const int mapping[3] = {1, 2, 0};
5509  const int chroma_den = 50000;
5510  const int luma_den = 10000;
5511  int i;
5512 
5513  if (c->fc->nb_streams < 1)
5514  return AVERROR_INVALIDDATA;
5515 
5516  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5517 
5518  if (atom.size < 24) {
5519  av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5520  return AVERROR_INVALIDDATA;
5521  }
5522 
5523  if (sc->mastering) {
5524  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate Mastering Display Color Volume\n");
5525  return 0;
5526  }
5527 
5529  if (!sc->mastering)
5530  return AVERROR(ENOMEM);
5531 
5532  for (i = 0; i < 3; i++) {
5533  const int j = mapping[i];
5534  sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5535  sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5536  }
5537  sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5538  sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5539 
5540  sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5541  sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5542 
5543  sc->mastering->has_luminance = 1;
5544  sc->mastering->has_primaries = 1;
5545 
5546  return 0;
5547 }
5548 
5550 {
5551  MOVStreamContext *sc;
5552  int version;
5553 
5554  if (c->fc->nb_streams < 1)
5555  return AVERROR_INVALIDDATA;
5556 
5557  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5558 
5559  if (atom.size < 5) {
5560  av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5561  return AVERROR_INVALIDDATA;
5562  }
5563 
5564  version = avio_r8(pb);
5565  if (version) {
5566  av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5567  return 0;
5568  }
5569  avio_skip(pb, 3); /* flags */
5570 
5571  if (sc->coll){
5572  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate COLL\n");
5573  return 0;
5574  }
5575 
5577  if (!sc->coll)
5578  return AVERROR(ENOMEM);
5579 
5580  sc->coll->MaxCLL = avio_rb16(pb);
5581  sc->coll->MaxFALL = avio_rb16(pb);
5582 
5583  return 0;
5584 }
5585 
5587 {
5588  MOVStreamContext *sc;
5589 
5590  if (c->fc->nb_streams < 1)
5591  return AVERROR_INVALIDDATA;
5592 
5593  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5594 
5595  if (atom.size < 4) {
5596  av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5597  return AVERROR_INVALIDDATA;
5598  }
5599 
5600  if (sc->coll){
5601  av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicate CLLI/COLL\n");
5602  return 0;
5603  }
5604 
5606  if (!sc->coll)
5607  return AVERROR(ENOMEM);
5608 
5609  sc->coll->MaxCLL = avio_rb16(pb);
5610  sc->coll->MaxFALL = avio_rb16(pb);
5611 
5612  return 0;
5613 }
5614 
5616 {
5617  AVStream *st;
5618  MOVStreamContext *sc;
5619  enum AVStereo3DType type;
5620  int mode;
5621 
5622  if (c->fc->nb_streams < 1)
5623  return 0;
5624 
5625  st = c->fc->streams[c->fc->nb_streams - 1];
5626  sc = st->priv_data;
5627 
5628  if (atom.size < 5) {
5629  av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5630  return AVERROR_INVALIDDATA;
5631  }
5632 
5633  if (sc->stereo3d)
5634  return AVERROR_INVALIDDATA;
5635 
5636  avio_skip(pb, 4); /* version + flags */
5637 
5638  mode = avio_r8(pb);
5639  switch (mode) {
5640  case 0:
5641  type = AV_STEREO3D_2D;
5642  break;
5643  case 1:
5645  break;
5646  case 2:
5648  break;
5649  default:
5650  av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5651  return 0;
5652  }
5653 
5654  sc->stereo3d = av_stereo3d_alloc();
5655  if (!sc->stereo3d)
5656  return AVERROR(ENOMEM);
5657 
5658  sc->stereo3d->type = type;
5659  return 0;
5660 }
5661 
5663 {
5664  AVStream *st;
5665  MOVStreamContext *sc;
5666  int size, version, layout;
5667  int32_t yaw, pitch, roll;
5668  uint32_t l = 0, t = 0, r = 0, b = 0;
5669  uint32_t tag, padding = 0;
5670  enum AVSphericalProjection projection;
5671 
5672  if (c->fc->nb_streams < 1)
5673  return 0;
5674 
5675  st = c->fc->streams[c->fc->nb_streams - 1];
5676  sc = st->priv_data;
5677 
5678  if (atom.size < 8) {
5679  av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5680  return AVERROR_INVALIDDATA;
5681  }
5682 
5683  size = avio_rb32(pb);
5684  if (size <= 12 || size > atom.size)
5685  return AVERROR_INVALIDDATA;
5686 
5687  tag = avio_rl32(pb);
5688  if (tag != MKTAG('s','v','h','d')) {
5689  av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5690  return 0;
5691  }
5692  version = avio_r8(pb);
5693  if (version != 0) {
5694  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5695  version);
5696  return 0;
5697  }
5698  avio_skip(pb, 3); /* flags */
5699  avio_skip(pb, size - 12); /* metadata_source */
5700 
5701  size = avio_rb32(pb);
5702  if (size > atom.size)
5703  return AVERROR_INVALIDDATA;
5704 
5705  tag = avio_rl32(pb);
5706  if (tag != MKTAG('p','r','o','j')) {
5707  av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5708  return 0;
5709  }
5710 
5711  size = avio_rb32(pb);
5712  if (size > atom.size)
5713  return AVERROR_INVALIDDATA;
5714 
5715  tag = avio_rl32(pb);
5716  if (tag != MKTAG('p','r','h','d')) {
5717  av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5718  return 0;
5719  }
5720  version = avio_r8(pb);
5721  if (version != 0) {
5722  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5723  version);
5724  return 0;
5725  }
5726  avio_skip(pb, 3); /* flags */
5727 
5728  /* 16.16 fixed point */
5729  yaw = avio_rb32(pb);
5730  pitch = avio_rb32(pb);
5731  roll = avio_rb32(pb);
5732 
5733  size = avio_rb32(pb);
5734  if (size > atom.size)
5735  return AVERROR_INVALIDDATA;
5736 
5737  tag = avio_rl32(pb);
5738  version = avio_r8(pb);
5739  if (version != 0) {
5740  av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5741  version);
5742  return 0;
5743  }
5744  avio_skip(pb, 3); /* flags */
5745  switch (tag) {
5746  case MKTAG('c','b','m','p'):
5747  layout = avio_rb32(pb);
5748  if (layout) {
5749  av_log(c->fc, AV_LOG_WARNING,
5750  "Unsupported cubemap layout %d\n", layout);
5751  return 0;
5752  }
5753  projection = AV_SPHERICAL_CUBEMAP;
5754  padding = avio_rb32(pb);
5755  break;
5756  case MKTAG('e','q','u','i'):
5757  t = avio_rb32(pb);
5758  b = avio_rb32(pb);
5759  l = avio_rb32(pb);
5760  r = avio_rb32(pb);
5761 
5762  if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5763  av_log(c->fc, AV_LOG_ERROR,
5764  "Invalid bounding rectangle coordinates "
5765  "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5766  return AVERROR_INVALIDDATA;
5767  }
5768 
5769  if (l || t || r || b)
5770  projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5771  else
5772  projection = AV_SPHERICAL_EQUIRECTANGULAR;
5773  break;
5774  default:
5775  av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5776  return 0;
5777  }
5778 
5780  if (!sc->spherical)
5781  return AVERROR(ENOMEM);
5782 
5783  sc->spherical->projection = projection;
5784 
5785  sc->spherical->yaw = yaw;
5786  sc->spherical->pitch = pitch;
5787  sc->spherical->roll = roll;
5788 
5789  sc->spherical->padding = padding;
5790 
5791  sc->spherical->bound_left = l;
5792  sc->spherical->bound_top = t;
5793  sc->spherical->bound_right = r;
5794  sc->spherical->bound_bottom = b;
5795 
5796  return 0;
5797 }
5798 
5800 {
5801  int ret = 0;
5802  uint8_t *buffer = av_malloc(len + 1);
5803  const char *val;
5804 
5805  if (!buffer)
5806  return AVERROR(ENOMEM);
5807  buffer[len] = '\0';
5808 
5809  ret = ffio_read_size(pb, buffer, len);
5810  if (ret < 0)
5811  goto out;
5812 
5813  /* Check for mandatory keys and values, try to support XML as best-effort */
5814  if (!sc->spherical &&
5815  av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5816  (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5817  av_stristr(val, "true") &&
5818  (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5819  av_stristr(val, "true") &&
5820  (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5821  av_stristr(val, "equirectangular")) {
5823  if (!sc->spherical)
5824  goto out;
5825 
5827 
5828  if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5829  enum AVStereo3DType mode;
5830 
5831  if (av_stristr(buffer, "left-right"))
5833  else if (av_stristr(buffer, "top-bottom"))
5835  else
5836  mode = AV_STEREO3D_2D;
5837 
5838  sc->stereo3d = av_stereo3d_alloc();
5839  if (!sc->stereo3d)
5840  goto out;
5841 
5842  sc->stereo3d->type = mode;
5843  }
5844 
5845  /* orientation */
5846  val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5847  if (val)
5848  sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5849  val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5850  if (val)
5851  sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5852  val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5853  if (val)
5854  sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5855  }
5856 
5857 out:
5858  av_free(buffer);
5859  return ret;
5860 }
5861 
5863 {
5864  AVStream *st;
5865  MOVStreamContext *sc;
5866  int64_t ret;
5867  uint8_t uuid[16];
5868  static const uint8_t uuid_isml_manifest[] = {
5869  0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5870  0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5871  };
5872  static const uint8_t uuid_xmp[] = {
5873  0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5874  0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5875  };
5876  static const uint8_t uuid_spherical[] = {
5877  0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5878  0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5879  };
5880 
5881  if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5882  return AVERROR_INVALIDDATA;
5883 
5884  if (c->fc->nb_streams < 1)
5885  return 0;
5886  st = c->fc->streams[c->fc->nb_streams - 1];
5887  sc = st->priv_data;
5888 
5889  ret = ffio_read_size(pb, uuid, sizeof(uuid));
5890  if (ret < 0)
5891  return ret;
5892  if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5893  uint8_t *buffer, *ptr;
5894  char *endptr;
5895  size_t len = atom.size - sizeof(uuid);
5896 
5897  if (len < 4) {
5898  return AVERROR_INVALIDDATA;
5899  }
5900  ret = avio_skip(pb, 4); // zeroes
5901  len -= 4;
5902 
5903  buffer = av_mallocz(len + 1);
5904  if (!buffer) {
5905  return AVERROR(ENOMEM);
5906  }
5907  ret = ffio_read_size(pb, buffer, len);
5908  if (ret < 0) {
5909  av_free(buffer);
5910  return ret;
5911  }
5912 
5913  ptr = buffer;
5914  while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5915  ptr += sizeof("systemBitrate=\"") - 1;
5916  c->bitrates_count++;
5917  c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5918  if (!c->bitrates) {
5919  c->bitrates_count = 0;
5920  av_free(buffer);
5921  return AVERROR(ENOMEM);
5922  }
5923  errno = 0;
5924  ret = strtol(ptr, &endptr, 10);
5925  if (ret < 0 || errno || *endptr != '"') {
5926  c->bitrates[c->bitrates_count - 1] = 0;
5927  } else {
5928  c->bitrates[c->bitrates_count - 1] = ret;
5929  }
5930  }
5931 
5932  av_free(buffer);
5933  } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5934  uint8_t *buffer;
5935  size_t len = atom.size - sizeof(uuid);
5936  if (c->export_xmp) {
5937  buffer = av_mallocz(len + 1);
5938  if (!buffer) {
5939  return AVERROR(ENOMEM);
5940  }
5941  ret = ffio_read_size(pb, buffer, len);
5942  if (ret < 0) {
5943  av_free(buffer);
5944  return ret;
5945  }
5946  buffer[len] = '\0';
5947  av_dict_set(&c->fc->metadata, "xmp",
5949  } else {
5950  // skip all uuid atom, which makes it fast for long uuid-xmp file
5951  ret = avio_skip(pb, len);
5952  if (ret < 0)
5953  return ret;
5954  }
5955  } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5956  size_t len = atom.size - sizeof(uuid);
5957  ret = mov_parse_uuid_spherical(sc, pb, len);
5958  if (ret < 0)
5959  return ret;
5960  if (!sc->spherical)
5961  av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5962  }
5963 
5964  return 0;
5965 }
5966 
5968 {
5969  int ret;
5970  uint8_t content[16];
5971 
5972  if (atom.size < 8)
5973  return 0;
5974 
5975  ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5976  if (ret < 0)
5977  return ret;
5978 
5979  if ( !c->found_moov
5980  && !c->found_mdat
5981  && !memcmp(content, "Anevia\x1A\x1A", 8)
5982  && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5983  c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5984  }
5985 
5986  return 0;
5987 }
5988 
5990 {
5991  uint32_t format = avio_rl32(pb);
5992  MOVStreamContext *sc;
5993  enum AVCodecID id;
5994  AVStream *st;
5995 
5996  if (c->fc->nb_streams < 1)
5997  return 0;
5998  st = c->fc->streams[c->fc->nb_streams - 1];
5999  sc = st->priv_data;
6000 
6001  switch (sc->format)
6002  {
6003  case MKTAG('e','n','c','v'): // encrypted video
6004  case MKTAG('e','n','c','a'): // encrypted audio
6005  id = mov_codec_id(st, format);
6006  if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
6007  st->codecpar->codec_id != id) {
6008  av_log(c->fc, AV_LOG_WARNING,
6009  "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
6010  (char*)&format, st->codecpar->codec_id);
6011  break;
6012  }
6013 
6014  st->codecpar->codec_id = id;
6015  sc->format = format;
6016  break;
6017 
6018  default:
6019  if (format != sc->format) {
6020  av_log(c->fc, AV_LOG_WARNING,
6021  "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
6022  (char*)&format, (char*)&sc->format);
6023  }
6024  break;
6025  }
6026 
6027  return 0;
6028 }
6029 
6030 /**
6031  * Gets the current encryption info and associated current stream context. If
6032  * we are parsing a track fragment, this will return the specific encryption
6033  * info for this fragment; otherwise this will return the global encryption
6034  * info for the current stream.
6035  */
6037 {
6038  MOVFragmentStreamInfo *frag_stream_info;
6039  AVStream *st;
6040  int i;
6041 
6042  frag_stream_info = get_current_frag_stream_info(&c->frag_index);
6043  if (frag_stream_info) {
6044  for (i = 0; i < c->fc->nb_streams; i++) {
6045  if (c->fc->streams[i]->id == frag_stream_info->id) {
6046  st = c->fc->streams[i];
6047  break;
6048  }
6049  }
6050  if (i == c->fc->nb_streams)
6051  return 0;
6052  *sc = st->priv_data;
6053 
6054  if (!frag_stream_info->encryption_index) {
6055  // If this stream isn't encrypted, don't create the index.
6056  if (!(*sc)->cenc.default_encrypted_sample)
6057  return 0;
6058  frag_stream_info->encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
6059  if (!frag_stream_info->encryption_index)
6060  return AVERROR(ENOMEM);
6061  }
6062  *encryption_index = frag_stream_info->encryption_index;
6063  return 1;
6064  } else {
6065  // No current track fragment, using stream level encryption info.
6066 
6067  if (c->fc->nb_streams < 1)
6068  return 0;
6069  st = c->fc->streams[c->fc->nb_streams - 1];
6070  *sc = st->priv_data;
6071 
6072  if (!(*sc)->cenc.encryption_index) {
6073  // If this stream isn't encrypted, don't create the index.
6074  if (!(*sc)->cenc.default_encrypted_sample)
6075  return 0;
6076  (*sc)->cenc.encryption_index = av_mallocz(sizeof(*frag_stream_info->encryption_index));
6077  if (!(*sc)->cenc.encryption_index)
6078  return AVERROR(ENOMEM);
6079  }
6080 
6081  *encryption_index = (*sc)->cenc.encryption_index;
6082  return 1;
6083  }
6084 }
6085 
6087 {
6088  int i, ret;
6089  unsigned int subsample_count;
6090  AVSubsampleEncryptionInfo *subsamples;
6091 
6092  if (!sc->cenc.default_encrypted_sample) {
6093  av_log(c->fc, AV_LOG_ERROR, "Missing schm or tenc\n");
6094  return AVERROR_INVALIDDATA;
6095  }
6096 
6098  if (!*sample)
6099  return AVERROR(ENOMEM);
6100 
6101  if (sc->cenc.per_sample_iv_size != 0) {
6102  if ((ret = ffio_read_size(pb, (*sample)->iv, sc->cenc.per_sample_iv_size)) < 0) {
6103  av_log(c->fc, AV_LOG_ERROR, "failed to read the initialization vector\n");
6105  *sample = NULL;
6106  return ret;
6107  }
6108  }
6109 
6110  if (use_subsamples) {
6111  subsample_count = avio_rb16(pb);
6112  av_free((*sample)->subsamples);
6113  (*sample)->subsamples = av_mallocz_array(subsample_count, sizeof(*subsamples));
6114  if (!(*sample)->subsamples) {
6116  *sample = NULL;
6117  return AVERROR(ENOMEM);
6118  }
6119 
6120  for (i = 0; i < subsample_count && !pb->eof_reached; i++) {
6121  (*sample)->subsamples[i].bytes_of_clear_data = avio_rb16(pb);
6122  (*sample)->subsamples[i].bytes_of_protected_data = avio_rb32(pb);
6123  }
6124 
6125  if (pb->eof_reached) {
6126  av_log(c->fc, AV_LOG_ERROR, "hit EOF while reading sub-sample encryption info\n");
6128  *sample = NULL;
6129  return AVERROR_INVALIDDATA;
6130  }
6131  (*sample)->subsample_count = subsample_count;
6132  }
6133 
6134  return 0;
6135 }
6136 
6138 {
6139  AVEncryptionInfo **encrypted_samples;
6140  MOVEncryptionIndex *encryption_index;
6141  MOVStreamContext *sc;
6142  int use_subsamples, ret;
6143  unsigned int sample_count, i, alloc_size = 0;
6144 
6145  ret = get_current_encryption_info(c, &encryption_index, &sc);
6146  if (ret != 1)
6147  return ret;
6148 
6149  if (encryption_index->nb_encrypted_samples) {
6150  // This can happen if we have both saio/saiz and senc atoms.
6151  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in senc\n");
6152  return 0;
6153  }
6154 
6155  avio_r8(pb); /* version */
6156  use_subsamples = avio_rb24(pb) & 0x02; /* flags */
6157 
6158  sample_count = avio_rb32(pb);
6159  if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
6160  return AVERROR(ENOMEM);
6161 
6162  for (i = 0; i < sample_count; i++) {
6163  unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
6164  encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
6165  min_samples * sizeof(*encrypted_samples));
6166  if (encrypted_samples) {
6167  encryption_index->encrypted_samples = encrypted_samples;
6168 
6170  c, pb, sc, &encryption_index->encrypted_samples[i], use_subsamples);
6171  } else {
6172  ret = AVERROR(ENOMEM);
6173  }
6174  if (pb->eof_reached) {
6175  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading senc\n");
6176  if (ret >= 0)
6177  av_encryption_info_free(encryption_index->encrypted_samples[i]);
6178  ret = AVERROR_INVALIDDATA;
6179  }
6180 
6181  if (ret < 0) {
6182  for (; i > 0; i--)
6183  av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
6184  av_freep(&encryption_index->encrypted_samples);
6185  return ret;
6186  }
6187  }
6188  encryption_index->nb_encrypted_samples = sample_count;
6189 
6190  return 0;
6191 }
6192 
6194 {
6195  AVEncryptionInfo **sample, **encrypted_samples;
6196  int64_t prev_pos;
6197  size_t sample_count, sample_info_size, i;
6198  int ret = 0;
6199  unsigned int alloc_size = 0;
6200 
6201  if (encryption_index->nb_encrypted_samples)
6202  return 0;
6203  sample_count = encryption_index->auxiliary_info_sample_count;
6204  if (encryption_index->auxiliary_offsets_count != 1) {
6205  av_log(c->fc, AV_LOG_ERROR, "Multiple auxiliary info chunks are not supported\n");
6206  return AVERROR_PATCHWELCOME;
6207  }
6208  if (sample_count >= INT_MAX / sizeof(*encrypted_samples))
6209  return AVERROR(ENOMEM);
6210 
6211  prev_pos = avio_tell(pb);
6212  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
6213  avio_seek(pb, encryption_index->auxiliary_offsets[0], SEEK_SET) != encryption_index->auxiliary_offsets[0]) {
6214  av_log(c->fc, AV_LOG_INFO, "Failed to seek for auxiliary info, will only parse senc atoms for encryption info\n");
6215  goto finish;
6216  }
6217 
6218  for (i = 0; i < sample_count && !pb->eof_reached; i++) {
6219  unsigned int min_samples = FFMIN(FFMAX(i + 1, 1024 * 1024), sample_count);
6220  encrypted_samples = av_fast_realloc(encryption_index->encrypted_samples, &alloc_size,
6221  min_samples * sizeof(*encrypted_samples));
6222  if (!encrypted_samples) {
6223  ret = AVERROR(ENOMEM);
6224  goto finish;
6225  }
6226  encryption_index->encrypted_samples = encrypted_samples;
6227 
6228  sample = &encryption_index->encrypted_samples[i];
6229  sample_info_size = encryption_index->auxiliary_info_default_size
6230  ? encryption_index->auxiliary_info_default_size
6231  : encryption_index->auxiliary_info_sizes[i];
6232 
6233  ret = mov_read_sample_encryption_info(c, pb, sc, sample, sample_info_size > sc->cenc.per_sample_iv_size);
6234  if (ret < 0)
6235  goto finish;
6236  }
6237  if (pb->eof_reached) {
6238  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading auxiliary info\n");
6239  ret = AVERROR_INVALIDDATA;
6240  } else {
6241  encryption_index->nb_encrypted_samples = sample_count;
6242  }
6243 
6244 finish:
6245  avio_seek(pb, prev_pos, SEEK_SET);
6246  if (ret < 0) {
6247  for (; i > 0; i--) {
6248  av_encryption_info_free(encryption_index->encrypted_samples[i - 1]);
6249  }
6250  av_freep(&encryption_index->encrypted_samples);
6251  }
6252  return ret;
6253 }
6254 
6255 /**
6256  * Tries to read the given number of bytes from the stream and puts it in a
6257  * newly allocated buffer. This reads in small chunks to avoid allocating large
6258  * memory if the file contains an invalid/malicious size value.
6259  */
6260 static int mov_try_read_block(AVIOContext *pb, size_t size, uint8_t **data)
6261 {
6262  const unsigned int block_size = 1024 * 1024;
6263  uint8_t *buffer = NULL;
6264  unsigned int alloc_size = 0, offset = 0;
6265  while (offset < size) {
6266  unsigned int new_size =
6267  alloc_size >= INT_MAX - block_size ? INT_MAX : alloc_size + block_size;
6268  uint8_t *new_buffer = av_fast_realloc(buffer, &alloc_size, new_size);
6269  unsigned int to_read = FFMIN(size, alloc_size) - offset;
6270  if (!new_buffer) {
6271  av_free(buffer);
6272  return AVERROR(ENOMEM);
6273  }
6274  buffer = new_buffer;
6275 
6276  if (avio_read(pb, buffer + offset, to_read) != to_read) {
6277  av_free(buffer);
6278  return AVERROR_INVALIDDATA;
6279  }
6280  offset += to_read;
6281  }
6282 
6283  *data = buffer;
6284  return 0;
6285 }
6286 
6288 {
6289  MOVEncryptionIndex *encryption_index;
6290  MOVStreamContext *sc;
6291  int ret;
6292  unsigned int sample_count, aux_info_type, aux_info_param;
6293 
6294  ret = get_current_encryption_info(c, &encryption_index, &sc);
6295  if (ret != 1)
6296  return ret;
6297 
6298  if (encryption_index->nb_encrypted_samples) {
6299  // This can happen if we have both saio/saiz and senc atoms.
6300  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saiz\n");
6301  return 0;
6302  }
6303 
6304  if (encryption_index->auxiliary_info_sample_count) {
6305  av_log(c->fc, AV_LOG_ERROR, "Duplicate saiz atom\n");
6306  return AVERROR_INVALIDDATA;
6307  }
6308 
6309  avio_r8(pb); /* version */
6310  if (avio_rb24(pb) & 0x01) { /* flags */
6311  aux_info_type = avio_rb32(pb);
6312  aux_info_param = avio_rb32(pb);
6313  if (sc->cenc.default_encrypted_sample) {
6314  if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
6315  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type\n");
6316  return 0;
6317  }
6318  if (aux_info_param != 0) {
6319  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saiz box with non-zero aux_info_type_parameter\n");
6320  return 0;
6321  }
6322  } else {
6323  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6324  if ((aux_info_type == MKBETAG('c','e','n','c') ||
6325  aux_info_type == MKBETAG('c','e','n','s') ||
6326  aux_info_type == MKBETAG('c','b','c','1') ||
6327  aux_info_type == MKBETAG('c','b','c','s')) &&
6328  aux_info_param == 0) {
6329  av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saiz without schm/tenc\n");
6330  return AVERROR_INVALIDDATA;
6331  } else {
6332  return 0;
6333  }
6334  }
6335  } else if (!sc->cenc.default_encrypted_sample) {
6336  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6337  return 0;
6338  }
6339 
6340  encryption_index->auxiliary_info_default_size = avio_r8(pb);
6341  sample_count = avio_rb32(pb);
6342  encryption_index->auxiliary_info_sample_count = sample_count;
6343 
6344  if (encryption_index->auxiliary_info_default_size == 0) {
6345  ret = mov_try_read_block(pb, sample_count, &encryption_index->auxiliary_info_sizes);
6346  if (ret < 0) {
6347  av_log(c->fc, AV_LOG_ERROR, "Failed to read the auxiliary info\n");
6348  return ret;
6349  }
6350  }
6351 
6352  if (encryption_index->auxiliary_offsets_count) {
6353  return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6354  }
6355 
6356  return 0;
6357 }
6358 
6360 {
6361  uint64_t *auxiliary_offsets;
6362  MOVEncryptionIndex *encryption_index;
6363  MOVStreamContext *sc;
6364  int i, ret;
6365  unsigned int version, entry_count, aux_info_type, aux_info_param;
6366  unsigned int alloc_size = 0;
6367 
6368  ret = get_current_encryption_info(c, &encryption_index, &sc);
6369  if (ret != 1)
6370  return ret;
6371 
6372  if (encryption_index->nb_encrypted_samples) {
6373  // This can happen if we have both saio/saiz and senc atoms.
6374  av_log(c->fc, AV_LOG_DEBUG, "Ignoring duplicate encryption info in saio\n");
6375  return 0;
6376  }
6377 
6378  if (encryption_index->auxiliary_offsets_count) {
6379  av_log(c->fc, AV_LOG_ERROR, "Duplicate saio atom\n");
6380  return AVERROR_INVALIDDATA;
6381  }
6382 
6383  version = avio_r8(pb); /* version */
6384  if (avio_rb24(pb) & 0x01) { /* flags */
6385  aux_info_type = avio_rb32(pb);
6386  aux_info_param = avio_rb32(pb);
6387  if (sc->cenc.default_encrypted_sample) {
6388  if (aux_info_type != sc->cenc.default_encrypted_sample->scheme) {
6389  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type\n");
6390  return 0;
6391  }
6392  if (aux_info_param != 0) {
6393  av_log(c->fc, AV_LOG_DEBUG, "Ignoring saio box with non-zero aux_info_type_parameter\n");
6394  return 0;
6395  }
6396  } else {
6397  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6398  if ((aux_info_type == MKBETAG('c','e','n','c') ||
6399  aux_info_type == MKBETAG('c','e','n','s') ||
6400  aux_info_type == MKBETAG('c','b','c','1') ||
6401  aux_info_type == MKBETAG('c','b','c','s')) &&
6402  aux_info_param == 0) {
6403  av_log(c->fc, AV_LOG_ERROR, "Saw encrypted saio without schm/tenc\n");
6404  return AVERROR_INVALIDDATA;
6405  } else {
6406  return 0;
6407  }
6408  }
6409  } else if (!sc->cenc.default_encrypted_sample) {
6410  // Didn't see 'schm' or 'tenc', so this isn't encrypted.
6411  return 0;
6412  }
6413 
6414  entry_count = avio_rb32(pb);
6415  if (entry_count >= INT_MAX / sizeof(*auxiliary_offsets))
6416  return AVERROR(ENOMEM);
6417 
6418  for (i = 0; i < entry_count && !pb->eof_reached; i++) {
6419  unsigned int min_offsets = FFMIN(FFMAX(i + 1, 1024), entry_count);
6420  auxiliary_offsets = av_fast_realloc(
6421  encryption_index->auxiliary_offsets, &alloc_size,
6422  min_offsets * sizeof(*auxiliary_offsets));
6423  if (!auxiliary_offsets) {
6424  av_freep(&encryption_index->auxiliary_offsets);
6425  return AVERROR(ENOMEM);
6426  }
6427  encryption_index->auxiliary_offsets = auxiliary_offsets;
6428 
6429  if (version == 0) {
6430  encryption_index->auxiliary_offsets[i] = avio_rb32(pb);
6431  } else {
6432  encryption_index->auxiliary_offsets[i] = avio_rb64(pb);
6433  }
6434  if (c->frag_index.current >= 0) {
6435  encryption_index->auxiliary_offsets[i] += c->fragment.base_data_offset;
6436  }
6437  }
6438 
6439  if (pb->eof_reached) {
6440  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading saio\n");
6441  av_freep(&encryption_index->auxiliary_offsets);
6442  return AVERROR_INVALIDDATA;
6443  }
6444 
6445  encryption_index->auxiliary_offsets_count = entry_count;
6446 
6447  if (encryption_index->auxiliary_info_sample_count) {
6448  return mov_parse_auxiliary_info(c, sc, pb, encryption_index);
6449  }
6450 
6451  return 0;
6452 }
6453 
6455 {
6456  AVEncryptionInitInfo *info, *old_init_info;
6457  uint8_t **key_ids;
6458  AVStream *st;
6459  uint8_t *side_data, *extra_data, *old_side_data;
6460  size_t side_data_size;
6461  buffer_size_t old_side_data_size;
6462  int ret = 0;
6463  unsigned int version, kid_count, extra_data_size, alloc_size = 0;
6464 
6465  if (c->fc->nb_streams < 1)
6466  return 0;
6467  st = c->fc->streams[c->fc->nb_streams-1];
6468 
6469  version = avio_r8(pb); /* version */
6470  avio_rb24(pb); /* flags */
6471 
6472  info = av_encryption_init_info_alloc(/* system_id_size */ 16, /* num_key_ids */ 0,
6473  /* key_id_size */ 16, /* data_size */ 0);
6474  if (!info)
6475  return AVERROR(ENOMEM);
6476 
6477  if ((ret = ffio_read_size(pb, info->system_id, 16)) < 0) {
6478  av_log(c->fc, AV_LOG_ERROR, "Failed to read the system id\n");
6479  goto finish;
6480  }
6481 
6482  if (version > 0) {
6483  kid_count = avio_rb32(pb);
6484  if (kid_count >= INT_MAX / sizeof(*key_ids)) {
6485  ret = AVERROR(ENOMEM);
6486  goto finish;
6487  }
6488 
6489  for (unsigned int i = 0; i < kid_count && !pb->eof_reached; i++) {
6490  unsigned int min_kid_count = FFMIN(FFMAX(i + 1, 1024), kid_count);
6491  key_ids = av_fast_realloc(info->key_ids, &alloc_size,
6492  min_kid_count * sizeof(*key_ids));
6493  if (!key_ids) {
6494  ret = AVERROR(ENOMEM);
6495  goto finish;
6496  }
6497  info->key_ids = key_ids;
6498 
6499  info->key_ids[i] = av_mallocz(16);
6500  if (!info->key_ids[i]) {
6501  ret = AVERROR(ENOMEM);
6502  goto finish;
6503  }
6504  info->num_key_ids = i + 1;
6505 
6506  if ((ret = ffio_read_size(pb, info->key_ids[i], 16)) < 0) {
6507  av_log(c->fc, AV_LOG_ERROR, "Failed to read the key id\n");
6508  goto finish;
6509  }
6510  }
6511 
6512  if (pb->eof_reached) {
6513  av_log(c->fc, AV_LOG_ERROR, "Hit EOF while reading pssh\n");
6514  ret = AVERROR_INVALIDDATA;
6515  goto finish;
6516  }
6517  }
6518 
6519  extra_data_size = avio_rb32(pb);
6520  ret = mov_try_read_block(pb, extra_data_size, &extra_data);
6521  if (ret < 0)
6522  goto finish;
6523 
6524  av_freep(&info->data); // malloc(0) may still allocate something.
6525  info->data = extra_data;
6526  info->data_size = extra_data_size;
6527 
6528  // If there is existing initialization data, append to the list.
6529  old_side_data = av_stream_get_side_data(st, AV_PKT_DATA_ENCRYPTION_INIT_INFO, &old_side_data_size);
6530  if (old_side_data) {
6531  old_init_info = av_encryption_init_info_get_side_data(old_side_data, old_side_data_size);
6532  if (old_init_info) {
6533  // Append to the end of the list.
6534  for (AVEncryptionInitInfo *cur = old_init_info;; cur = cur->next) {
6535  if (!cur->next) {
6536  cur->next = info;
6537  break;
6538  }
6539  }
6540  info = old_init_info;
6541  } else {
6542  // Assume existing side-data will be valid, so the only error we could get is OOM.
6543  ret = AVERROR(ENOMEM);
6544  goto finish;
6545  }
6546  }
6547 
6548  side_data = av_encryption_init_info_add_side_data(info, &side_data_size);
6549  if (!side_data) {
6550  ret = AVERROR(ENOMEM);
6551  goto finish;
6552  }
6554  side_data, side_data_size);
6555  if (ret < 0)
6556  av_free(side_data);
6557 
6558 finish:
6560  return ret;
6561 }
6562 
6564 {
6565  AVStream *st;
6566  MOVStreamContext *sc;
6567 
6568  if (c->fc->nb_streams < 1)
6569  return 0;
6570  st = c->fc->streams[c->fc->nb_streams-1];
6571  sc = st->priv_data;
6572 
6573  if (sc->pseudo_stream_id != 0) {
6574  av_log(c->fc, AV_LOG_ERROR, "schm boxes are only supported in first sample descriptor\n");
6575  return AVERROR_PATCHWELCOME;
6576  }
6577 
6578  if (atom.size < 8)
6579  return AVERROR_INVALIDDATA;
6580 
6581  avio_rb32(pb); /* version and flags */
6582 
6583  if (!sc->cenc.default_encrypted_sample) {
6585  if (!sc->cenc.default_encrypted_sample) {
6586  return AVERROR(ENOMEM);
6587  }
6588  }
6589 
6591  return 0;
6592 }
6593 
6595 {
6596  AVStream *st;
6597  MOVStreamContext *sc;
6598  unsigned int version, pattern, is_protected, iv_size;
6599 
6600  if (c->fc->nb_streams < 1)
6601  return 0;
6602  st = c->fc->streams[c->fc->nb_streams-1];
6603  sc = st->priv_data;
6604 
6605  if (sc->pseudo_stream_id != 0) {
6606  av_log(c->fc, AV_LOG_ERROR, "tenc atom are only supported in first sample descriptor\n");
6607  return AVERROR_PATCHWELCOME;
6608  }
6609 
6610  if (!sc->cenc.default_encrypted_sample) {
6612  if (!sc->cenc.default_encrypted_sample) {
6613  return AVERROR(ENOMEM);
6614  }
6615  }
6616 
6617  if (atom.size < 20)
6618  return AVERROR_INVALIDDATA;
6619 
6620  version = avio_r8(pb); /* version */
6621  avio_rb24(pb); /* flags */
6622 
6623  avio_r8(pb); /* reserved */
6624  pattern = avio_r8(pb);
6625 
6626  if (version > 0) {
6627  sc->cenc.default_encrypted_sample->crypt_byte_block = pattern >> 4;
6628  sc->cenc.default_encrypted_sample->skip_byte_block = pattern & 0xf;
6629  }
6630 
6631  is_protected = avio_r8(pb);
6632  if (is_protected && !sc->cenc.encryption_index) {
6633  // The whole stream should be by-default encrypted.
6635  if (!sc->cenc.encryption_index)
6636  return AVERROR(ENOMEM);
6637  }
6638  sc->cenc.per_sample_iv_size = avio_r8(pb);
6639  if (sc->cenc.per_sample_iv_size != 0 && sc->cenc.per_sample_iv_size != 8 &&
6640  sc->cenc.per_sample_iv_size != 16) {
6641  av_log(c->fc, AV_LOG_ERROR, "invalid per-sample IV size value\n");
6642  return AVERROR_INVALIDDATA;
6643  }
6644  if (avio_read(pb, sc->cenc.default_encrypted_sample->key_id, 16) != 16) {
6645  av_log(c->fc, AV_LOG_ERROR, "failed to read the default key ID\n");
6646  return AVERROR_INVALIDDATA;
6647  }
6648 
6649  if (is_protected && !sc->cenc.per_sample_iv_size) {
6650  iv_size = avio_r8(pb);
6651  if (iv_size != 8 && iv_size != 16) {
6652  av_log(c->fc, AV_LOG_ERROR, "invalid default_constant_IV_size in tenc atom\n");
6653  return AVERROR_INVALIDDATA;
6654  }
6655 
6656  if (avio_read(pb, sc->cenc.default_encrypted_sample->iv, iv_size) != iv_size) {
6657  av_log(c->fc, AV_LOG_ERROR, "failed to read the default IV\n");
6658  return AVERROR_INVALIDDATA;
6659  }
6660  }
6661 
6662  return 0;
6663 }
6664 
6666 {
6667  AVStream *st;
6668  int last, type, size, ret;
6669  uint8_t buf[4];
6670 
6671  if (c->fc->nb_streams < 1)
6672  return 0;
6673  st = c->fc->streams[c->fc->nb_streams-1];
6674 
6675  if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
6676  return AVERROR_INVALIDDATA;
6677 
6678  /* Check FlacSpecificBox version. */
6679  if (avio_r8(pb) != 0)
6680  return AVERROR_INVALIDDATA;
6681 
6682  avio_rb24(pb); /* Flags */
6683 
6684  avio_read(pb, buf, sizeof(buf));
6685  flac_parse_block_header(buf, &last, &type, &size);
6686 
6688  av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
6689  return AVERROR_INVALIDDATA;
6690  }
6691 
6692  ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
6693  if (ret < 0)
6694  return ret;
6695 
6696  if (!last)
6697  av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
6698 
6699  return 0;
6700 }
6701 
6703 {
6704  int i, ret;
6705 
6706  if (sample->scheme != MKBETAG('c','e','n','c') || sample->crypt_byte_block != 0 || sample->skip_byte_block != 0) {
6707  av_log(c->fc, AV_LOG_ERROR, "Only the 'cenc' encryption scheme is supported\n");
6708  return AVERROR_PATCHWELCOME;
6709  }
6710 
6711  if (!sc->cenc.aes_ctr) {
6712  /* initialize the cipher */
6713  sc->cenc.aes_ctr = av_aes_ctr_alloc();
6714  if (!sc->cenc.aes_ctr) {
6715  return AVERROR(ENOMEM);
6716  }
6717 
6718  ret = av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
6719  if (ret < 0) {
6720  return ret;
6721  }
6722  }
6723 
6725 
6726  if (!sample->subsample_count) {
6727  /* decrypt the whole packet */
6728  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
6729  return 0;
6730  }
6731 
6732  for (i = 0; i < sample->subsample_count; i++) {
6733  if (sample->subsamples[i].bytes_of_clear_data + sample->subsamples[i].bytes_of_protected_data > size) {
6734  av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
6735  return AVERROR_INVALIDDATA;
6736  }
6737 
6738  /* skip the clear bytes */
6739  input += sample->subsamples[i].bytes_of_clear_data;
6740  size -= sample->subsamples[i].bytes_of_clear_data;
6741 
6742  /* decrypt the encrypted bytes */
6743  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, sample->subsamples[i].bytes_of_protected_data);
6744  input += sample->subsamples[i].bytes_of_protected_data;
6745  size -= sample->subsamples[i].bytes_of_protected_data;
6746  }
6747 
6748  if (size > 0) {
6749  av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
6750  return AVERROR_INVALIDDATA;
6751  }
6752 
6753  return 0;
6754 }
6755 
6756 static int cenc_filter(MOVContext *mov, AVStream* st, MOVStreamContext *sc, AVPacket *pkt, int current_index)
6757 {
6758  MOVFragmentStreamInfo *frag_stream_info;
6759  MOVEncryptionIndex *encryption_index;
6760  AVEncryptionInfo *encrypted_sample;
6761  int encrypted_index, ret;
6762 
6763  frag_stream_info = get_frag_stream_info(&mov->frag_index, mov->frag_index.current, st->id);
6764  encrypted_index = current_index;
6765  encryption_index = NULL;
6766  if (frag_stream_info) {
6767  // Note this only supports encryption info in the first sample descriptor.
6768  if (mov->fragment.stsd_id == 1) {
6769  if (frag_stream_info->encryption_index) {
6770  encrypted_index = current_index - frag_stream_info->index_entry;
6771  encryption_index = frag_stream_info->encryption_index;
6772  } else {
6773  encryption_index = sc->cenc.encryption_index;
6774  }
6775  }
6776  } else {
6777  encryption_index = sc->cenc.encryption_index;
6778  }
6779 
6780  if (encryption_index) {
6781  if (encryption_index->auxiliary_info_sample_count &&
6782  !encryption_index->nb_encrypted_samples) {
6783  av_log(mov->fc, AV_LOG_ERROR, "saiz atom found without saio\n");
6784  return AVERROR_INVALIDDATA;
6785  }
6786  if (encryption_index->auxiliary_offsets_count &&
6787  !encryption_index->nb_encrypted_samples) {
6788  av_log(mov->fc, AV_LOG_ERROR, "saio atom found without saiz\n");
6789  return AVERROR_INVALIDDATA;
6790  }
6791 
6792  if (!encryption_index->nb_encrypted_samples) {
6793  // Full-sample encryption with default settings.
6794  encrypted_sample = sc->cenc.default_encrypted_sample;
6795  } else if (encrypted_index >= 0 && encrypted_index < encryption_index->nb_encrypted_samples) {
6796  // Per-sample setting override.
6797  encrypted_sample = encryption_index->encrypted_samples[encrypted_index];
6798  } else {
6799  av_log(mov->fc, AV_LOG_ERROR, "Incorrect number of samples in encryption info\n");
6800  return AVERROR_INVALIDDATA;
6801  }
6802 
6803  if (mov->decryption_key) {
6804  return cenc_decrypt(mov, sc, encrypted_sample, pkt->data, pkt->size);
6805  } else {
6806  size_t size;
6807  uint8_t *side_data = av_encryption_info_add_side_data(encrypted_sample, &size);
6808  if (!side_data)
6809  return AVERROR(ENOMEM);
6811  if (ret < 0)
6812  av_free(side_data);
6813  return ret;
6814  }
6815  }
6816 
6817  return 0;
6818 }
6819 
6821 {
6822  const int OPUS_SEEK_PREROLL_MS = 80;
6823  int ret;
6824  AVStream *st;
6825  size_t size;
6826  uint16_t pre_skip;
6827 
6828  if (c->fc->nb_streams < 1)
6829  return 0;
6830  st = c->fc->streams[c->fc->nb_streams-1];
6831 
6832  if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6833  return AVERROR_INVALIDDATA;
6834 
6835  /* Check OpusSpecificBox version. */
6836  if (avio_r8(pb) != 0) {
6837  av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6838  return AVERROR_INVALIDDATA;
6839  }
6840 
6841  /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6842  size = atom.size + 8;
6843 
6844  if ((ret = ff_alloc_extradata(st->codecpar, size)) < 0)
6845  return ret;
6846 
6847  AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6848  AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6849  AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6850  avio_read(pb, st->codecpar->extradata + 9, size - 9);
6851 
6852  /* OpusSpecificBox is stored in big-endian, but OpusHead is
6853  little-endian; aside from the preceeding magic and version they're
6854  otherwise currently identical. Data after output gain at offset 16
6855  doesn't need to be bytewapped. */
6856  pre_skip = AV_RB16(st->codecpar->extradata + 10);
6857  AV_WL16(st->codecpar->extradata + 10, pre_skip);
6858  AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6859  AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6860 
6861  st->codecpar->initial_padding = pre_skip;
6863  (AVRational){1, 1000},
6864  (AVRational){1, 48000});
6865 
6866  return 0;
6867 }
6868 
6870 {
6871  AVStream *st;
6872  unsigned format_info;
6873  int channel_assignment, channel_assignment1, channel_assignment2;
6874  int ratebits;
6875 
6876  if (c->fc->nb_streams < 1)
6877  return 0;
6878  st = c->fc->streams[c->fc->nb_streams-1];
6879 
6880  if (atom.size < 10)
6881  return AVERROR_INVALIDDATA;
6882 
6883  format_info = avio_rb32(pb);
6884 
6885  ratebits = (format_info >> 28) & 0xF;
6886  channel_assignment1 = (format_info >> 15) & 0x1F;
6887  channel_assignment2 = format_info & 0x1FFF;
6888  if (channel_assignment2)
6889  channel_assignment = channel_assignment2;
6890  else
6891  channel_assignment = channel_assignment1;
6892 
6893  st->codecpar->frame_size = 40 << (ratebits & 0x7);
6894  st->codecpar->sample_rate = mlp_samplerate(ratebits);
6895  st->codecpar->channels = truehd_channels(channel_assignment);
6896  st->codecpar->channel_layout = truehd_layout(channel_assignment);
6897 
6898  return 0;
6899 }
6900 
6902 {
6903  AVStream *st;
6904  uint32_t buf;
6906  size_t dovi_size;
6907  int ret;
6908 
6909  if (c->fc->nb_streams < 1)
6910  return 0;
6911  st = c->fc->streams[c->fc->nb_streams-1];
6912 
6913  if ((uint64_t)atom.size > (1<<30) || atom.size < 4)
6914  return AVERROR_INVALIDDATA;
6915 
6916  dovi = av_dovi_alloc(&dovi_size);
6917  if (!dovi)
6918  return AVERROR(ENOMEM);
6919 
6920  dovi->dv_version_major = avio_r8(pb);
6921  dovi->dv_version_minor = avio_r8(pb);
6922 
6923  buf = avio_rb16(pb);
6924  dovi->dv_profile = (buf >> 9) & 0x7f; // 7 bits
6925  dovi->dv_level = (buf >> 3) & 0x3f; // 6 bits
6926  dovi->rpu_present_flag = (buf >> 2) & 0x01; // 1 bit
6927  dovi->el_present_flag = (buf >> 1) & 0x01; // 1 bit
6928  dovi->bl_present_flag = buf & 0x01; // 1 bit
6929  if (atom.size >= 24) { // 4 + 4 + 4 * 4
6930  buf = avio_r8(pb);
6931  dovi->dv_bl_signal_compatibility_id = (buf >> 4) & 0x0f; // 4 bits
6932  } else {
6933  // 0 stands for None
6934  // Dolby Vision V1.2.93 profiles and levels
6936  }
6937 
6939  (uint8_t *)dovi, dovi_size);
6940  if (ret < 0) {
6941  av_free(dovi);
6942  return ret;
6943  }
6944 
6945  av_log(c, AV_LOG_TRACE, "DOVI in dvcC/dvvC box, version: %d.%d, profile: %d, level: %d, "
6946  "rpu flag: %d, el flag: %d, bl flag: %d, compatibility id: %d\n",
6947  dovi->dv_version_major, dovi->dv_version_minor,
6948  dovi->dv_profile, dovi->dv_level,
6949  dovi->rpu_present_flag,
6950  dovi->el_present_flag,
6951  dovi->bl_present_flag,
6953  );
6954 
6955  return 0;
6956 }
6957 
6959 { MKTAG('A','C','L','R'), mov_read_aclr },
6960 { MKTAG('A','P','R','G'), mov_read_avid },
6961 { MKTAG('A','A','L','P'), mov_read_avid },
6962 { MKTAG('A','R','E','S'), mov_read_ares },
6963 { MKTAG('a','v','s','s'), mov_read_avss },
6964 { MKTAG('a','v','1','C'), mov_read_av1c },
6965 { MKTAG('c','h','p','l'), mov_read_chpl },
6966 { MKTAG('c','o','6','4'), mov_read_stco },
6967 { MKTAG('c','o','l','r'), mov_read_colr },
6968 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6969 { MKTAG('d','i','n','f'), mov_read_default },
6970 { MKTAG('D','p','x','E'), mov_read_dpxe },
6971 { MKTAG('d','r','e','f'), mov_read_dref },
6972 { MKTAG('e','d','t','s'), mov_read_default },
6973 { MKTAG('e','l','s','t'), mov_read_elst },
6974 { MKTAG('e','n','d','a'), mov_read_enda },
6975 { MKTAG('f','i','e','l'), mov_read_fiel },
6976 { MKTAG('a','d','r','m'), mov_read_adrm },
6977 { MKTAG('f','t','y','p'), mov_read_ftyp },
6978 { MKTAG('g','l','b','l'), mov_read_glbl },
6979 { MKTAG('h','d','l','r'), mov_read_hdlr },
6980 { MKTAG('i','l','s','t'), mov_read_ilst },
6981 { MKTAG('j','p','2','h'), mov_read_jp2h },
6982 { MKTAG('m','d','a','t'), mov_read_mdat },
6983 { MKTAG('m','d','h','d'), mov_read_mdhd },
6984 { MKTAG('m','d','i','a'), mov_read_default },
6985 { MKTAG('m','e','t','a'), mov_read_meta },
6986 { MKTAG('m','i','n','f'), mov_read_default },
6987 { MKTAG('m','o','o','f'), mov_read_moof },
6988 { MKTAG('m','o','o','v'), mov_read_moov },
6989 { MKTAG('m','v','e','x'), mov_read_default },
6990 { MKTAG('m','v','h','d'), mov_read_mvhd },
6991 { MKTAG('S','M','I',' '), mov_read_svq3 },
6992 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6993 { MKTAG('a','v','c','C'), mov_read_glbl },
6994 { MKTAG('p','a','s','p'), mov_read_pasp },
6995 { MKTAG('s','i','d','x'), mov_read_sidx },
6996 { MKTAG('s','t','b','l'), mov_read_default },
6997 { MKTAG('s','t','c','o'), mov_read_stco },
6998 { MKTAG('s','t','p','s'), mov_read_stps },
6999 { MKTAG('s','t','r','f'), mov_read_strf },
7000 { MKTAG('s','t','s','c'), mov_read_stsc },
7001 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
7002 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
7003 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
7004 { MKTAG('s','t','t','s'), mov_read_stts },
7005 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
7006 { MKTAG('s','d','t','p'), mov_read_sdtp }, /* independent and disposable samples */
7007 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
7008 { MKTAG('t','f','d','t'), mov_read_tfdt },
7009 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
7010 { MKTAG('t','r','a','k'), mov_read_trak },
7011 { MKTAG('t','r','a','f'), mov_read_default },
7012 { MKTAG('t','r','e','f'), mov_read_default },
7013 { MKTAG('t','m','c','d'), mov_read_tmcd },
7014 { MKTAG('c','h','a','p'), mov_read_chap },
7015 { MKTAG('t','r','e','x'), mov_read_trex },
7016 { MKTAG('t','r','u','n'), mov_read_trun },
7017 { MKTAG('u','d','t','a'), mov_read_default },
7018 { MKTAG('w','a','v','e'), mov_read_wave },
7019 { MKTAG('e','s','d','s'), mov_read_esds },
7020 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
7021 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
7022 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
7023 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
7024 { MKTAG('w','f','e','x'), mov_read_wfex },
7025 { MKTAG('c','m','o','v'), mov_read_cmov },
7026 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
7027 { MKTAG('d','v','c','1'), mov_read_dvc1 },
7028 { MKTAG('s','b','g','p'), mov_read_sbgp },
7029 { MKTAG('h','v','c','C'), mov_read_glbl },
7030 { MKTAG('u','u','i','d'), mov_read_uuid },
7031 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
7032 { MKTAG('f','r','e','e'), mov_read_free },
7033 { MKTAG('-','-','-','-'), mov_read_custom },
7034 { MKTAG('s','i','n','f'), mov_read_default },
7035 { MKTAG('f','r','m','a'), mov_read_frma },
7036 { MKTAG('s','e','n','c'), mov_read_senc },
7037 { MKTAG('s','a','i','z'), mov_read_saiz },
7038 { MKTAG('s','a','i','o'), mov_read_saio },
7039 { MKTAG('p','s','s','h'), mov_read_pssh },
7040 { MKTAG('s','c','h','m'), mov_read_schm },
7041 { MKTAG('s','c','h','i'), mov_read_default },
7042 { MKTAG('t','e','n','c'), mov_read_tenc },
7043 { MKTAG('d','f','L','a'), mov_read_dfla },
7044 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
7045 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
7046 { MKTAG('d','O','p','s'), mov_read_dops },
7047 { MKTAG('d','m','l','p'), mov_read_dmlp },
7048 { MKTAG('S','m','D','m'), mov_read_smdm },
7049 { MKTAG('C','o','L','L'), mov_read_coll },
7050 { MKTAG('v','p','c','C'), mov_read_vpcc },
7051 { MKTAG('m','d','c','v'), mov_read_mdcv },
7052 { MKTAG('c','l','l','i'), mov_read_clli },
7053 { MKTAG('d','v','c','C'), mov_read_dvcc_dvvc },
7054 { MKTAG('d','v','v','C'), mov_read_dvcc_dvvc },
7055 { 0, NULL }
7056 };
7057 
7059 {
7060  int64_t total_size = 0;
7061  MOVAtom a;
7062  int i;
7063 
7064  if (c->atom_depth > 10) {
7065  av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
7066  return AVERROR_INVALIDDATA;
7067  }
7068  c->atom_depth ++;
7069 
7070  if (atom.size < 0)
7071  atom.size = INT64_MAX;
7072  while (total_size <= atom.size - 8 && !avio_feof(pb)) {
7074  a.size = atom.size;
7075  a.type=0;
7076  if (atom.size >= 8) {
7077  a.size = avio_rb32(pb);
7078  a.type = avio_rl32(pb);
7079  if (((a.type == MKTAG('f','r','e','e') && c->moov_retry) ||
7080  a.type == MKTAG('h','o','o','v')) &&
7081  a.size >= 8 &&
7082  c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT) {
7083  uint32_t type;
7084  avio_skip(pb, 4);
7085  type = avio_rl32(pb);
7086  if (avio_feof(pb))
7087  break;
7088  avio_seek(pb, -8, SEEK_CUR);
7089  if (type == MKTAG('m','v','h','d') ||
7090  type == MKTAG('c','m','o','v')) {
7091  av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free or hoov atom.\n");
7092  a.type = MKTAG('m','o','o','v');
7093  }
7094  }
7095  if (atom.type != MKTAG('r','o','o','t') &&
7096  atom.type != MKTAG('m','o','o','v')) {
7097  if (a.type == MKTAG('t','r','a','k') ||
7098  a.type == MKTAG('m','d','a','t')) {
7099  av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
7100  avio_skip(pb, -8);
7101  c->atom_depth --;
7102  return 0;
7103  }
7104  }
7105  total_size += 8;
7106  if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
7107  a.size = avio_rb64(pb) - 8;
7108  total_size += 8;
7109  }
7110  }
7111  av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
7112  av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
7113  if (a.size == 0) {
7114  a.size = atom.size - total_size + 8;
7115  }
7116  if (a.size < 0)
7117  break;
7118  a.size -= 8;
7119  if (a.size < 0)
7120  break;
7121  a.size = FFMIN(a.size, atom.size - total_size);
7122 
7123  for (i = 0; mov_default_parse_table[i].type; i++)
7124  if (mov_default_parse_table[i].type == a.type) {
7126  break;
7127  }
7128 
7129  // container is user data
7130  if (!parse && (atom.type == MKTAG('u','d','t','a') ||
7131  atom.type == MKTAG('i','l','s','t')))
7133 
7134  // Supports parsing the QuickTime Metadata Keys.
7135  // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
7136  if (!parse && c->found_hdlr_mdta &&
7137  atom.type == MKTAG('m','e','t','a') &&
7138  a.type == MKTAG('k','e','y','s') &&
7139  c->meta_keys_count == 0) {
7140  parse = mov_read_keys;
7141  }
7142 
7143  if (!parse) { /* skip leaf atoms data */
7144  avio_skip(pb, a.size);
7145  } else {
7146  int64_t start_pos = avio_tell(pb);
7147  int64_t left;
7148  int err = parse(c, pb, a);
7149  if (err < 0) {
7150  c->atom_depth --;
7151  return err;
7152  }
7153  if (c->found_moov && c->found_mdat && a.size <= INT64_MAX - start_pos &&
7154  ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
7155  start_pos + a.size == avio_size(pb))) {
7156  if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
7157  c->next_root_atom = start_pos + a.size;
7158  c->atom_depth --;
7159  return 0;
7160  }
7161  left = a.size - avio_tell(pb) + start_pos;
7162  if (left > 0) /* skip garbage at atom end */
7163  avio_skip(pb, left);
7164  else if (left < 0) {
7165  av_log(c->fc, AV_LOG_WARNING,
7166  "overread end of atom '%s' by %"PRId64" bytes\n",
7167  av_fourcc2str(a.type), -left);
7168  avio_seek(pb, left, SEEK_CUR);
7169  }
7170  }
7171 
7172  total_size += a.size;
7173  }
7174 
7175  if (total_size < atom.size && atom.size < 0x7ffff)
7176  avio_skip(pb, atom.size - total_size);
7177 
7178  c->atom_depth --;
7179  return 0;
7180 }
7181 
7182 static int mov_probe(const AVProbeData *p)
7183 {
7184  int64_t offset;
7185  uint32_t tag;
7186  int score = 0;
7187  int moov_offset = -1;
7188 
7189  /* check file header */
7190  offset = 0;
7191  for (;;) {
7192  int64_t size;
7193  int minsize = 8;
7194  /* ignore invalid offset */
7195  if ((offset + 8ULL) > (unsigned int)p->buf_size)
7196  break;
7197  size = AV_RB32(p->buf + offset);
7198  if (size == 1 && offset + 16 <= (unsigned int)p->buf_size) {
7199  size = AV_RB64(p->buf+offset + 8);
7200  minsize = 16;
7201  } else if (size == 0) {
7202  size = p->buf_size - offset;
7203  }
7204  if (size < minsize) {
7205  offset += 4;
7206  continue;
7207  }
7208  tag = AV_RL32(p->buf + offset + 4);
7209  switch(tag) {
7210  /* check for obvious tags */
7211  case MKTAG('m','o','o','v'):
7212  moov_offset = offset + 4;
7213  case MKTAG('m','d','a','t'):
7214  case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
7215  case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
7216  case MKTAG('f','t','y','p'):
7217  if (tag == MKTAG('f','t','y','p') &&
7218  ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
7219  || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
7220  )) {
7221  score = FFMAX(score, 5);
7222  } else {
7223  score = AVPROBE_SCORE_MAX;
7224  }
7225  break;
7226  /* those are more common words, so rate then a bit less */
7227  case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
7228  case MKTAG('w','i','d','e'):
7229  case MKTAG('f','r','e','e'):
7230  case MKTAG('j','u','n','k'):
7231  case MKTAG('p','i','c','t'):
7232  score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
7233  break;
7234  case MKTAG(0x82,0x82,0x7f,0x7d):
7235  case MKTAG('s','k','i','p'):
7236  case MKTAG('u','u','i','d'):
7237  case MKTAG('p','r','f','l'):
7238  /* if we only find those cause probedata is too small at least rate them */
7239  score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
7240  break;
7241  }
7242  if (size > INT64_MAX - offset)
7243  break;
7244  offset += size;
7245  }
7246  if (score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
7247  /* moov atom in the header - we should make sure that this is not a
7248  * MOV-packed MPEG-PS */
7249  offset = moov_offset;
7250 
7251  while (offset < (p->buf_size - 16)) { /* Sufficient space */
7252  /* We found an actual hdlr atom */
7253  if (AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
7254  AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
7255  AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')) {
7256  av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
7257  /* We found a media handler reference atom describing an
7258  * MPEG-PS-in-MOV, return a
7259  * low score to force expanding the probe window until
7260  * mpegps_probe finds what it needs */
7261  return 5;
7262  } else {
7263  /* Keep looking */
7264  offset += 2;
7265  }
7266  }
7267  }
7268 
7269  return score;
7270 }
7271 
7272 // must be done after parsing all trak because there's no order requirement
7274 {
7275  MOVContext *mov = s->priv_data;
7276  AVStream *st;
7277  MOVStreamContext *sc;
7278  int64_t cur_pos;
7279  int i, j;
7280  int chapter_track;
7281 
7282  for (j = 0; j < mov->nb_chapter_tracks; j++) {
7283  chapter_track = mov->chapter_tracks[j];
7284  st = NULL;
7285  for (i = 0; i < s->nb_streams; i++)
7286  if (s->streams[i]->id == chapter_track) {
7287  st = s->streams[i];
7288  break;
7289  }
7290  if (!st) {
7291  av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
7292  continue;
7293  }
7294 
7295  sc = st->priv_data;
7296  cur_pos = avio_tell(sc->pb);
7297 
7298  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
7300  if (st->nb_index_entries) {
7301  // Retrieve the first frame, if possible
7302  AVIndexEntry *sample = &st->index_entries[0];
7303  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7304  av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
7305  goto finish;
7306  }
7307 
7308  if (av_get_packet(sc->pb, &st->attached_pic, sample->size) < 0)
7309  goto finish;
7310 
7311  st->attached_pic.stream_index = st->index;
7313  }
7314  } else {
7317  st->discard = AVDISCARD_ALL;
7318  for (i = 0; i < st->nb_index_entries; i++) {
7320  int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
7321  uint8_t *title;
7322  uint16_t ch;
7323  int len, title_len;
7324 
7325  if (end < sample->timestamp) {
7326  av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
7327  end = AV_NOPTS_VALUE;
7328  }
7329 
7330  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
7331  av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
7332  goto finish;
7333  }
7334 
7335  // the first two bytes are the length of the title
7336  len = avio_rb16(sc->pb);
7337  if (len > sample->size-2)
7338  continue;
7339  title_len = 2*len + 1;
7340  if (!(title = av_mallocz(title_len)))
7341  goto finish;
7342 
7343  // The samples could theoretically be in any encoding if there's an encd
7344  // atom following, but in practice are only utf-8 or utf-16, distinguished
7345  // instead by the presence of a BOM
7346  if (!len) {
7347  title[0] = 0;
7348  } else {
7349  ch = avio_rb16(sc->pb);
7350  if (ch == 0xfeff)
7351  avio_get_str16be(sc->pb, len, title, title_len);
7352  else if (ch == 0xfffe)
7353  avio_get_str16le(sc->pb, len, title, title_len);
7354  else {
7355  AV_WB16(title, ch);
7356  if (len == 1 || len == 2)
7357  title[len] = 0;
7358  else
7359  avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
7360  }
7361  }
7362 
7363  avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
7364  av_freep(&title);
7365  }
7366  }
7367 finish:
7368  avio_seek(sc->pb, cur_pos, SEEK_SET);
7369  }
7370 }
7371 
7373  uint32_t value, int flags)
7374 {
7375  AVTimecode tc;
7376  char buf[AV_TIMECODE_STR_SIZE];
7377  AVRational rate = st->avg_frame_rate;
7378  int ret = av_timecode_init(&tc, rate, flags, 0, s);
7379  if (ret < 0)
7380  return ret;
7381  av_dict_set(&st->metadata, "timecode",
7382  av_timecode_make_string(&tc, buf, value), 0);
7383  return 0;
7384 }
7385 
7387 {
7388  MOVStreamContext *sc = st->priv_data;
7389  char buf[AV_TIMECODE_STR_SIZE];
7390  int64_t cur_pos = avio_tell(sc->pb);
7391  int hh, mm, ss, ff, drop;
7392 
7393  if (!st->nb_index_entries)
7394  return -1;
7395 
7396  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
7397  avio_skip(s->pb, 13);
7398  hh = avio_r8(s->pb);
7399  mm = avio_r8(s->pb);
7400  ss = avio_r8(s->pb);
7401  drop = avio_r8(s->pb);
7402  ff = avio_r8(s->pb);
7403  snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
7404  hh, mm, ss, drop ? ';' : ':', ff);
7405  av_dict_set(&st->metadata, "timecode", buf, 0);
7406 
7407  avio_seek(sc->pb, cur_pos, SEEK_SET);
7408  return 0;
7409 }
7410 
7412 {
7413  MOVStreamContext *sc = st->priv_data;
7414  int flags = 0;
7415  int64_t cur_pos = avio_tell(sc->pb);
7416  uint32_t value;
7417 
7418  if (!st->nb_index_entries)
7419  return -1;
7420 
7421  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
7422  value = avio_rb32(s->pb);
7423 
7424  if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
7425  if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
7426  if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
7427 
7428  /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
7429  * not the case) and thus assume "frame number format" instead of QT one.
7430  * No sample with tmcd track can be found with a QT timecode at the moment,
7431  * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
7432  * format). */
7434 
7435  avio_seek(sc->pb, cur_pos, SEEK_SET);
7436  return 0;
7437 }
7438 
7440  int i;
7441  if (!index || !*index) return;
7442  for (i = 0; i < (*index)->nb_encrypted_samples; i++) {
7443  av_encryption_info_free((*index)->encrypted_samples[i]);
7444  }
7445  av_freep(&(*index)->encrypted_samples);
7446  av_freep(&(*index)->auxiliary_info_sizes);
7447  av_freep(&(*index)->auxiliary_offsets);
7448  av_freep(index);
7449 }
7450 
7452 {
7453  MOVContext *mov = s->priv_data;
7454  int i, j;
7455 
7456  for (i = 0; i < s->nb_streams; i++) {
7457  AVStream *st = s->streams[i];
7458  MOVStreamContext *sc = st->priv_data;
7459 
7460  if (!sc)
7461  continue;
7462 
7463  av_freep(&sc->ctts_data);
7464  for (j = 0; j < sc->drefs_count; j++) {
7465  av_freep(&sc->drefs[j].path);
7466  av_freep(&sc->drefs[j].dir);
7467  }
7468  av_freep(&sc->drefs);
7469 
7470  sc->drefs_count = 0;
7471 
7472  if (!sc->pb_is_copied)
7473  ff_format_io_close(s, &sc->pb);
7474 
7475  sc->pb = NULL;
7476  av_freep(&sc->chunk_offsets);
7477  av_freep(&sc->stsc_data);
7478  av_freep(&sc->sample_sizes);
7479  av_freep(&sc->keyframes);
7480  av_freep(&sc->stts_data);
7481  av_freep(&sc->sdtp_data);
7482  av_freep(&sc->stps_data);
7483  av_freep(&sc->elst_data);
7484  av_freep(&sc->rap_group);
7485  av_freep(&sc->display_matrix);
7486  av_freep(&sc->index_ranges);
7487 
7488  if (sc->extradata)
7489  for (j = 0; j < sc->stsd_count; j++)
7490  av_free(sc->extradata[j]);
7491  av_freep(&sc->extradata);
7492  av_freep(&sc->extradata_size);
7493 
7497 
7498  av_freep(&sc->stereo3d);
7499  av_freep(&sc->spherical);
7500  av_freep(&sc->mastering);
7501  av_freep(&sc->coll);
7502  }
7503 
7504  av_freep(&mov->dv_demux);
7506  mov->dv_fctx = NULL;
7507 
7508  if (mov->meta_keys) {
7509  for (i = 1; i < mov->meta_keys_count; i++) {
7510  av_freep(&mov->meta_keys[i]);
7511  }
7512  av_freep(&mov->meta_keys);
7513  }
7514 
7515  av_freep(&mov->trex_data);
7516  av_freep(&mov->bitrates);
7517 
7518  for (i = 0; i < mov->frag_index.nb_items; i++) {
7520  for (j = 0; j < mov->frag_index.item[i].nb_stream_info; j++) {
7521  mov_free_encryption_index(&frag[j].encryption_index);
7522  }
7524  }
7525  av_freep(&mov->frag_index.item);
7526 
7527  av_freep(&mov->aes_decrypt);
7528  av_freep(&mov->chapter_tracks);
7529 
7530  return 0;
7531 }
7532 
7533 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
7534 {
7535  int i;
7536 
7537  for (i = 0; i < s->nb_streams; i++) {
7538  AVStream *st = s->streams[i];
7539  MOVStreamContext *sc = st->priv_data;
7540 
7541  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
7542  sc->timecode_track == tmcd_id)
7543  return 1;
7544  }
7545  return 0;
7546 }
7547 
7548 /* look for a tmcd track not referenced by any video track, and export it globally */
7550 {
7551  int i;
7552 
7553  for (i = 0; i < s->nb_streams; i++) {
7554  AVStream *st = s->streams[i];
7555 
7556  if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
7557  !tmcd_is_referenced(s, i + 1)) {
7558  AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
7559  if (tcr) {
7560  av_dict_set(&s->metadata, "timecode", tcr->value, 0);
7561  break;
7562  }
7563  }
7564  }
7565 }
7566 
7567 static int read_tfra(MOVContext *mov, AVIOContext *f)
7568 {
7569  int version, fieldlength, i, j;
7570  int64_t pos = avio_tell(f);
7571  uint32_t size = avio_rb32(f);
7572  unsigned track_id, item_count;
7573 
7574  if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
7575  return 1;
7576  }
7577  av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
7578 
7579  version = avio_r8(f);
7580  avio_rb24(f);
7581  track_id = avio_rb32(f);
7582  fieldlength = avio_rb32(f);
7583  item_count = avio_rb32(f);
7584  for (i = 0; i < item_count; i++) {
7585  int64_t time, offset;
7586  int index;
7587  MOVFragmentStreamInfo * frag_stream_info;
7588 
7589  if (avio_feof(f)) {
7590  return AVERROR_INVALIDDATA;
7591  }
7592 
7593  if (version == 1) {
7594  time = avio_rb64(f);
7595  offset = avio_rb64(f);
7596  } else {
7597  time = avio_rb32(f);
7598  offset = avio_rb32(f);
7599  }
7600 
7601  // The first sample of each stream in a fragment is always a random
7602  // access sample. So it's entry in the tfra can be used as the
7603  // initial PTS of the fragment.
7604  index = update_frag_index(mov, offset);
7605  frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
7606  if (frag_stream_info &&
7607  frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
7608  frag_stream_info->first_tfra_pts = time;
7609 
7610  for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
7611  avio_r8(f);
7612  for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
7613  avio_r8(f);
7614  for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
7615  avio_r8(f);
7616  }
7617 
7618  avio_seek(f, pos + size, SEEK_SET);
7619  return 0;
7620 }
7621 
7623 {
7624  int64_t stream_size = avio_size(f);
7625  int64_t original_pos = avio_tell(f);
7626  int64_t seek_ret;
7627  int ret = -1;
7628  if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
7629  ret = seek_ret;
7630  goto fail;
7631  }
7632  c->mfra_size = avio_rb32(f);
7633  c->have_read_mfra_size = 1;
7634  if (!c->mfra_size || c->mfra_size > stream_size) {
7635  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
7636  goto fail;
7637  }
7638  if ((seek_ret = avio_seek(f, -((int64_t) c->mfra_size), SEEK_CUR)) < 0) {
7639  ret = seek_ret;
7640  goto fail;
7641  }
7642  if (avio_rb32(f) != c->mfra_size) {
7643  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
7644  goto fail;
7645  }
7646  if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
7647  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
7648  goto fail;
7649  }
7650  av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
7651  do {
7652  ret = read_tfra(c, f);
7653  if (ret < 0)
7654  goto fail;
7655  } while (!ret);
7656  ret = 0;
7657  c->frag_index.complete = 1;
7658 fail:
7659  seek_ret = avio_seek(f, original_pos, SEEK_SET);
7660  if (seek_ret < 0) {
7661  av_log(c->fc, AV_LOG_ERROR,
7662  "failed to seek back after looking for mfra\n");
7663  ret = seek_ret;
7664  }
7665  return ret;
7666 }
7667 
7669 {
7670  MOVContext *mov = s->priv_data;
7671  AVIOContext *pb = s->pb;
7672  int j, err;
7673  MOVAtom atom = { AV_RL32("root") };
7674  int i;
7675 
7676  if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
7677  av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
7679  return AVERROR(EINVAL);
7680  }
7681 
7682  mov->fc = s;
7683  mov->trak_index = -1;
7684  /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
7685  if (pb->seekable & AVIO_SEEKABLE_NORMAL)
7686  atom.size = avio_size(pb);
7687  else
7688  atom.size = INT64_MAX;
7689 
7690  /* check MOV header */
7691  do {
7692  if (mov->moov_retry)
7693  avio_seek(pb, 0, SEEK_SET);
7694  if ((err = mov_read_default(mov, pb, atom)) < 0) {
7695  av_log(s, AV_LOG_ERROR, "error reading header\n");
7696  goto fail;
7697  }
7698  } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
7699  if (!mov->found_moov) {
7700  av_log(s, AV_LOG_ERROR, "moov atom not found\n");
7701  err = AVERROR_INVALIDDATA;
7702  goto fail;
7703  }
7704  av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
7705 
7706  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
7707  if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
7709  for (i = 0; i < s->nb_streams; i++)
7710  if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
7711  mov_read_timecode_track(s, s->streams[i]);
7712  } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
7713  mov_read_rtmd_track(s, s->streams[i]);
7714  }
7715  }
7716 
7717  /* copy timecode metadata from tmcd tracks to the related video streams */
7718  for (i = 0; i < s->nb_streams; i++) {
7719  AVStream *st = s->streams[i];
7720  MOVStreamContext *sc = st->priv_data;
7721  if (sc->timecode_track > 0) {
7722  AVDictionaryEntry *tcr;
7723  int tmcd_st_id = -1;
7724 
7725  for (j = 0; j < s->nb_streams; j++)
7726  if (s->streams[j]->id == sc->timecode_track)
7727  tmcd_st_id = j;
7728 
7729  if (tmcd_st_id < 0 || tmcd_st_id == i)
7730  continue;
7731  tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
7732  if (tcr)
7733  av_dict_set(&st->metadata, "timecode", tcr->value, 0);
7734  }
7735  }
7737 
7738  for (i = 0; i < s->nb_streams; i++) {
7739  AVStream *st = s->streams[i];
7740  MOVStreamContext *sc = st->priv_data;
7741  fix_timescale(mov, sc);
7742  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
7743  st->codecpar->codec_id == AV_CODEC_ID_AAC) {
7744  st->internal->skip_samples = sc->start_pad;
7745  }
7746  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
7748  sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
7750  if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
7751  st->codecpar->width = sc->width;
7752  st->codecpar->height = sc->height;
7753  }
7755  if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
7756  goto fail;
7757  }
7758  }
7759  if (mov->handbrake_version &&
7760  mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
7761  st->codecpar->codec_id == AV_CODEC_ID_MP3) {
7762  av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
7764  }
7765  }
7766 
7767  if (mov->trex_data) {
7768  for (i = 0; i < s->nb_streams; i++) {
7769  AVStream *st = s->streams[i];
7770  MOVStreamContext *sc = st->priv_data;
7771  if (st->duration > 0) {
7772  if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7773  av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7774  sc->data_size, sc->time_scale);
7775  err = AVERROR_INVALIDDATA;
7776  goto fail;
7777  }
7778  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
7779  }
7780  }
7781  }
7782 
7783  if (mov->use_mfra_for > 0) {
7784  for (i = 0; i < s->nb_streams; i++) {
7785  AVStream *st = s->streams[i];
7786  MOVStreamContext *sc = st->priv_data;
7787  if (sc->duration_for_fps > 0) {
7788  if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
7789  av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
7790  sc->data_size, sc->time_scale);
7791  err = AVERROR_INVALIDDATA;
7792  goto fail;
7793  }
7794  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
7795  sc->duration_for_fps;
7796  }
7797  }
7798  }
7799 
7800  for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
7801  if (mov->bitrates[i]) {
7802  s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
7803  }
7804  }
7805 
7807 
7808  for (i = 0; i < s->nb_streams; i++) {
7809  AVStream *st = s->streams[i];
7810  MOVStreamContext *sc = st->priv_data;
7811 
7812  switch (st->codecpar->codec_type) {
7813  case AVMEDIA_TYPE_AUDIO:
7814  err = ff_replaygain_export(st, s->metadata);
7815  if (err < 0)
7816  goto fail;
7817  break;
7818  case AVMEDIA_TYPE_VIDEO:
7819  if (sc->display_matrix) {
7821  sizeof(int32_t) * 9);
7822  if (err < 0)
7823  goto fail;
7824 
7825  sc->display_matrix = NULL;
7826  }
7827  if (sc->stereo3d) {
7829  (uint8_t *)sc->stereo3d,
7830  sizeof(*sc->stereo3d));
7831  if (err < 0)
7832  goto fail;
7833 
7834  sc->stereo3d = NULL;
7835  }
7836  if (sc->spherical) {
7838  (uint8_t *)sc->spherical,
7839  sc->spherical_size);
7840  if (err < 0)
7841  goto fail;
7842 
7843  sc->spherical = NULL;
7844  }
7845  if (sc->mastering) {
7847  (uint8_t *)sc->mastering,
7848  sizeof(*sc->mastering));
7849  if (err < 0)
7850  goto fail;
7851 
7852  sc->mastering = NULL;
7853  }
7854  if (sc->coll) {
7856  (uint8_t *)sc->coll,
7857  sc->coll_size);
7858  if (err < 0)
7859  goto fail;
7860 
7861  sc->coll = NULL;
7862  }
7863  break;
7864  }
7865  }
7867 
7868  for (i = 0; i < mov->frag_index.nb_items; i++)
7869  if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
7870  mov->frag_index.item[i].headers_read = 1;
7871 
7872  return 0;
7873 fail:
7874  mov_read_close(s);
7875  return err;
7876 }
7877 
7879 {
7881  int64_t best_dts = INT64_MAX;
7882  int i;
7883  for (i = 0; i < s->nb_streams; i++) {
7884  AVStream *avst = s->streams[i];
7885  MOVStreamContext *msc = avst->priv_data;
7886  if (msc->pb && msc->current_sample < avst->nb_index_entries) {
7887  AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
7888  int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
7889  uint64_t dtsdiff = best_dts > dts ? best_dts - (uint64_t)dts : ((uint64_t)dts - best_dts);
7890  av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
7891  if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
7892  ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
7893  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && dts != AV_NOPTS_VALUE &&
7894  ((dtsdiff <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
7895  (dtsdiff > AV_TIME_BASE && dts < best_dts)))))) {
7896  sample = current_sample;
7897  best_dts = dts;
7898  *st = avst;
7899  }
7900  }
7901  }
7902  return sample;
7903 }
7904 
7905 static int should_retry(AVIOContext *pb, int error_code) {
7906  if (error_code == AVERROR_EOF || avio_feof(pb))
7907  return 0;
7908 
7909  return 1;
7910 }
7911 
7912 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
7913 {
7914  int ret;
7915  MOVContext *mov = s->priv_data;
7916 
7917  if (index >= 0 && index < mov->frag_index.nb_items)
7918  target = mov->frag_index.item[index].moof_offset;
7919  if (avio_seek(s->pb, target, SEEK_SET) != target) {
7920  av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
7921  return AVERROR_INVALIDDATA;
7922  }
7923 
7924  mov->next_root_atom = 0;
7925  if (index < 0 || index >= mov->frag_index.nb_items)
7926  index = search_frag_moof_offset(&mov->frag_index, target);
7927  if (index < mov->frag_index.nb_items &&
7928  mov->frag_index.item[index].moof_offset == target) {
7929  if (index + 1 < mov->frag_index.nb_items)
7930  mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7931  if (mov->frag_index.item[index].headers_read)
7932  return 0;
7933  mov->frag_index.item[index].headers_read = 1;
7934  }
7935 
7936  mov->found_mdat = 0;
7937 
7938  ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
7939  if (ret < 0)
7940  return ret;
7941  if (avio_feof(s->pb))
7942  return AVERROR_EOF;
7943  av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
7944 
7945  return 1;
7946 }
7947 
7949 {
7950  uint8_t *side, *extradata;
7951  int extradata_size;
7952 
7953  /* Save the current index. */
7954  sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
7955 
7956  /* Notify the decoder that extradata changed. */
7957  extradata_size = sc->extradata_size[sc->last_stsd_index];
7958  extradata = sc->extradata[sc->last_stsd_index];
7959  if (extradata_size > 0 && extradata) {
7962  extradata_size);
7963  if (!side)
7964  return AVERROR(ENOMEM);
7965  memcpy(side, extradata, extradata_size);
7966  }
7967 
7968  return 0;
7969 }
7970 
7972 {
7973  int new_size, ret;
7974 
7975  if (size <= 8)
7976  return AVERROR_INVALIDDATA;
7977  new_size = ((size - 8) / 2) * 3;
7978  ret = av_new_packet(pkt, new_size);
7979  if (ret < 0)
7980  return ret;
7981 
7982  avio_skip(pb, 8);
7983  for (int j = 0; j < new_size; j += 3) {
7984  pkt->data[j] = 0xFC;
7985  pkt->data[j+1] = avio_r8(pb);
7986  pkt->data[j+2] = avio_r8(pb);
7987  }
7988 
7989  return 0;
7990 }
7991 
7993 {
7994  MOVContext *mov = s->priv_data;
7995  MOVStreamContext *sc;
7997  AVStream *st = NULL;
7998  int64_t current_index;
7999  int ret;
8000  mov->fc = s;
8001  retry:
8002  sample = mov_find_next_sample(s, &st);
8003  if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
8004  if (!mov->next_root_atom)
8005  return AVERROR_EOF;
8006  if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
8007  return ret;
8008  goto retry;
8009  }
8010  sc = st->priv_data;
8011  /* must be done just before reading, to avoid infinite loop on sample */
8012  current_index = sc->current_index;
8014 
8015  if (mov->next_root_atom) {
8016  sample->pos = FFMIN(sample->pos, mov->next_root_atom);
8017  sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
8018  }
8019 
8020  if (st->discard != AVDISCARD_ALL) {
8021  int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
8022  if (ret64 != sample->pos) {
8023  av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
8024  sc->ffindex, sample->pos);
8025  if (should_retry(sc->pb, ret64)) {
8027  }
8028  return AVERROR_INVALIDDATA;
8029  }
8030 
8031  if (st->discard == AVDISCARD_NONKEY && !(sample->flags & AVINDEX_KEYFRAME)) {
8032  av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
8033  goto retry;
8034  }
8035 
8036  if (st->codecpar->codec_id == AV_CODEC_ID_EIA_608 && sample->size > 8)
8037  ret = get_eia608_packet(sc->pb, pkt, sample->size);
8038  else
8039  ret = av_get_packet(sc->pb, pkt, sample->size);
8040  if (ret < 0) {
8041  if (should_retry(sc->pb, ret)) {
8043  }
8044  return ret;
8045  }
8046 #if CONFIG_DV_DEMUXER
8047  if (mov->dv_demux && sc->dv_audio_container) {
8048  AVBufferRef *buf = pkt->buf;
8050  pkt->buf = buf;
8052  if (ret < 0)
8053  return ret;
8054  ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
8055  if (ret < 0)
8056  return ret;
8057  }
8058 #endif
8059  if (sc->has_palette) {
8060  uint8_t *pal;
8061 
8063  if (!pal) {
8064  av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
8065  } else {
8066  memcpy(pal, sc->palette, AVPALETTE_SIZE);
8067  sc->has_palette = 0;
8068  }
8069  }
8070  if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
8071  if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
8073  }
8074  }
8075 
8076  pkt->stream_index = sc->ffindex;
8077  pkt->dts = sample->timestamp;
8078  if (sample->flags & AVINDEX_DISCARD_FRAME) {
8080  }
8081  if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
8083  /* update ctts context */
8084  sc->ctts_sample++;
8085  if (sc->ctts_index < sc->ctts_count &&
8086  sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
8087  sc->ctts_index++;
8088  sc->ctts_sample = 0;
8089  }
8090  } else {
8091  int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
8093 
8094  if (next_dts >= pkt->dts)
8095  pkt->duration = next_dts - pkt->dts;
8096  pkt->pts = pkt->dts;
8097  }
8098  if (st->discard == AVDISCARD_ALL)
8099  goto retry;
8100  if (sc->sdtp_data && sc->current_sample <= sc->sdtp_count) {
8101  uint8_t sample_flags = sc->sdtp_data[sc->current_sample - 1];
8102  uint8_t sample_is_depended_on = (sample_flags >> 2) & 0x3;
8103  pkt->flags |= sample_is_depended_on == MOV_SAMPLE_DEPENDENCY_NO ? AV_PKT_FLAG_DISPOSABLE : 0;
8104  }
8105  pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
8106  pkt->pos = sample->pos;
8107 
8108  /* Multiple stsd handling. */
8109  if (sc->stsc_data) {
8110  /* Keep track of the stsc index for the given sample, then check
8111  * if the stsd index is different from the last used one. */
8112  sc->stsc_sample++;
8113  if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
8114  mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
8115  sc->stsc_index++;
8116  sc->stsc_sample = 0;
8117  /* Do not check indexes after a switch. */
8118  } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
8119  sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
8120  sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
8121  ret = mov_change_extradata(sc, pkt);
8122  if (ret < 0)
8123  return ret;
8124  }
8125  }
8126 
8127  if (mov->aax_mode)
8128  aax_filter(pkt->data, pkt->size, mov);
8129 
8130  ret = cenc_filter(mov, st, sc, pkt, current_index);
8131  if (ret < 0) {
8132  return ret;
8133  }
8134 
8135  return 0;
8136 }
8137 
8139 {
8140  MOVContext *mov = s->priv_data;
8141  int index;
8142 
8143  if (!mov->frag_index.complete)
8144  return 0;
8145 
8146  index = search_frag_timestamp(&mov->frag_index, st, timestamp);
8147  if (index < 0)
8148  index = 0;
8149  if (!mov->frag_index.item[index].headers_read)
8150  return mov_switch_root(s, -1, index);
8151  if (index + 1 < mov->frag_index.nb_items)
8152  mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
8153 
8154  return 0;
8155 }
8156 
8157 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
8158 {
8159  MOVStreamContext *sc = st->priv_data;
8160  int sample, time_sample, ret;
8161  unsigned int i;
8162 
8163  // Here we consider timestamp to be PTS, hence try to offset it so that we
8164  // can search over the DTS timeline.
8165  timestamp -= (sc->min_corrected_pts + sc->dts_shift);
8166 
8167  ret = mov_seek_fragment(s, st, timestamp);
8168  if (ret < 0)
8169  return ret;
8170 
8171  sample = av_index_search_timestamp(st, timestamp, flags);
8172  av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
8173  if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
8174  sample = 0;
8175  if (sample < 0) /* not sure what to do */
8176  return AVERROR_INVALIDDATA;
8178  av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
8179  /* adjust ctts index */
8180  if (sc->ctts_data) {
8181  time_sample = 0;
8182  for (i = 0; i < sc->ctts_count; i++) {
8183  int next = time_sample + sc->ctts_data[i].count;
8184  if (next > sc->current_sample) {
8185  sc->ctts_index = i;
8186  sc->ctts_sample = sc->current_sample - time_sample;
8187  break;
8188  }
8189  time_sample = next;
8190  }
8191  }
8192 
8193  /* adjust stsd index */
8194  if (sc->chunk_count) {
8195  time_sample = 0;
8196  for (i = 0; i < sc->stsc_count; i++) {
8197  int64_t next = time_sample + mov_get_stsc_samples(sc, i);
8198  if (next > sc->current_sample) {
8199  sc->stsc_index = i;
8200  sc->stsc_sample = sc->current_sample - time_sample;
8201  break;
8202  }
8203  av_assert0(next == (int)next);
8204  time_sample = next;
8205  }
8206  }
8207 
8208  return sample;
8209 }
8210 
8212 {
8213  MOVStreamContext *sc = st->priv_data;
8214  int64_t first_ts = st->index_entries[0].timestamp;
8216  int64_t off;
8217 
8219  return 0;
8220 
8221  /* compute skip samples according to stream start_pad, seek ts and first ts */
8222  off = av_rescale_q(ts - first_ts, st->time_base,
8223  (AVRational){1, st->codecpar->sample_rate});
8224  return FFMAX(sc->start_pad - off, 0);
8225 }
8226 
8227 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
8228 {
8229  MOVContext *mc = s->priv_data;
8230  AVStream *st;
8231  int sample;
8232  int i;
8233 
8234  if (stream_index >= s->nb_streams)
8235  return AVERROR_INVALIDDATA;
8236 
8237  st = s->streams[stream_index];
8238  sample = mov_seek_stream(s, st, sample_time, flags);
8239  if (sample < 0)
8240  return sample;
8241 
8242  if (mc->seek_individually) {
8243  /* adjust seek timestamp to found sample timestamp */
8244  int64_t seek_timestamp = st->index_entries[sample].timestamp;
8246 
8247  for (i = 0; i < s->nb_streams; i++) {
8248  int64_t timestamp;
8249  st = s->streams[i];
8250 
8251  if (stream_index == i)
8252  continue;
8253 
8254  timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
8255  sample = mov_seek_stream(s, st, timestamp, flags);
8256  if (sample >= 0)
8258  }
8259  } else {
8260  for (i = 0; i < s->nb_streams; i++) {
8261  MOVStreamContext *sc;
8262  st = s->streams[i];
8263  sc = st->priv_data;
8264  mov_current_sample_set(sc, 0);
8265  }
8266  while (1) {
8267  MOVStreamContext *sc;
8268  AVIndexEntry *entry = mov_find_next_sample(s, &st);
8269  if (!entry)
8270  return AVERROR_INVALIDDATA;
8271  sc = st->priv_data;
8272  if (sc->ffindex == stream_index && sc->current_sample == sample)
8273  break;
8275  }
8276  }
8277  return 0;
8278 }
8279 
8280 #define OFFSET(x) offsetof(MOVContext, x)
8281 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
8282 static const AVOption mov_options[] = {
8283  {"use_absolute_path",
8284  "allow using absolute path when opening alias, this is a possible security issue",
8285  OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
8286  0, 1, FLAGS},
8287  {"seek_streams_individually",
8288  "Seek each stream individually to the closest point",
8289  OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
8290  0, 1, FLAGS},
8291  {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
8292  0, 1, FLAGS},
8293  {"advanced_editlist",
8294  "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
8295  OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
8296  0, 1, FLAGS},
8297  {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
8298  0, 1, FLAGS},
8299  {"use_mfra_for",
8300  "use mfra for fragment timestamps",
8301  OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
8303  "use_mfra_for"},
8304  {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
8305  FLAGS, "use_mfra_for" },
8306  {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
8307  FLAGS, "use_mfra_for" },
8308  {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
8309  FLAGS, "use_mfra_for" },
8310  { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
8311  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
8312  { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
8313  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
8314  { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
8316  { "audible_key", "AES-128 Key for Audible AAXC files", OFFSET(audible_key),
8318  { "audible_iv", "AES-128 IV for Audible AAXC files", OFFSET(audible_iv),
8320  { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
8321  "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
8322  AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
8323  .flags = AV_OPT_FLAG_DECODING_PARAM },
8324  { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
8325  { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
8326  {.i64 = 0}, 0, 1, FLAGS },
8327 
8328  { NULL },
8329 };
8330 
8331 static const AVClass mov_class = {
8332  .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
8333  .item_name = av_default_item_name,
8334  .option = mov_options,
8335  .version = LIBAVUTIL_VERSION_INT,
8336 };
8337 
8339  .name = "mov,mp4,m4a,3gp,3g2,mj2",
8340  .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
8341  .priv_class = &mov_class,
8342  .priv_data_size = sizeof(MOVContext),
8343  .extensions = "mov,mp4,m4a,3gp,3g2,mj2,psp,m4b,ism,ismv,isma,f4v",
8344  .read_probe = mov_probe,
8350 };
const uint16_t avpriv_ac3_channel_layout_tab[8]
Map audio coding mode (acmod) to channel layout mask.
Definition: ac3tab.c:89
int av_aes_ctr_init(struct AVAESCTR *a, const uint8_t *key)
Initialize an AVAESCTR context.
Definition: aes_ctr.c:69
void av_aes_ctr_set_full_iv(struct AVAESCTR *a, const uint8_t *iv)
Forcefully change the "full" 16-byte iv, including the counter.
Definition: aes_ctr.c:48
struct AVAESCTR * av_aes_ctr_alloc(void)
Allocate an AVAESCTR context.
Definition: aes_ctr.c:36
void av_aes_ctr_free(struct AVAESCTR *a)
Release an AVAESCTR context.
Definition: aes_ctr.c:84
void av_aes_ctr_crypt(struct AVAESCTR *a, uint8_t *dst, const uint8_t *src, int count)
Process a buffer using a previously initialized context.
Definition: aes_ctr.c:111
#define AES_CTR_KEY_SIZE
Definition: aes_ctr.h:30
static double val(void *priv, double ch)
Definition: aeval.c:76
static const char *const format[]
Definition: af_aiir.c:456
Macro definitions for various function/variable attributes.
uint8_t
int32_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define FF_COMPLIANCE_STRICT
Strictly conform to all the things in the spec no matter what consequences.
Definition: avcodec.h:1603
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition: avformat.h:1562
#define AVINDEX_KEYFRAME
Definition: avformat.h:811
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:453
#define AVFMT_FLAG_IGNIDX
Ignore index.
Definition: avformat.h:1365
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition: avformat.h:470
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:451
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2417
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:310
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:841
#define AVFMT_SEEK_TO_PTS
Seeking is based on PTS.
Definition: avformat.h:484
#define AVINDEX_DISCARD_FRAME
Definition: avformat.h:812
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:2415
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:818
#define AV_DISPOSITION_TIMED_THUMBNAILS
The stream is sparse, and contains thumbnail images, often corresponding to chapter markers.
Definition: avformat.h:846
@ AVSTREAM_PARSE_HEADERS
Only parse headers, do not repack.
Definition: avformat.h:795
@ AVSTREAM_PARSE_FULL
full parsing and repack
Definition: avformat.h:794
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:253
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:902
#define AVIO_FLAG_READ
read-only
Definition: avio.h:674
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:342
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:766
int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a UTF-16 string from pb and convert it to UTF-8.
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:364
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:337
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:633
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:750
int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a string from pb into buf.
Definition: aviobuf.c:860
unsigned int avio_rb24(AVIOContext *s)
Definition: aviobuf.c:774
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:781
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:624
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition: aviobuf.c:998
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:682
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:88
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t size)
Definition: avpacket.c:343
#define AV_RB32
Definition: intreadwrite.h:130
#define AV_RB16
Definition: intreadwrite.h:53
#define AV_RL32
Definition: intreadwrite.h:146
#define AV_RB64
Definition: intreadwrite.h:164
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:101
#define av_bswap32
Definition: bswap.h:33
#define flag(name)
Definition: cbs_av1.c: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:636
#define AV_PKT_FLAG_DISCARD
Flag is used to discard packets which are required to maintain valid decoder state but are not requir...
Definition: packet.h:417
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:634
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
#define AV_PKT_FLAG_DISPOSABLE
Flag is used to indicate packets that contain frames that can be discarded by the decoder.
Definition: packet.h:429
FF_ENABLE_DEPRECATION_WARNINGS int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as a packet side data.
Definition: avpacket.c:309
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:99
@ AV_PKT_DATA_ICC_PROFILE
ICC profile data consisting of an opaque octet buffer following the format described by ISO 15076-1.
Definition: packet.h:274
@ AV_PKT_DATA_MASTERING_DISPLAY_METADATA
Mastering display metadata (based on SMPTE-2086:2014).
Definition: packet.h:222
@ AV_PKT_DATA_AUDIO_SERVICE_TYPE
This side data should be associated with an audio stream and corresponds to enum AVAudioServiceType.
Definition: packet.h:120
@ AV_PKT_DATA_SPHERICAL
This side data should be associated with a video stream and corresponds to the AVSphericalMapping str...
Definition: packet.h:228
@ AV_PKT_DATA_PALETTE
An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE bytes worth of palette.
Definition: packet.h:46
@ AV_PKT_DATA_ENCRYPTION_INFO
This side data contains encryption info for how to decrypt the packet.
Definition: packet.h:255
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: packet.h:108
@ AV_PKT_DATA_ENCRYPTION_INIT_INFO
This side data is encryption initialization data.
Definition: packet.h:249
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: packet.h:55
@ AV_PKT_DATA_STEREO3D
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition: packet.h:114
@ AV_PKT_DATA_CONTENT_LIGHT_LEVEL
Content light level (based on CTA-861.3).
Definition: packet.h:235
@ AV_PKT_DATA_DOVI_CONF
DOVI configuration ref: dolby-vision-bitstreams-within-the-iso-base-media-file-format-v2....
Definition: packet.h:283
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, size_t size)
Allocate new information from stream.
uint8_t * av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, size_t *size)
Get side information from stream.
int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type, uint8_t *data, size_t size)
Wrap an existing array as stream side data.
Definition: utils.c:5522
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4436
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:211
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4509
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:4799
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:2130
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition: aes.c:31
void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt)
Encrypt or decrypt a buffer using a previously initialized context.
Definition: aes.c:163
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:74
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:76
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function.
Definition: dict.h:72
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition: dict.h:69
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set that converts the value to a string and stores it.
Definition: dict.c:147
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:220
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:188
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
#define AV_LOG_INFO
Standard information.
Definition: log.h:205
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition: rational.h:71
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition: rational.c:106
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
void * av_realloc(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory.
Definition: mem.c:134
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition: mem.c:478
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:161
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
Definition: mem.c:198
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array through a pointer to a pointer.
Definition: mem.c:206
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
Definition: mem.c:190
#define av_fourcc2str(fourcc)
Definition: avutil.h:348
#define AV_FOURCC_MAX_STRING_SIZE
Definition: avutil.h:346
char * av_fourcc_make_string(char *buf, uint32_t fourcc)
Fill the provided buffer with a string containing a FourCC (four-character code) representation.
Definition: utils.c:116
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition: avutil.h:203
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition: sha.c:45
void av_sha_update(struct AVSHA *ctx, const uint8_t *data, unsigned int len)
Update hash value.
Definition: sha.c:315
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition: sha.c:345
av_cold int av_sha_init(AVSHA *ctx, int bits)
Initialize SHA-1 or SHA-2 hashing.
Definition: sha.c:273
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition: avstring.c:93
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition: avstring.c:56
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
double av_display_rotation_get(const int32_t matrix[9])
Extract the rotation component of the transformation matrix.
Definition: display.c:34
AVSphericalProjection
Projection of the video surface(s) on a sphere.
Definition: spherical.h:51
AVSphericalMapping * av_spherical_alloc(size_t *size)
Allocate a AVSphericalVideo structure and initialize its fields to default values.
Definition: spherical.c:25
@ AV_SPHERICAL_EQUIRECTANGULAR
Video represents a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:56
@ AV_SPHERICAL_EQUIRECTANGULAR_TILE
Video represents a portion of a sphere mapped on a flat surface using equirectangular projection.
Definition: spherical.h:72
@ AV_SPHERICAL_CUBEMAP
Video frame is split into 6 faces of a cube, and arranged on a 3x2 layout.
Definition: spherical.h:65
AVStereo3DType
List of possible 3D Types.
Definition: stereo3d.h:51
AVStereo3D * av_stereo3d_alloc(void)
Allocate an AVStereo3D structure and set its fields to default values.
Definition: stereo3d.c:28
@ AV_STEREO3D_2D
Video is not stereoscopic (and metadata has to be there).
Definition: stereo3d.h:55
@ AV_STEREO3D_TOPBOTTOM
Views are on top of each other.
Definition: stereo3d.h:79
@ AV_STEREO3D_SIDEBYSIDE
Views are next to each other.
Definition: stereo3d.h:67
int index
Definition: gxfenc.c:89
cl_device_type type
const char * key
const char *const ff_id3v1_genre_str[ID3v1_GENRE_MAX+1]
ID3v1 genres.
Definition: id3v1.c:27
#define ID3v1_GENRE_MAX
Definition: id3v1.h:29
int i
Definition: input.c:407
static av_always_inline float av_int2float(uint32_t i)
Reinterpret a 32-bit integer as a float.
Definition: intfloat.h:40
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:60
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
#define AV_RB8(x)
Definition: intreadwrite.h:395
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define AV_WB8(p, d)
Definition: intreadwrite.h:396
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
#define AV_WL16(p, v)
Definition: intreadwrite.h:412
int ff_mov_lang_to_iso639(unsigned code, char to[4])
Definition: isom.c:260
const AVCodecTag ff_codec_movdata_tags[]
Definition: isom.c:82
const AVCodecTag ff_codec_movsubtitle_tags[]
Definition: isom.c:75
#define MOV_TRUN_SAMPLE_DURATION
Definition: isom.h:324
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
Definition: mov_esds.c:23
#define FF_MOV_FLAG_MFRA_PTS
Definition: isom.h:373
#define MOV_TRUN_SAMPLE_CTS
Definition: isom.h:327
#define MOV_TKHD_FLAG_ENABLED
Definition: isom.h:339
#define MOV_TFHD_DEFAULT_BASE_IS_MOOF
Definition: isom.h:320
#define FF_MOV_FLAG_MFRA_DTS
Definition: isom.h:372
const AVCodecTag ff_codec_movaudio_tags[]
Definition: isom_tags.c:278
#define MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES
Definition: isom.h:337
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom_tags.c:29
#define MOV_TFHD_DEFAULT_SIZE
Definition: isom.h:317
#define TAG_IS_AVCI(tag)
Definition: isom.h:349
#define MOV_TRUN_FIRST_SAMPLE_FLAGS
Definition: isom.h:323
#define MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC
Definition: isom.h:330
#define MOV_TFHD_STSD_ID
Definition: isom.h:315
#define MOV_TRUN_SAMPLE_FLAGS
Definition: isom.h:326
#define MOV_TFHD_DEFAULT_FLAGS
Definition: isom.h:318
#define MOV_TRUN_DATA_OFFSET
Definition: isom.h:322
#define MOV_TFHD_BASE_DATA_OFFSET
Definition: isom.h:314
static enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
Compute codec id for 'lpcm' tag.
Definition: isom.h:379
#define MOV_TRUN_SAMPLE_SIZE
Definition: isom.h:325
#define MOV_SAMPLE_DEPENDENCY_NO
Definition: isom.h:346
#define FF_MOV_FLAG_MFRA_AUTO
Definition: isom.h:371
#define MOV_TFHD_DEFAULT_DURATION
Definition: isom.h:316
static const struct ColorPrimaries color_primaries[AVCOL_PRI_NB]
int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt, uint8_t *buf, int buf_size, int64_t pos)
Definition: dv.c:371
DVDemuxContext * avpriv_dv_init_demux(AVFormatContext *s)
Definition: dv.c:338
int avpriv_dv_get_packet(DVDemuxContext *c, AVPacket *pkt)
Definition: dv.c:354
void ff_rfps_calculate(AVFormatContext *ic)
Definition: utils.c:3408
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t dts)
add frame for rfps calculation.
Definition: utils.c:3348
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
Definition: utils.c:2065
int ff_generate_avci_extradata(AVStream *st)
Generate standard extradata for AVC-Intra based on width/height and field order.
Definition: utils.c:5370
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4945
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0.
Definition: utils.c:3314
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5692
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:4639
int ff_get_extradata(AVFormatContext *s, AVCodecParameters *par, AVIOContext *pb, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0 and f...
Definition: utils.c:3332
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:3131
static int read_probe(const AVProbeData *pd)
Definition: jvdec.c:55
#define FF_API_OLD_ROTATE_API
Definition: version.h:80
common internal API header
int buffer_size_t
Definition: internal.h:306
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:83
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
Stereoscopic video.
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
version
Definition: libkvazaar.c:326
#define isnan(x)
Definition: libm.h:340
static av_const double hypot(double x, double y)
Definition: libm.h:366
AVContentLightMetadata * av_content_light_metadata_alloc(size_t *size)
Allocate an AVContentLightMetadata structure and set its fields to default values.
AVMasteringDisplayMetadata * av_mastering_display_metadata_alloc(void)
Copyright (c) 2016 Neil Birkbeck neil.birkbeck@gmail.com
static int truehd_channels(int chanmap)
Definition: mlp_parse.h:88
static int mlp_samplerate(int in)
Definition: mlp_parse.h:80
static uint64_t truehd_layout(int chanmap)
Definition: mlp_parse.h:98
static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4401
static int64_t mov_get_skip_samples(AVStream *st, int sample)
Definition: mov.c:8211
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 mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
Definition: mov.c:8227
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:6820
static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
Definition: mov.c:7912
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:8157
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mov.c:7992
static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:7058
AVInputFormat ff_mov_demuxer
Definition: mov.c:8338
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:6260
static int mov_read_saio(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6359
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:5375
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:7668
static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6665
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:5615
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:5386
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:5662
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:6756
static const AVClass mov_class
Definition: mov.c:8331
static int mov_read_sample_encryption_info(MOVContext *c, AVIOContext *pb, MOVStreamContext *sc, AVEncryptionInfo **sample, int use_subsamples)
Definition: mov.c:6086
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:5458
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:7386
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:6869
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:6563
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:7567
static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
Definition: mov.c:8138
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:8281
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:6901
static int should_retry(AVIOContext *pb, int error_code)
Definition: mov.c:7905
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:5586
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:6454
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:7622
#define MIN_DATA_ENTRY_BOX_SIZE
Definition: mov.c:577
static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5505
static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
Definition: mov.c:7411
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:7372
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:6958
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:6287
static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5967
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:7878
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:6036
static int mov_read_close(AVFormatContext *s)
Definition: mov.c:7451
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:6594
static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5862
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 get_eia608_packet(AVIOContext *pb, AVPacket *pkt, int size)
Definition: mov.c:7971
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:6193
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:5414
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:6702
static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:6137
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:7439
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:8280
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:5549
static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:5989
static int mov_codec_id(AVStream *st, uint32_t format)
Definition: mov.c:2088
static void export_orphan_timecode(AVFormatContext *s)
Definition: mov.c:7549
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:7182
static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
Definition: mov.c:5799
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:7948
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:7533
static void mov_read_chapters(AVFormatContext *s)
Definition: mov.c:7273
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:8282
int ff_mov_read_chan(AVFormatContext *s, AVIOContext *pb, AVStream *st, int64_t size)
Read 'chan' tag from the input stream.
Definition: mov_chan.c:547
uint32_t tag
Definition: movenc.c:1611
MPEG Audio header decoder.
static int ff_mpa_check_header(uint32_t header)
const char data[16]
Definition: mxf.c:142
int cid
Definition: mxfenc.c:2039
static float distance(float x, float y, int band)
#define OPUS_SEEK_PREROLL_MS
Definition: oggparseopus.c:35
AVOptions.
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:279
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
Definition: pixdesc.c:2940
const char * av_color_space_name(enum AVColorSpace space)
Definition: pixdesc.c:2961
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
Definition: pixdesc.c:2919
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition: pixfmt.h:569
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:586
#define AVPALETTE_SIZE
Definition: pixfmt.h:32
@ AVCOL_PRI_UNSPECIFIED
Definition: pixfmt.h:461
@ AVCOL_TRC_UNSPECIFIED
Definition: pixfmt.h:486
@ AVCOL_SPC_UNSPECIFIED
Definition: pixfmt.h:515
int ff_get_qtpalette(int codec_id, AVIOContext *pb, uint32_t *palette)
Retrieve the palette (or "color table" in QuickTime terms), either from the video sample description,...
Definition: qtpalette.c:323
#define tc
Definition: regdef.h:69
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition: replaygain.c:91
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:33
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:508
internal header for RIFF based (de)muxers do NOT include this in end user applications
int ff_get_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int size, int big_endian)
Definition: riffdec.c:91
static char buffer[20]
Definition: seek.c:32
Public header for SHA-1 & SHA-256 hash function implementations.
#define snprintf
Definition: snprintf.h:34
unsigned int pos
Definition: spdifenc.c:412
Spherical video.
A reference to a data buffer.
Definition: buffer.h:84
Describe the class of an AVClass context structure.
Definition: log.h:67
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
enum AVAudioServiceType audio_service_type
Type of service that the audio stream conveys.
Definition: avcodec.h:1261
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:659
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
enum AVColorSpace color_space
Definition: codec_par.h:149
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
int frame_size
Audio only.
Definition: codec_par.h:181
enum AVFieldOrder field_order
Video only.
Definition: codec_par.h:141
uint64_t channel_layout
Audio only.
Definition: codec_par.h:162
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: codec_par.h:102
int channels
Audio only.
Definition: codec_par.h:166
int width
Video only.
Definition: codec_par.h:126
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: codec_par.h:89
int seek_preroll
Audio only.
Definition: codec_par.h:200
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
int block_align
Audio only.
Definition: codec_par.h:177
int video_delay
Video only.
Definition: codec_par.h:155
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
enum AVColorPrimaries color_primaries
Definition: codec_par.h:147
int sample_rate
Audio only.
Definition: codec_par.h:170
enum AVColorTransferCharacteristic color_trc
Definition: codec_par.h:148
int initial_padding
Audio only.
Definition: codec_par.h:189
enum AVColorRange color_range
Video only.
Definition: codec_par.h:146
unsigned MaxFALL
Max average light level per frame (cd/m^2).
unsigned MaxCLL
Max content light level (cd/m^2).
char * value
Definition: dict.h:83
This describes encryption info for a packet.
uint32_t skip_byte_block
Only used for pattern encryption.
uint8_t * iv
The initialization vector.
uint32_t crypt_byte_block
Only used for pattern encryption.
uint8_t * key_id
The ID of the key used to encrypt the packet.
uint32_t scheme
The fourcc encryption scheme, in big-endian byte order.
This describes info used to initialize an encryption key system.
uint8_t * data
Key-system specific initialization data.
struct AVEncryptionInitInfo * next
An optional pointer to the next initialization info in the list.
uint8_t ** key_ids
An array of key IDs this initialization data is for.
uint8_t * system_id
A unique identifier for the key system this is for, can be NULL if it is not known.
uint32_t num_key_ids
The number of key IDs.
Format I/O context.
Definition: avformat.h:1232
Bytestream IO Context.
Definition: avio.h:161
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
int eof_reached
true if was unable to read due to error or eof
Definition: avio.h:239
int64_t pos
Definition: avformat.h:804
int min_distance
Minimum distance between this and the previous keyframe, used to avoid unneeded searching.
Definition: avformat.h:815
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:805
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:645
int has_primaries
Flag indicating whether the display primaries (and white point) are set.
AVRational max_luminance
Max luminance of mastering display (cd/m^2).
AVRational min_luminance
Min luminance of mastering display (cd/m^2).
AVRational display_primaries[3][2]
CIE 1931 xy chromaticity coords of color primaries (r, g, b order).
AVRational white_point[2]
CIE 1931 xy chromaticity coords of white point.
int has_luminance
Flag indicating whether the luminance (min_ and max_) have been set.
AVOption.
Definition: opt.h:248
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: packet.h:352
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
int64_t pos
byte position in stream, -1 if unknown
Definition: packet.h:389
This structure contains the data a format has to probe a file.
Definition: avformat.h:441
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:444
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:443
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
hash context
Definition: sha.c:34
uint64_t count
number of bytes in buffer
Definition: sha.c:36
uint32_t bound_left
Distance from the left edge.
Definition: spherical.h:167
enum AVSphericalProjection projection
Projection type.
Definition: spherical.h:86
uint32_t bound_top
Distance from the top edge.
Definition: spherical.h:168
uint32_t bound_bottom
Distance from the bottom edge.
Definition: spherical.h:170
uint32_t bound_right
Distance from the right edge.
Definition: spherical.h:169
int32_t pitch
Rotation around the right vector [-90, 90].
Definition: spherical.h:127
int32_t roll
Rotation around the forward vector [-180, 180].
Definition: spherical.h:128
int32_t yaw
Rotation around the up vector [-180, 180].
Definition: spherical.h:126
uint32_t padding
Number of pixels to pad from the edge of each cube face.
Definition: spherical.h:182
enum AVStereo3DType type
How views are packed within the video.
Definition: stereo3d.h:180
int skip_samples
Number of samples to skip at the start of the frame decoded from the next packet.
Definition: internal.h:258
Stream structure.
Definition: avformat.h:873
unsigned int index_entries_allocated_size
Definition: avformat.h:1093
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1038
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:935
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:924
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:928
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:922
AVDictionary * metadata
Definition: avformat.h:937
void * priv_data
Definition: avformat.h:888
int id
Format-specific stream ID.
Definition: avformat.h:880
int index
stream index in AVFormatContext
Definition: avformat.h:874
int nb_index_entries
Definition: avformat.h:1092
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition: avformat.h:912
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition: avformat.h:955
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:946
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:902
attribute_deprecated AVCodecContext * codec
Definition: avformat.h:886
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1090
enum AVStreamParseType need_parsing
Definition: avformat.h:1081
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1015
AVStreamInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1113
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:926
This file is part of FFmpeg.
Definition: isom.h:82
uint32_t type
Definition: isom.h:83
int64_t size
Definition: isom.h:84
int handbrake_version
Definition: isom.h:264
int * bitrates
bitrates read before streams creation
Definition: isom.h:275
int ignore_editlist
Definition: isom.h:268
unsigned meta_keys_count
Definition: isom.h:256
char ** meta_keys
Definition: isom.h:255
AVFormatContext * fc
Definition: isom.h:248
unsigned int aax_mode
'aax' file has been detected
Definition: isom.h:282
int found_mdat
'mdat' atom has been found
Definition: isom.h:252
int bitrates_count
Definition: isom.h:276
int * chapter_tracks
Definition: isom.h:265
int64_t next_root_atom
offset of the next root atom
Definition: isom.h:272
int ignore_chapters
Definition: isom.h:270
DVDemuxContext * dv_demux
Definition: isom.h:257
unsigned int nb_chapter_tracks
Definition: isom.h:266
uint8_t * decryption_key
Definition: isom.h:294
MOVFragmentIndex frag_index
Definition: isom.h:280
MOVTrackExt * trex_data
Definition: isom.h:261
struct AVAES * aes_decrypt
Definition: isom.h:293
int decryption_key_len
Definition: isom.h:295
MOVFragment fragment
current fragment in moof atom
Definition: isom.h:260
AVFormatContext * dv_fctx
Definition: isom.h:258
int moov_retry
Definition: isom.h:277
int time_scale
Definition: isom.h:249
int found_moov
'moov' atom has been found
Definition: isom.h:251
int advanced_editlist
Definition: isom.h:269
int trak_index
Index of the current 'trak'.
Definition: isom.h:254
int use_mfra_for
Definition: isom.h:278
Definition: isom.h:73
char volume[28]
Definition: isom.h:77
char * dir
Definition: isom.h:76
int16_t nlvl_to
Definition: isom.h:79
char * path
Definition: isom.h:75
uint32_t type
Definition: isom.h:74
int16_t nlvl_from
Definition: isom.h:79
char filename[64]
Definition: isom.h:78
Definition: isom.h:67
float rate
Definition: isom.h:70
int64_t duration
Definition: isom.h:68
int64_t time
Definition: isom.h:69
uint64_t * auxiliary_offsets
Absolute seek position.
Definition: isom.h:123
unsigned int nb_encrypted_samples
Definition: isom.h:117
size_t auxiliary_offsets_count
Definition: isom.h:124
size_t auxiliary_info_sample_count
Definition: isom.h:121
uint8_t auxiliary_info_default_size
Definition: isom.h:122
uint8_t * auxiliary_info_sizes
Definition: isom.h:120
AVEncryptionInfo ** encrypted_samples
Definition: isom.h:118
MOVFragmentStreamInfo * stream_info
Definition: isom.h:142
int64_t moof_offset
Definition: isom.h:138
MOVFragmentIndexItem * item
Definition: isom.h:150
int complete
Definition: isom.h:147
int nb_items
Definition: isom.h:149
MOVEncryptionIndex * encryption_index
Definition: isom.h:134
int64_t tfdt_dts
Definition: isom.h:131
int64_t next_trun_dts
Definition: isom.h:132
int64_t first_tfra_pts
Definition: isom.h:130
int64_t sidx_pts
Definition: isom.h:129
unsigned track_id
Definition: isom.h:91
unsigned flags
Definition: isom.h:98
unsigned duration
Definition: isom.h:96
int found_tfhd
Definition: isom.h:90
unsigned size
Definition: isom.h:97
unsigned stsd_id
Definition: isom.h:95
uint64_t base_data_offset
Definition: isom.h:92
uint64_t moof_offset
Definition: isom.h:93
uint64_t implicit_offset
Definition: isom.h:94
int64_t start
Definition: isom.h:154
int64_t end
Definition: isom.h:155
int(* parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:74
uint32_t type
Definition: mov.c:73
unsigned int index
Definition: isom.h:111
unsigned int count
Definition: isom.h:110
int64_t time_offset
time offset of the edit list entries
Definition: isom.h:190
int64_t duration_for_fps
Definition: isom.h:218
AVIOContext * pb
Definition: isom.h:159
size_t spherical_size
Definition: isom.h:230
uint8_t ** extradata
extradata array (and size) for multiple stsd
Definition: isom.h:221
MOVSbgp * rap_group
Definition: isom.h:215
MOVEncryptionIndex * encryption_index
Definition: isom.h:242
int64_t track_end
used for dts generation in fragmented movie files
Definition: isom.h:212
int pseudo_stream_id
-1 means demux all ids
Definition: isom.h:199
unsigned int rap_group_count
Definition: isom.h:214
int height
tkhd height
Definition: isom.h:206
int stsc_sample
Definition: isom.h:175
MOVDref * drefs
Definition: isom.h:202
MOVStts * ctts_data
Definition: isom.h:171
unsigned int ctts_allocated_size
Definition: isom.h:170
unsigned int per_sample_iv_size
Definition: isom.h:240
int * extradata_size
Definition: isom.h:222
struct MOVStreamContext::@261 cenc
size_t coll_size
Definition: isom.h:233
int dv_audio_container
Definition: isom.h:198
AVContentLightMetadata * coll
Definition: isom.h:232
int64_t * chunk_offsets
Definition: isom.h:164
MOVStsc * stsc_data
Definition: isom.h:173
AVStereo3D * stereo3d
Definition: isom.h:228
int32_t * display_matrix
Definition: isom.h:227
int current_sample
Definition: isom.h:192
unsigned int samples_per_frame
Definition: isom.h:197
int start_pad
amount of samples to skip due to enc-dec delay
Definition: isom.h:213
int nb_frames_for_fps
Definition: isom.h:217
uint32_t format
Definition: isom.h:235
int keyframe_absent
Definition: isom.h:186
MOVElst * elst_data
Definition: isom.h:178
int64_t current_index
Definition: isom.h:193
unsigned int stts_count
Definition: isom.h:165
uint8_t * sdtp_data
Definition: isom.h:168
unsigned int sample_size
may contain value calculated from stsd or value from stsz atom
Definition: isom.h:182
AVEncryptionInfo * default_encrypted_sample
Definition: isom.h:241
int timecode_track
Definition: isom.h:204
int16_t audio_cid
stsd audio compression id
Definition: isom.h:200
int ctts_sample
Definition: isom.h:181
struct AVAESCTR * aes_ctr
Definition: isom.h:239
MOVStts * stts_data
Definition: isom.h:166
int last_stsd_index
Definition: isom.h:223
int stsd_count
Definition: isom.h:224
unsigned int chunk_count
Definition: isom.h:163
int64_t data_size
Definition: isom.h:210
int pb_is_copied
Definition: isom.h:160
int * keyframes
Definition: isom.h:188
int has_sidx
Definition: isom.h:237
unsigned drefs_count
Definition: isom.h:201
MOVIndexRange * current_index_range
Definition: isom.h:195
AVMasteringDisplayMetadata * mastering
Definition: isom.h:231
int width
tkhd width
Definition: isom.h:205
unsigned int sdtp_count
Definition: isom.h:167
unsigned int sample_count
Definition: isom.h:184
int dts_shift
dts shift when ctts is negative
Definition: isom.h:207
int stsd_version
Definition: isom.h:225
int time_scale
Definition: isom.h:189
unsigned int stsc_index
Definition: isom.h:174
int64_t min_corrected_pts
minimum Composition time shown by the edits excluding empty edits.
Definition: isom.h:191
int has_palette
Definition: isom.h:209
int ctts_index
Definition: isom.h:180
uint32_t palette[256]
Definition: isom.h:208
int ffindex
AVStream index.
Definition: isom.h:161
int * sample_sizes
Definition: isom.h:185
AVSphericalMapping * spherical
Definition: isom.h:229
unsigned int keyframe_count
Definition: isom.h:187
unsigned int bytes_per_frame
Definition: isom.h:196
uint32_t tmcd_flags
tmcd track flags
Definition: isom.h:211
unsigned * stps_data
partial sync sample for mpeg-2 open gop
Definition: isom.h:177
MOVIndexRange * index_ranges
Definition: isom.h:194
unsigned int stsc_count
Definition: isom.h:172
unsigned int stsz_sample_size
always contains sample size from stsz atom
Definition: isom.h:183
unsigned int elst_count
Definition: isom.h:179
unsigned int ctts_count
Definition: isom.h:169
unsigned int stps_count
Definition: isom.h:176
int first
Definition: isom.h:62
int count
Definition: isom.h:63
int id
Definition: isom.h:64
Definition: isom.h:56
unsigned int count
Definition: isom.h:57
int duration
Definition: isom.h:58
unsigned flags
Definition: isom.h:106
unsigned duration
Definition: isom.h:104
unsigned size
Definition: isom.h:105
unsigned track_id
Definition: isom.h:102
unsigned stsd_id
Definition: isom.h:103
#define av_free(p)
#define av_malloc_array(a, b)
#define ff_dlog(a,...)
#define av_realloc_f(p, o, n)
#define avpriv_request_sample(...)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
#define src
Definition: vp8dsp.c:255
static int ref[MAX_W *MAX_W]
Definition: jpeg2000dwt.c:107
FILE * out
Definition: movenc.c:54
int64_t duration
Definition: movenc.c:64
AVPacket * pkt
Definition: movenc.c:59
AVFormatContext * ctx
Definition: movenc.c:48
static void finish(void)
Definition: movenc.c:342
#define height
#define width
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum)
Load timecode string in buf.
Definition: timecode.c:102
int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx)
Init a timecode struct with the passed parameters.
Definition: timecode.c:219
Timecode helpers header.
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
@ AV_TIMECODE_FLAG_ALLOWNEGATIVE
negative time values are allowed
Definition: timecode.h:38
@ AV_TIMECODE_FLAG_DROPFRAME
timecode is drop frame
Definition: timecode.h:36
@ AV_TIMECODE_FLAG_24HOURSMAX
timecode wraps after 24 hours
Definition: timecode.h:37
static int64_t pts
int size
enum AVCodecID codec_id
Definition: vaapi_decode.c:369
#define mc
const char * b
Definition: vf_curves.c:118
const char * g
Definition: vf_curves.c:117
const char * r
Definition: vf_curves.c:116
static double cr(void *priv, double x, double y)
Definition: vf_geq.c:216
static double cb(void *priv, double x, double y)
Definition: vf_geq.c:215
if(ret< 0)
Definition: vf_mcdeint.c:282
static float mean(const float *input, int size)
Definition: vf_nnedi.c:864
color_range
static const uint8_t offset[127][2]
Definition: vf_spp.c:107
static void rotate(const float rot_quaternion[2][4], float *vec)
Rotate vector with given rotation quaternion.
Definition: vf_v360.c:3919
int len
static int parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
Definition: vp3_parser.c:23
static double c[64]