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