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