FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
mov.c
Go to the documentation of this file.
1 /*
2  * MOV demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * first version by Francois Revol <revol@free.fr>
7  * seek function by Gael Chardon <gael.dev@4now.net>
8  *
9  * This file is part of FFmpeg.
10  *
11  * FFmpeg is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * FFmpeg is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with FFmpeg; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25 
26 #include <inttypes.h>
27 #include <limits.h>
28 #include <stdint.h>
29 
30 #include "libavutil/attributes.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/intreadwrite.h"
34 #include "libavutil/intfloat.h"
35 #include "libavutil/mathematics.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/display.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/aes.h"
42 #include "libavutil/aes_ctr.h"
43 #include "libavutil/sha.h"
44 #include "libavutil/timecode.h"
45 #include "libavcodec/ac3tab.h"
46 #include "avformat.h"
47 #include "internal.h"
48 #include "avio_internal.h"
49 #include "riff.h"
50 #include "isom.h"
51 #include "libavcodec/get_bits.h"
52 #include "id3v1.h"
53 #include "mov_chan.h"
54 #include "replaygain.h"
55 
56 #if CONFIG_ZLIB
57 #include <zlib.h>
58 #endif
59 
60 #include "qtpalette.h"
61 
62 /* those functions parse an atom */
63 /* links atom IDs to parse functions */
64 typedef struct MOVParseTableEntry {
65  uint32_t type;
66  int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
68 
69 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
70 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
71 
73  unsigned len, const char *key)
74 {
75  char buf[16];
76 
77  short current, total = 0;
78  avio_rb16(pb); // unknown
79  current = avio_rb16(pb);
80  if (len >= 6)
81  total = avio_rb16(pb);
82  if (!total)
83  snprintf(buf, sizeof(buf), "%d", current);
84  else
85  snprintf(buf, sizeof(buf), "%d/%d", current, total);
87  av_dict_set(&c->fc->metadata, key, buf, 0);
88 
89  return 0;
90 }
91 
93  unsigned len, const char *key)
94 {
95  /* bypass padding bytes */
96  avio_r8(pb);
97  avio_r8(pb);
98  avio_r8(pb);
99 
101  av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
102 
103  return 0;
104 }
105 
107  unsigned len, const char *key)
108 {
110  av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
111 
112  return 0;
113 }
114 
116  unsigned len, const char *key)
117 {
118  short genre;
119 
120  avio_r8(pb); // unknown
121 
122  genre = avio_r8(pb);
123  if (genre < 1 || genre > ID3v1_GENRE_MAX)
124  return 0;
126  av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
127 
128  return 0;
129 }
130 
131 static const uint32_t mac_to_unicode[128] = {
132  0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
133  0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
134  0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
135  0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
136  0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
137  0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
138  0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
139  0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
140  0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
141  0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
142  0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
143  0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
144  0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
145  0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
146  0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
147  0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
148 };
149 
151  char *dst, int dstlen)
152 {
153  char *p = dst;
154  char *end = dst+dstlen-1;
155  int i;
156 
157  for (i = 0; i < len; i++) {
158  uint8_t t, c = avio_r8(pb);
159  if (c < 0x80 && p < end)
160  *p++ = c;
161  else if (p < end)
162  PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
163  }
164  *p = 0;
165  return p - dst;
166 }
167 
168 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
169 {
170  AVPacket pkt;
171  AVStream *st;
172  MOVStreamContext *sc;
173  enum AVCodecID id;
174  int ret;
175 
176  switch (type) {
177  case 0xd: id = AV_CODEC_ID_MJPEG; break;
178  case 0xe: id = AV_CODEC_ID_PNG; break;
179  case 0x1b: id = AV_CODEC_ID_BMP; break;
180  default:
181  av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
182  avio_skip(pb, len);
183  return 0;
184  }
185 
186  st = avformat_new_stream(c->fc, NULL);
187  if (!st)
188  return AVERROR(ENOMEM);
189  sc = av_mallocz(sizeof(*sc));
190  if (!sc)
191  return AVERROR(ENOMEM);
192  st->priv_data = sc;
193 
194  ret = av_get_packet(pb, &pkt, len);
195  if (ret < 0)
196  return ret;
197 
198  if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
199  if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
200  id = AV_CODEC_ID_PNG;
201  } else {
202  id = AV_CODEC_ID_MJPEG;
203  }
204  }
205 
207 
208  st->attached_pic = pkt;
209  st->attached_pic.stream_index = st->index;
211 
213  st->codecpar->codec_id = id;
214 
215  return 0;
216 }
217 
218 // 3GPP TS 26.244
219 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
220 {
221  char language[4] = { 0 };
222  char buf[200], place[100];
223  uint16_t langcode = 0;
224  double longitude, latitude, altitude;
225  const char *key = "location";
226 
227  if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
228  av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
229  return AVERROR_INVALIDDATA;
230  }
231 
232  avio_skip(pb, 4); // version+flags
233  langcode = avio_rb16(pb);
234  ff_mov_lang_to_iso639(langcode, language);
235  len -= 6;
236 
237  len -= avio_get_str(pb, len, place, sizeof(place));
238  if (len < 1) {
239  av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
240  return AVERROR_INVALIDDATA;
241  }
242  avio_skip(pb, 1); // role
243  len -= 1;
244 
245  if (len < 12) {
246  av_log(c->fc, AV_LOG_ERROR,
247  "loci too short (%u bytes left, need at least %d)\n", len, 12);
248  return AVERROR_INVALIDDATA;
249  }
250  longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
251  latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
252  altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
253 
254  // Try to output in the same format as the ?xyz field
255  snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
256  if (altitude)
257  av_strlcatf(buf, sizeof(buf), "%+f", altitude);
258  av_strlcatf(buf, sizeof(buf), "/%s", place);
259 
260  if (*language && strcmp(language, "und")) {
261  char key2[16];
262  snprintf(key2, sizeof(key2), "%s-%s", key, language);
263  av_dict_set(&c->fc->metadata, key2, buf, 0);
264  }
266  return av_dict_set(&c->fc->metadata, key, buf, 0);
267 }
268 
270 {
271  char tmp_key[5];
272  char key2[32], language[4] = {0};
273  char *str = NULL;
274  const char *key = NULL;
275  uint16_t langcode = 0;
276  uint32_t data_type = 0, str_size, str_size_alloc;
277  int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
278  int raw = 0;
279  int num = 0;
280 
281  switch (atom.type) {
282  case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
283  case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
284  case MKTAG( 'X','M','P','_'):
285  if (c->export_xmp) { key = "xmp"; raw = 1; } break;
286  case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
287  case MKTAG( 'a','k','I','D'): key = "account_type";
289  case MKTAG( 'a','p','I','D'): key = "account_id"; break;
290  case MKTAG( 'c','a','t','g'): key = "category"; break;
291  case MKTAG( 'c','p','i','l'): key = "compilation";
293  case MKTAG( 'c','p','r','t'): key = "copyright"; break;
294  case MKTAG( 'd','e','s','c'): key = "description"; break;
295  case MKTAG( 'd','i','s','k'): key = "disc";
297  case MKTAG( 'e','g','i','d'): key = "episode_uid";
299  case MKTAG( 'g','n','r','e'): key = "genre";
300  parse = mov_metadata_gnre; break;
301  case MKTAG( 'h','d','v','d'): key = "hd_video";
303  case MKTAG( 'k','e','y','w'): key = "keywords"; break;
304  case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
305  case MKTAG( 'l','o','c','i'):
306  return mov_metadata_loci(c, pb, atom.size);
307  case MKTAG( 'p','c','s','t'): key = "podcast";
309  case MKTAG( 'p','g','a','p'): key = "gapless_playback";
311  case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
312  case MKTAG( 'r','t','n','g'): key = "rating";
314  case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
315  case MKTAG( 's','o','a','l'): key = "sort_album"; break;
316  case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
317  case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
318  case MKTAG( 's','o','n','m'): key = "sort_name"; break;
319  case MKTAG( 's','o','s','n'): key = "sort_show"; break;
320  case MKTAG( 's','t','i','k'): key = "media_type";
322  case MKTAG( 't','r','k','n'): key = "track";
324  case MKTAG( 't','v','e','n'): key = "episode_id"; break;
325  case MKTAG( 't','v','e','s'): key = "episode_sort";
327  case MKTAG( 't','v','n','n'): key = "network"; break;
328  case MKTAG( 't','v','s','h'): key = "show"; break;
329  case MKTAG( 't','v','s','n'): key = "season_number";
331  case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
332  case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
333  case MKTAG(0xa9,'a','l','b'): key = "album"; break;
334  case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
335  case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
336  case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
337  case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
338  case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
339  case MKTAG(0xa9,'d','a','y'): key = "date"; break;
340  case MKTAG(0xa9,'d','i','r'): key = "director"; break;
341  case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
342  case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
343  case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
344  case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
345  case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
346  case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
347  case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
348  case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
349  case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
350  case MKTAG(0xa9,'m','a','k'): key = "make"; break;
351  case MKTAG(0xa9,'m','o','d'): key = "model"; break;
352  case MKTAG(0xa9,'n','a','m'): key = "title"; break;
353  case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
354  case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
355  case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
356  case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
357  case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
358  case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
359  case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
360  case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
361  case MKTAG(0xa9,'t','r','k'): key = "track"; break;
362  case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
363  case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
364  case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
365  case MKTAG(0xa9,'x','y','z'): key = "location"; break;
366  }
367 retry:
368  if (c->itunes_metadata && atom.size > 8) {
369  int data_size = avio_rb32(pb);
370  int tag = avio_rl32(pb);
371  if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
372  data_type = avio_rb32(pb); // type
373  avio_rb32(pb); // unknown
374  str_size = data_size - 16;
375  atom.size -= 16;
376 
377  if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
378  int ret = mov_read_covr(c, pb, data_type, str_size);
379  if (ret < 0) {
380  av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
381  }
382  return ret;
383  } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
384  uint32_t index = AV_RB32(&atom.type);
385  if (index < c->meta_keys_count) {
386  key = c->meta_keys[index];
387  } else {
389  "The index of 'data' is out of range: %d >= %d.\n",
390  index, c->meta_keys_count);
391  }
392  }
393  } else return 0;
394  } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
395  str_size = avio_rb16(pb); // string length
396  if (str_size > atom.size) {
397  raw = 1;
398  avio_seek(pb, -2, SEEK_CUR);
399  av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
400  goto retry;
401  }
402  langcode = avio_rb16(pb);
403  ff_mov_lang_to_iso639(langcode, language);
404  atom.size -= 4;
405  } else
406  str_size = atom.size;
407 
408  if (c->export_all && !key) {
409  snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
410  key = tmp_key;
411  }
412 
413  if (!key)
414  return 0;
415  if (atom.size < 0 || str_size >= INT_MAX/2)
416  return AVERROR_INVALIDDATA;
417 
418  // Allocates enough space if data_type is a int32 or float32 number, otherwise
419  // worst-case requirement for output string in case of utf8 coded input
420  num = (data_type >= 21 && data_type <= 23);
421  str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
422  str = av_mallocz(str_size_alloc);
423  if (!str)
424  return AVERROR(ENOMEM);
425 
426  if (parse)
427  parse(c, pb, str_size, key);
428  else {
429  if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
430  mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
431  } else if (data_type == 21) { // BE signed integer, variable size
432  int val = 0;
433  if (str_size == 1)
434  val = (int8_t)avio_r8(pb);
435  else if (str_size == 2)
436  val = (int16_t)avio_rb16(pb);
437  else if (str_size == 3)
438  val = ((int32_t)(avio_rb24(pb)<<8))>>8;
439  else if (str_size == 4)
440  val = (int32_t)avio_rb32(pb);
441  if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
442  av_log(c->fc, AV_LOG_ERROR,
443  "Failed to store the number (%d) in string.\n", val);
444  av_free(str);
445  return AVERROR_INVALIDDATA;
446  }
447  } else if (data_type == 22) { // BE unsigned integer, variable size
448  unsigned int val = 0;
449  if (str_size == 1)
450  val = avio_r8(pb);
451  else if (str_size == 2)
452  val = avio_rb16(pb);
453  else if (str_size == 3)
454  val = avio_rb24(pb);
455  else if (str_size == 4)
456  val = avio_rb32(pb);
457  if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
458  av_log(c->fc, AV_LOG_ERROR,
459  "Failed to store the number (%u) in string.\n", val);
460  av_free(str);
461  return AVERROR_INVALIDDATA;
462  }
463  } else if (data_type == 23 && str_size >= 4) { // BE float32
464  float val = av_int2float(avio_rb32(pb));
465  if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
466  av_log(c->fc, AV_LOG_ERROR,
467  "Failed to store the float32 number (%f) in string.\n", val);
468  av_free(str);
469  return AVERROR_INVALIDDATA;
470  }
471  } else {
472  int ret = ffio_read_size(pb, str, str_size);
473  if (ret < 0) {
474  av_free(str);
475  return ret;
476  }
477  str[str_size] = 0;
478  }
480  av_dict_set(&c->fc->metadata, key, str, 0);
481  if (*language && strcmp(language, "und")) {
482  snprintf(key2, sizeof(key2), "%s-%s", key, language);
483  av_dict_set(&c->fc->metadata, key2, str, 0);
484  }
485  if (!strcmp(key, "encoder")) {
486  int major, minor, micro;
487  if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
488  c->handbrake_version = 1000000*major + 1000*minor + micro;
489  }
490  }
491  }
492  av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
493  av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
494  key, str, (char*)&atom.type, str_size_alloc, atom.size);
495 
496  av_freep(&str);
497  return 0;
498 }
499 
501 {
502  int64_t start;
503  int i, nb_chapters, str_len, version;
504  char str[256+1];
505  int ret;
506 
507  if (c->ignore_chapters)
508  return 0;
509 
510  if ((atom.size -= 5) < 0)
511  return 0;
512 
513  version = avio_r8(pb);
514  avio_rb24(pb);
515  if (version)
516  avio_rb32(pb); // ???
517  nb_chapters = avio_r8(pb);
518 
519  for (i = 0; i < nb_chapters; i++) {
520  if (atom.size < 9)
521  return 0;
522 
523  start = avio_rb64(pb);
524  str_len = avio_r8(pb);
525 
526  if ((atom.size -= 9+str_len) < 0)
527  return 0;
528 
529  ret = ffio_read_size(pb, str, str_len);
530  if (ret < 0)
531  return ret;
532  str[str_len] = 0;
533  avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
534  }
535  return 0;
536 }
537 
538 #define MIN_DATA_ENTRY_BOX_SIZE 12
540 {
541  AVStream *st;
542  MOVStreamContext *sc;
543  int entries, i, j;
544 
545  if (c->fc->nb_streams < 1)
546  return 0;
547  st = c->fc->streams[c->fc->nb_streams-1];
548  sc = st->priv_data;
549 
550  avio_rb32(pb); // version + flags
551  entries = avio_rb32(pb);
552  if (!entries ||
553  entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
554  entries >= UINT_MAX / sizeof(*sc->drefs))
555  return AVERROR_INVALIDDATA;
556  sc->drefs_count = 0;
557  av_free(sc->drefs);
558  sc->drefs_count = 0;
559  sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
560  if (!sc->drefs)
561  return AVERROR(ENOMEM);
562  sc->drefs_count = entries;
563 
564  for (i = 0; i < entries; i++) {
565  MOVDref *dref = &sc->drefs[i];
566  uint32_t size = avio_rb32(pb);
567  int64_t next = avio_tell(pb) + size - 4;
568 
569  if (size < 12)
570  return AVERROR_INVALIDDATA;
571 
572  dref->type = avio_rl32(pb);
573  avio_rb32(pb); // version + flags
574  av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
575 
576  if (dref->type == MKTAG('a','l','i','s') && size > 150) {
577  /* macintosh alias record */
578  uint16_t volume_len, len;
579  int16_t type;
580  int ret;
581 
582  avio_skip(pb, 10);
583 
584  volume_len = avio_r8(pb);
585  volume_len = FFMIN(volume_len, 27);
586  ret = ffio_read_size(pb, dref->volume, 27);
587  if (ret < 0)
588  return ret;
589  dref->volume[volume_len] = 0;
590  av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
591 
592  avio_skip(pb, 12);
593 
594  len = avio_r8(pb);
595  len = FFMIN(len, 63);
596  ret = ffio_read_size(pb, dref->filename, 63);
597  if (ret < 0)
598  return ret;
599  dref->filename[len] = 0;
600  av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
601 
602  avio_skip(pb, 16);
603 
604  /* read next level up_from_alias/down_to_target */
605  dref->nlvl_from = avio_rb16(pb);
606  dref->nlvl_to = avio_rb16(pb);
607  av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
608  dref->nlvl_from, dref->nlvl_to);
609 
610  avio_skip(pb, 16);
611 
612  for (type = 0; type != -1 && avio_tell(pb) < next; ) {
613  if(avio_feof(pb))
614  return AVERROR_EOF;
615  type = avio_rb16(pb);
616  len = avio_rb16(pb);
617  av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
618  if (len&1)
619  len += 1;
620  if (type == 2) { // absolute path
621  av_free(dref->path);
622  dref->path = av_mallocz(len+1);
623  if (!dref->path)
624  return AVERROR(ENOMEM);
625 
626  ret = ffio_read_size(pb, dref->path, len);
627  if (ret < 0) {
628  av_freep(&dref->path);
629  return ret;
630  }
631  if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
632  len -= volume_len;
633  memmove(dref->path, dref->path+volume_len, len);
634  dref->path[len] = 0;
635  }
636  // trim string of any ending zeros
637  for (j = len - 1; j >= 0; j--) {
638  if (dref->path[j] == 0)
639  len--;
640  else
641  break;
642  }
643  for (j = 0; j < len; j++)
644  if (dref->path[j] == ':' || dref->path[j] == 0)
645  dref->path[j] = '/';
646  av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
647  } else if (type == 0) { // directory name
648  av_free(dref->dir);
649  dref->dir = av_malloc(len+1);
650  if (!dref->dir)
651  return AVERROR(ENOMEM);
652 
653  ret = ffio_read_size(pb, dref->dir, len);
654  if (ret < 0) {
655  av_freep(&dref->dir);
656  return ret;
657  }
658  dref->dir[len] = 0;
659  for (j = 0; j < len; j++)
660  if (dref->dir[j] == ':')
661  dref->dir[j] = '/';
662  av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
663  } else
664  avio_skip(pb, len);
665  }
666  } else {
667  av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
668  dref->type, size);
669  entries--;
670  i--;
671  }
672  avio_seek(pb, next, SEEK_SET);
673  }
674  return 0;
675 }
676 
678 {
679  AVStream *st;
680  uint32_t type;
681  uint32_t av_unused ctype;
682  int64_t title_size;
683  char *title_str;
684  int ret;
685 
686  avio_r8(pb); /* version */
687  avio_rb24(pb); /* flags */
688 
689  /* component type */
690  ctype = avio_rl32(pb);
691  type = avio_rl32(pb); /* component subtype */
692 
693  av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
694  av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
695 
696  if (c->trak_index < 0) { // meta not inside a trak
697  if (type == MKTAG('m','d','t','a')) {
698  c->found_hdlr_mdta = 1;
699  }
700  return 0;
701  }
702 
703  st = c->fc->streams[c->fc->nb_streams-1];
704 
705  if (type == MKTAG('v','i','d','e'))
707  else if (type == MKTAG('s','o','u','n'))
709  else if (type == MKTAG('m','1','a',' '))
711  else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
713 
714  avio_rb32(pb); /* component manufacture */
715  avio_rb32(pb); /* component flags */
716  avio_rb32(pb); /* component flags mask */
717 
718  title_size = atom.size - 24;
719  if (title_size > 0) {
720  title_str = av_malloc(title_size + 1); /* Add null terminator */
721  if (!title_str)
722  return AVERROR(ENOMEM);
723 
724  ret = ffio_read_size(pb, title_str, title_size);
725  if (ret < 0) {
726  av_freep(&title_str);
727  return ret;
728  }
729  title_str[title_size] = 0;
730  if (title_str[0]) {
731  int off = (!c->isom && title_str[0] == title_size - 1);
732  av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
733  }
734  av_freep(&title_str);
735  }
736 
737  return 0;
738 }
739 
741 {
742  AVStream *st;
743  int tag;
744 
745  if (fc->nb_streams < 1)
746  return 0;
747  st = fc->streams[fc->nb_streams-1];
748 
749  avio_rb32(pb); /* version + flags */
750  ff_mp4_read_descr(fc, pb, &tag);
751  if (tag == MP4ESDescrTag) {
753  } else
754  avio_rb16(pb); /* ID */
755 
756  ff_mp4_read_descr(fc, pb, &tag);
757  if (tag == MP4DecConfigDescrTag)
758  ff_mp4_read_dec_config_descr(fc, st, pb);
759  return 0;
760 }
761 
763 {
764  return ff_mov_read_esds(c->fc, pb);
765 }
766 
768 {
769  AVStream *st;
770  enum AVAudioServiceType *ast;
771  int ac3info, acmod, lfeon, bsmod;
772 
773  if (c->fc->nb_streams < 1)
774  return 0;
775  st = c->fc->streams[c->fc->nb_streams-1];
776 
778  sizeof(*ast));
779  if (!ast)
780  return AVERROR(ENOMEM);
781 
782  ac3info = avio_rb24(pb);
783  bsmod = (ac3info >> 14) & 0x7;
784  acmod = (ac3info >> 11) & 0x7;
785  lfeon = (ac3info >> 10) & 0x1;
786  st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
788  if (lfeon)
790  *ast = bsmod;
791  if (st->codecpar->channels > 1 && bsmod == 0x7)
793 
794 #if FF_API_LAVF_AVCTX
796  st->codec->audio_service_type = *ast;
798 #endif
799 
800  return 0;
801 }
802 
804 {
805  AVStream *st;
806  enum AVAudioServiceType *ast;
807  int eac3info, acmod, lfeon, bsmod;
808 
809  if (c->fc->nb_streams < 1)
810  return 0;
811  st = c->fc->streams[c->fc->nb_streams-1];
812 
814  sizeof(*ast));
815  if (!ast)
816  return AVERROR(ENOMEM);
817 
818  /* No need to parse fields for additional independent substreams and its
819  * associated dependent substreams since libavcodec's E-AC-3 decoder
820  * does not support them yet. */
821  avio_rb16(pb); /* data_rate and num_ind_sub */
822  eac3info = avio_rb24(pb);
823  bsmod = (eac3info >> 12) & 0x1f;
824  acmod = (eac3info >> 9) & 0x7;
825  lfeon = (eac3info >> 8) & 0x1;
827  if (lfeon)
830  *ast = bsmod;
831  if (st->codecpar->channels > 1 && bsmod == 0x7)
833 
834 #if FF_API_LAVF_AVCTX
836  st->codec->audio_service_type = *ast;
838 #endif
839 
840  return 0;
841 }
842 
844 {
845  const uint32_t ddts_size = 20;
846  AVStream *st = NULL;
847  uint8_t *buf = NULL;
848  uint32_t frame_duration_code = 0;
849  uint32_t channel_layout_code = 0;
850  GetBitContext gb;
851 
852  buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
853  if (!buf) {
854  return AVERROR(ENOMEM);
855  }
856  if (avio_read(pb, buf, ddts_size) < ddts_size) {
857  av_free(buf);
858  return AVERROR_INVALIDDATA;
859  }
860 
861  init_get_bits(&gb, buf, 8*ddts_size);
862 
863  if (c->fc->nb_streams < 1) {
864  return 0;
865  }
866  st = c->fc->streams[c->fc->nb_streams-1];
867 
868  st->codecpar->sample_rate = get_bits_long(&gb, 32);
869  skip_bits_long(&gb, 32); /* max bitrate */
870  st->codecpar->bit_rate = get_bits_long(&gb, 32);
871  st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
872  frame_duration_code = get_bits(&gb, 2);
873  skip_bits(&gb, 30); /* various fields */
874  channel_layout_code = get_bits(&gb, 16);
875 
876  st->codecpar->frame_size =
877  (frame_duration_code == 0) ? 512 :
878  (frame_duration_code == 1) ? 1024 :
879  (frame_duration_code == 2) ? 2048 :
880  (frame_duration_code == 3) ? 4096 : 0;
881 
882  if (channel_layout_code > 0xff) {
883  av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
884  }
885  st->codecpar->channel_layout =
886  ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
887  ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
888  ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
889  ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
890  ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
891  ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
892 
894 
895  return 0;
896 }
897 
899 {
900  AVStream *st;
901 
902  if (c->fc->nb_streams < 1)
903  return 0;
904  st = c->fc->streams[c->fc->nb_streams-1];
905 
906  if (atom.size < 16)
907  return 0;
908 
909  /* skip version and flags */
910  avio_skip(pb, 4);
911 
912  ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
913 
914  return 0;
915 }
916 
918 {
919  AVStream *st;
920  int ret;
921 
922  if (c->fc->nb_streams < 1)
923  return 0;
924  st = c->fc->streams[c->fc->nb_streams-1];
925 
926  if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
927  av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
928 
929  return ret;
930 }
931 
933 {
934  const int num = avio_rb32(pb);
935  const int den = avio_rb32(pb);
936  AVStream *st;
937 
938  if (c->fc->nb_streams < 1)
939  return 0;
940  st = c->fc->streams[c->fc->nb_streams-1];
941 
942  if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
943  (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
945  "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
947  num, den);
948  } else if (den != 0) {
950  num, den, 32767);
951  }
952  return 0;
953 }
954 
955 /* this atom contains actual media data */
957 {
958  if (atom.size == 0) /* wrong one (MP4) */
959  return 0;
960  c->found_mdat=1;
961  return 0; /* now go for moov */
962 }
963 
964 #define DRM_BLOB_SIZE 56
965 
967 {
968  uint8_t intermediate_key[20];
969  uint8_t intermediate_iv[20];
970  uint8_t input[64];
971  uint8_t output[64];
972  uint8_t file_checksum[20];
973  uint8_t calculated_checksum[20];
974  struct AVSHA *sha;
975  int i;
976  int ret = 0;
977  uint8_t *activation_bytes = c->activation_bytes;
978  uint8_t *fixed_key = c->audible_fixed_key;
979 
980  c->aax_mode = 1;
981 
982  sha = av_sha_alloc();
983  if (!sha)
984  return AVERROR(ENOMEM);
985  c->aes_decrypt = av_aes_alloc();
986  if (!c->aes_decrypt) {
987  ret = AVERROR(ENOMEM);
988  goto fail;
989  }
990 
991  /* drm blob processing */
992  avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
993  avio_read(pb, input, DRM_BLOB_SIZE);
994  avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
995  avio_read(pb, file_checksum, 20);
996 
997  av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
998  for (i = 0; i < 20; i++)
999  av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
1000  av_log(c->fc, AV_LOG_INFO, "\n");
1001 
1002  /* verify activation data */
1003  if (!activation_bytes) {
1004  av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1005  ret = 0; /* allow ffprobe to continue working on .aax files */
1006  goto fail;
1007  }
1008  if (c->activation_bytes_size != 4) {
1009  av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1010  ret = AVERROR(EINVAL);
1011  goto fail;
1012  }
1013 
1014  /* verify fixed key */
1015  if (c->audible_fixed_key_size != 16) {
1016  av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1017  ret = AVERROR(EINVAL);
1018  goto fail;
1019  }
1020 
1021  /* AAX (and AAX+) key derivation */
1022  av_sha_init(sha, 160);
1023  av_sha_update(sha, fixed_key, 16);
1024  av_sha_update(sha, activation_bytes, 4);
1025  av_sha_final(sha, intermediate_key);
1026  av_sha_init(sha, 160);
1027  av_sha_update(sha, fixed_key, 16);
1028  av_sha_update(sha, intermediate_key, 20);
1029  av_sha_update(sha, activation_bytes, 4);
1030  av_sha_final(sha, intermediate_iv);
1031  av_sha_init(sha, 160);
1032  av_sha_update(sha, intermediate_key, 16);
1033  av_sha_update(sha, intermediate_iv, 16);
1034  av_sha_final(sha, calculated_checksum);
1035  if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1036  av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1037  ret = AVERROR_INVALIDDATA;
1038  goto fail;
1039  }
1040  av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1041  av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1042  for (i = 0; i < 4; i++) {
1043  // file data (in output) is stored in big-endian mode
1044  if (activation_bytes[i] != output[3 - i]) { // critical error
1045  av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1046  ret = AVERROR_INVALIDDATA;
1047  goto fail;
1048  }
1049  }
1050  memcpy(c->file_key, output + 8, 16);
1051  memcpy(input, output + 26, 16);
1052  av_sha_init(sha, 160);
1053  av_sha_update(sha, input, 16);
1054  av_sha_update(sha, c->file_key, 16);
1055  av_sha_update(sha, fixed_key, 16);
1056  av_sha_final(sha, c->file_iv);
1057 
1058 fail:
1059  av_free(sha);
1060 
1061  return ret;
1062 }
1063 
1064 // Audible AAX (and AAX+) bytestream decryption
1065 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1066 {
1067  int blocks = 0;
1068  unsigned char iv[16];
1069 
1070  memcpy(iv, c->file_iv, 16); // iv is overwritten
1071  blocks = size >> 4; // trailing bytes are not encrypted!
1072  av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1073  av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1074 
1075  return 0;
1076 }
1077 
1078 /* read major brand, minor version and compatible brands and store them as metadata */
1080 {
1081  uint32_t minor_ver;
1082  int comp_brand_size;
1083  char* comp_brands_str;
1084  uint8_t type[5] = {0};
1085  int ret = ffio_read_size(pb, type, 4);
1086  if (ret < 0)
1087  return ret;
1088 
1089  if (strcmp(type, "qt "))
1090  c->isom = 1;
1091  av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1092  av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1093  minor_ver = avio_rb32(pb); /* minor version */
1094  av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1095 
1096  comp_brand_size = atom.size - 8;
1097  if (comp_brand_size < 0)
1098  return AVERROR_INVALIDDATA;
1099  comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1100  if (!comp_brands_str)
1101  return AVERROR(ENOMEM);
1102 
1103  ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1104  if (ret < 0) {
1105  av_freep(&comp_brands_str);
1106  return ret;
1107  }
1108  comp_brands_str[comp_brand_size] = 0;
1109  av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1110  av_freep(&comp_brands_str);
1111 
1112  return 0;
1113 }
1114 
1115 /* this atom should contain all header atoms */
1117 {
1118  int ret;
1119 
1120  if (c->found_moov) {
1121  av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1122  avio_skip(pb, atom.size);
1123  return 0;
1124  }
1125 
1126  if ((ret = mov_read_default(c, pb, atom)) < 0)
1127  return ret;
1128  /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1129  /* so we don't parse the whole file if over a network */
1130  c->found_moov=1;
1131  return 0; /* now go for mdat */
1132 }
1133 
1135 {
1136  if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1137  c->has_looked_for_mfra = 1;
1138  if (pb->seekable) {
1139  int ret;
1140  av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1141  "for a mfra\n");
1142  if ((ret = mov_read_mfra(c, pb)) < 0) {
1143  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1144  "read the mfra (may be a live ismv)\n");
1145  }
1146  } else {
1147  av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1148  "seekable, can not look for mfra\n");
1149  }
1150  }
1152  av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1153  return mov_read_default(c, pb, atom);
1154 }
1155 
1156 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1157 {
1158  char buffer[32];
1159  if (time) {
1160  struct tm *ptm, tmbuf;
1161  time_t timet;
1162  if(time >= 2082844800)
1163  time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
1164  timet = time;
1165  ptm = gmtime_r(&timet, &tmbuf);
1166  if (!ptm) return;
1167  if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1168  av_dict_set(metadata, "creation_time", buffer, 0);
1169  }
1170 }
1171 
1173 {
1174  AVStream *st;
1175  MOVStreamContext *sc;
1176  int version;
1177  char language[4] = {0};
1178  unsigned lang;
1179  int64_t creation_time;
1180 
1181  if (c->fc->nb_streams < 1)
1182  return 0;
1183  st = c->fc->streams[c->fc->nb_streams-1];
1184  sc = st->priv_data;
1185 
1186  if (sc->time_scale) {
1187  av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1188  return AVERROR_INVALIDDATA;
1189  }
1190 
1191  version = avio_r8(pb);
1192  if (version > 1) {
1193  avpriv_request_sample(c->fc, "Version %d", version);
1194  return AVERROR_PATCHWELCOME;
1195  }
1196  avio_rb24(pb); /* flags */
1197  if (version == 1) {
1198  creation_time = avio_rb64(pb);
1199  avio_rb64(pb);
1200  } else {
1201  creation_time = avio_rb32(pb);
1202  avio_rb32(pb); /* modification time */
1203  }
1204  mov_metadata_creation_time(&st->metadata, creation_time);
1205 
1206  sc->time_scale = avio_rb32(pb);
1207  st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1208 
1209  lang = avio_rb16(pb); /* language */
1210  if (ff_mov_lang_to_iso639(lang, language))
1211  av_dict_set(&st->metadata, "language", language, 0);
1212  avio_rb16(pb); /* quality */
1213 
1214  return 0;
1215 }
1216 
1218 {
1219  int64_t creation_time;
1220  int version = avio_r8(pb); /* version */
1221  avio_rb24(pb); /* flags */
1222 
1223  if (version == 1) {
1224  creation_time = avio_rb64(pb);
1225  avio_rb64(pb);
1226  } else {
1227  creation_time = avio_rb32(pb);
1228  avio_rb32(pb); /* modification time */
1229  }
1230  mov_metadata_creation_time(&c->fc->metadata, creation_time);
1231  c->time_scale = avio_rb32(pb); /* time scale */
1232 
1233  av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1234 
1235  c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1236  // set the AVCodecContext duration because the duration of individual tracks
1237  // may be inaccurate
1238  if (c->time_scale > 0 && !c->trex_data)
1240  avio_rb32(pb); /* preferred scale */
1241 
1242  avio_rb16(pb); /* preferred volume */
1243 
1244  avio_skip(pb, 10); /* reserved */
1245 
1246  avio_skip(pb, 36); /* display matrix */
1247 
1248  avio_rb32(pb); /* preview time */
1249  avio_rb32(pb); /* preview duration */
1250  avio_rb32(pb); /* poster time */
1251  avio_rb32(pb); /* selection time */
1252  avio_rb32(pb); /* selection duration */
1253  avio_rb32(pb); /* current time */
1254  avio_rb32(pb); /* next track ID */
1255 
1256  return 0;
1257 }
1258 
1260 {
1261  AVStream *st;
1262  int little_endian;
1263 
1264  if (c->fc->nb_streams < 1)
1265  return 0;
1266  st = c->fc->streams[c->fc->nb_streams-1];
1267 
1268  little_endian = avio_rb16(pb) & 0xFF;
1269  av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1270  if (little_endian == 1) {
1271  switch (st->codecpar->codec_id) {
1272  case AV_CODEC_ID_PCM_S24BE:
1274  break;
1275  case AV_CODEC_ID_PCM_S32BE:
1277  break;
1278  case AV_CODEC_ID_PCM_F32BE:
1280  break;
1281  case AV_CODEC_ID_PCM_F64BE:
1283  break;
1284  default:
1285  break;
1286  }
1287  }
1288  return 0;
1289 }
1290 
1292 {
1293  AVStream *st;
1294  char color_parameter_type[5] = { 0 };
1295  uint16_t color_primaries, color_trc, color_matrix;
1296  int ret;
1297 
1298  if (c->fc->nb_streams < 1)
1299  return 0;
1300  st = c->fc->streams[c->fc->nb_streams - 1];
1301 
1302  ret = ffio_read_size(pb, color_parameter_type, 4);
1303  if (ret < 0)
1304  return ret;
1305  if (strncmp(color_parameter_type, "nclx", 4) &&
1306  strncmp(color_parameter_type, "nclc", 4)) {
1307  av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1308  color_parameter_type);
1309  return 0;
1310  }
1311 
1312  color_primaries = avio_rb16(pb);
1313  color_trc = avio_rb16(pb);
1314  color_matrix = avio_rb16(pb);
1315 
1316  av_log(c->fc, AV_LOG_TRACE,
1317  "%s: pri %d trc %d matrix %d",
1318  color_parameter_type, color_primaries, color_trc, color_matrix);
1319 
1320  if (!strncmp(color_parameter_type, "nclx", 4)) {
1321  uint8_t color_range = avio_r8(pb) >> 7;
1322  av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1323  if (color_range)
1325  else
1327  /* 14496-12 references JPEG XR specs (rather than the more complete
1328  * 23001-8) so some adjusting is required */
1329  if (color_primaries >= AVCOL_PRI_FILM)
1330  color_primaries = AVCOL_PRI_UNSPECIFIED;
1331  if ((color_trc >= AVCOL_TRC_LINEAR &&
1332  color_trc <= AVCOL_TRC_LOG_SQRT) ||
1333  color_trc >= AVCOL_TRC_BT2020_10)
1334  color_trc = AVCOL_TRC_UNSPECIFIED;
1335  if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1336  color_matrix = AVCOL_SPC_UNSPECIFIED;
1338  st->codecpar->color_trc = color_trc;
1339  st->codecpar->color_space = color_matrix;
1340  } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1341  /* color primaries, Table 4-4 */
1342  switch (color_primaries) {
1343  case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
1344  case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
1345  case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
1346  }
1347  /* color transfer, Table 4-5 */
1348  switch (color_trc) {
1349  case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
1350  case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
1351  }
1352  /* color matrix, Table 4-6 */
1353  switch (color_matrix) {
1354  case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
1355  case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
1356  case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
1357  }
1358  }
1359  av_log(c->fc, AV_LOG_TRACE, "\n");
1360 
1361  return 0;
1362 }
1363 
1365 {
1366  AVStream *st;
1367  unsigned mov_field_order;
1368  enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1369 
1370  if (c->fc->nb_streams < 1) // will happen with jp2 files
1371  return 0;
1372  st = c->fc->streams[c->fc->nb_streams-1];
1373  if (atom.size < 2)
1374  return AVERROR_INVALIDDATA;
1375  mov_field_order = avio_rb16(pb);
1376  if ((mov_field_order & 0xFF00) == 0x0100)
1377  decoded_field_order = AV_FIELD_PROGRESSIVE;
1378  else if ((mov_field_order & 0xFF00) == 0x0200) {
1379  switch (mov_field_order & 0xFF) {
1380  case 0x01: decoded_field_order = AV_FIELD_TT;
1381  break;
1382  case 0x06: decoded_field_order = AV_FIELD_BB;
1383  break;
1384  case 0x09: decoded_field_order = AV_FIELD_TB;
1385  break;
1386  case 0x0E: decoded_field_order = AV_FIELD_BT;
1387  break;
1388  }
1389  }
1390  if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1391  av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1392  }
1393  st->codecpar->field_order = decoded_field_order;
1394 
1395  return 0;
1396 }
1397 
1399 {
1400  int err = 0;
1401  uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1402  if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1403  return AVERROR_INVALIDDATA;
1404  if ((err = av_reallocp(&par->extradata, size)) < 0) {
1405  par->extradata_size = 0;
1406  return err;
1407  }
1409  return 0;
1410 }
1411 
1412 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1414  AVCodecParameters *par, uint8_t *buf)
1415 {
1416  int64_t result = atom.size;
1417  int err;
1418 
1419  AV_WB32(buf , atom.size + 8);
1420  AV_WL32(buf + 4, atom.type);
1421  err = ffio_read_size(pb, buf + 8, atom.size);
1422  if (err < 0) {
1423  par->extradata_size -= atom.size;
1424  return err;
1425  } else if (err < atom.size) {
1426  av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1427  par->extradata_size -= atom.size - err;
1428  result = err;
1429  }
1430  memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1431  return result;
1432 }
1433 
1434 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1436  enum AVCodecID codec_id)
1437 {
1438  AVStream *st;
1439  uint64_t original_size;
1440  int err;
1441 
1442  if (c->fc->nb_streams < 1) // will happen with jp2 files
1443  return 0;
1444  st = c->fc->streams[c->fc->nb_streams-1];
1445 
1446  if (st->codecpar->codec_id != codec_id)
1447  return 0; /* unexpected codec_id - don't mess with extradata */
1448 
1449  original_size = st->codecpar->extradata_size;
1450  err = mov_realloc_extradata(st->codecpar, atom);
1451  if (err)
1452  return err;
1453 
1454  err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
1455  if (err < 0)
1456  return err;
1457  return 0; // Note: this is the original behavior to ignore truncation.
1458 }
1459 
1460 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1462 {
1463  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1464 }
1465 
1467 {
1468  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1469 }
1470 
1472 {
1473  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1474 }
1475 
1477 {
1478  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1479 }
1480 
1482 {
1483  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1484  if(ret == 0)
1485  ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1486  return ret;
1487 }
1488 
1490 {
1491  int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1492 
1493  if (!ret && c->fc->nb_streams >= 1) {
1494  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1495  if (par->extradata_size >= 40) {
1496  par->height = AV_RB16(&par->extradata[36]);
1497  par->width = AV_RB16(&par->extradata[38]);
1498  }
1499  }
1500  return ret;
1501 }
1502 
1504 {
1505  if (c->fc->nb_streams >= 1) {
1506  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1507  if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1508  par->codec_id == AV_CODEC_ID_H264 &&
1509  atom.size > 11) {
1510  int cid;
1511  avio_skip(pb, 10);
1512  cid = avio_rb16(pb);
1513  /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1514  if (cid == 0xd4d || cid == 0xd4e)
1515  par->width = 1440;
1516  return 0;
1517  } else if (par->codec_tag == MKTAG('A', 'V', 'd', '1') &&
1518  atom.size >= 24) {
1519  int num, den;
1520  avio_skip(pb, 12);
1521  num = avio_rb32(pb);
1522  den = avio_rb32(pb);
1523  if (num <= 0 || den <= 0)
1524  return 0;
1525  switch (avio_rb32(pb)) {
1526  case 2:
1527  if (den >= INT_MAX / 2)
1528  return 0;
1529  den *= 2;
1530  case 1:
1531  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1532  c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1533  default:
1534  return 0;
1535  }
1536  }
1537  }
1538 
1539  return mov_read_avid(c, pb, atom);
1540 }
1541 
1543 {
1544  int ret = 0;
1545  int length = 0;
1546  uint64_t original_size;
1547  if (c->fc->nb_streams >= 1) {
1548  AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1549  if (par->codec_id == AV_CODEC_ID_H264)
1550  return 0;
1551  if (atom.size == 16) {
1552  original_size = par->extradata_size;
1553  ret = mov_realloc_extradata(par, atom);
1554  if (!ret) {
1555  length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1556  if (length == atom.size) {
1557  const uint8_t range_value = par->extradata[original_size + 19];
1558  switch (range_value) {
1559  case 1:
1561  break;
1562  case 2:
1564  break;
1565  default:
1566  av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1567  break;
1568  }
1569  ff_dlog(c, "color_range: %d\n", par->color_range);
1570  } else {
1571  /* For some reason the whole atom was not added to the extradata */
1572  av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1573  }
1574  } else {
1575  av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1576  }
1577  } else {
1578  av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1579  }
1580  }
1581 
1582  return ret;
1583 }
1584 
1586 {
1587  return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1588 }
1589 
1591 {
1592  AVStream *st;
1593  int ret;
1594 
1595  if (c->fc->nb_streams < 1)
1596  return 0;
1597  st = c->fc->streams[c->fc->nb_streams-1];
1598 
1599  if ((uint64_t)atom.size > (1<<30))
1600  return AVERROR_INVALIDDATA;
1601 
1602  if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1605  // pass all frma atom to codec, needed at least for QDMC and QDM2
1606  av_freep(&st->codecpar->extradata);
1607  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1608  if (ret < 0)
1609  return ret;
1610  } else if (atom.size > 8) { /* to read frma, esds atoms */
1611  if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1612  uint64_t buffer;
1613  ret = ffio_ensure_seekback(pb, 8);
1614  if (ret < 0)
1615  return ret;
1616  buffer = avio_rb64(pb);
1617  atom.size -= 8;
1618  if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1619  && buffer >> 32 <= atom.size
1620  && buffer >> 32 >= 8) {
1621  avio_skip(pb, -8);
1622  atom.size += 8;
1623  } else if (!st->codecpar->extradata_size) {
1624 #define ALAC_EXTRADATA_SIZE 36
1626  if (!st->codecpar->extradata)
1627  return AVERROR(ENOMEM);
1630  AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1631  AV_WB64(st->codecpar->extradata + 12, buffer);
1632  avio_read(pb, st->codecpar->extradata + 20, 16);
1633  avio_skip(pb, atom.size - 24);
1634  return 0;
1635  }
1636  }
1637  if ((ret = mov_read_default(c, pb, atom)) < 0)
1638  return ret;
1639  } else
1640  avio_skip(pb, atom.size);
1641  return 0;
1642 }
1643 
1644 /**
1645  * This function reads atom content and puts data in extradata without tag
1646  * nor size unlike mov_read_extradata.
1647  */
1649 {
1650  AVStream *st;
1651  int ret;
1652 
1653  if (c->fc->nb_streams < 1)
1654  return 0;
1655  st = c->fc->streams[c->fc->nb_streams-1];
1656 
1657  if ((uint64_t)atom.size > (1<<30))
1658  return AVERROR_INVALIDDATA;
1659 
1660  if (atom.size >= 10) {
1661  // Broken files created by legacy versions of libavformat will
1662  // wrap a whole fiel atom inside of a glbl atom.
1663  unsigned size = avio_rb32(pb);
1664  unsigned type = avio_rl32(pb);
1665  avio_seek(pb, -8, SEEK_CUR);
1666  if (type == MKTAG('f','i','e','l') && size == atom.size)
1667  return mov_read_default(c, pb, atom);
1668  }
1669  if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1670  av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1671  return 0;
1672  }
1673  av_freep(&st->codecpar->extradata);
1674  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1675  if (ret < 0)
1676  return ret;
1677 
1678  return 0;
1679 }
1680 
1682 {
1683  AVStream *st;
1684  uint8_t profile_level;
1685  int ret;
1686 
1687  if (c->fc->nb_streams < 1)
1688  return 0;
1689  st = c->fc->streams[c->fc->nb_streams-1];
1690 
1691  if (atom.size >= (1<<28) || atom.size < 7)
1692  return AVERROR_INVALIDDATA;
1693 
1694  profile_level = avio_r8(pb);
1695  if ((profile_level & 0xf0) != 0xc0)
1696  return 0;
1697 
1698  avio_seek(pb, 6, SEEK_CUR);
1699  av_freep(&st->codecpar->extradata);
1700  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1701  if (ret < 0)
1702  return ret;
1703 
1704  return 0;
1705 }
1706 
1707 /**
1708  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1709  * but can have extradata appended at the end after the 40 bytes belonging
1710  * to the struct.
1711  */
1713 {
1714  AVStream *st;
1715  int ret;
1716 
1717  if (c->fc->nb_streams < 1)
1718  return 0;
1719  if (atom.size <= 40)
1720  return 0;
1721  st = c->fc->streams[c->fc->nb_streams-1];
1722 
1723  if ((uint64_t)atom.size > (1<<30))
1724  return AVERROR_INVALIDDATA;
1725 
1726  avio_skip(pb, 40);
1727  av_freep(&st->codecpar->extradata);
1728  ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1729  if (ret < 0)
1730  return ret;
1731 
1732  return 0;
1733 }
1734 
1736 {
1737  AVStream *st;
1738  MOVStreamContext *sc;
1739  unsigned int i, entries;
1740 
1741  if (c->fc->nb_streams < 1)
1742  return 0;
1743  st = c->fc->streams[c->fc->nb_streams-1];
1744  sc = st->priv_data;
1745 
1746  avio_r8(pb); /* version */
1747  avio_rb24(pb); /* flags */
1748 
1749  entries = avio_rb32(pb);
1750 
1751  if (!entries)
1752  return 0;
1753 
1754  if (sc->chunk_offsets)
1755  av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1756  av_free(sc->chunk_offsets);
1757  sc->chunk_count = 0;
1758  sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1759  if (!sc->chunk_offsets)
1760  return AVERROR(ENOMEM);
1761  sc->chunk_count = entries;
1762 
1763  if (atom.type == MKTAG('s','t','c','o'))
1764  for (i = 0; i < entries && !pb->eof_reached; i++)
1765  sc->chunk_offsets[i] = avio_rb32(pb);
1766  else if (atom.type == MKTAG('c','o','6','4'))
1767  for (i = 0; i < entries && !pb->eof_reached; i++)
1768  sc->chunk_offsets[i] = avio_rb64(pb);
1769  else
1770  return AVERROR_INVALIDDATA;
1771 
1772  sc->chunk_count = i;
1773 
1774  if (pb->eof_reached)
1775  return AVERROR_EOF;
1776 
1777  return 0;
1778 }
1779 
1780 /**
1781  * Compute codec id for 'lpcm' tag.
1782  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1783  */
1785 {
1786  /* lpcm flags:
1787  * 0x1 = float
1788  * 0x2 = big-endian
1789  * 0x4 = signed
1790  */
1791  return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1792 }
1793 
1794 static int mov_codec_id(AVStream *st, uint32_t format)
1795 {
1796  int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1797 
1798  if (id <= 0 &&
1799  ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1800  (format & 0xFFFF) == 'T' + ('S' << 8)))
1801  id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1802 
1803  if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1805  } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1806  /* skip old ASF MPEG-4 tag */
1807  format && format != MKTAG('m','p','4','s')) {
1809  if (id <= 0)
1810  id = ff_codec_get_id(ff_codec_bmp_tags, format);
1811  if (id > 0)
1813  else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
1815  st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
1817  if (id > 0)
1819  }
1820  }
1821 
1822  st->codecpar->codec_tag = format;
1823 
1824  return id;
1825 }
1826 
1828  AVStream *st, MOVStreamContext *sc)
1829 {
1830  uint8_t codec_name[32];
1831  int64_t stsd_start;
1832  unsigned int len;
1833 
1834  /* The first 16 bytes of the video sample description are already
1835  * read in ff_mov_read_stsd_entries() */
1836  stsd_start = avio_tell(pb) - 16;
1837 
1838  avio_rb16(pb); /* version */
1839  avio_rb16(pb); /* revision level */
1840  avio_rb32(pb); /* vendor */
1841  avio_rb32(pb); /* temporal quality */
1842  avio_rb32(pb); /* spatial quality */
1843 
1844  st->codecpar->width = avio_rb16(pb); /* width */
1845  st->codecpar->height = avio_rb16(pb); /* height */
1846 
1847  avio_rb32(pb); /* horiz resolution */
1848  avio_rb32(pb); /* vert resolution */
1849  avio_rb32(pb); /* data size, always 0 */
1850  avio_rb16(pb); /* frames per samples */
1851 
1852  len = avio_r8(pb); /* codec name, pascal string */
1853  if (len > 31)
1854  len = 31;
1855  mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1856  if (len < 31)
1857  avio_skip(pb, 31 - len);
1858 
1859  if (codec_name[0])
1860  av_dict_set(&st->metadata, "encoder", codec_name, 0);
1861 
1862  /* codec_tag YV12 triggers an UV swap in rawdec.c */
1863  if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1864  st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1865  st->codecpar->width &= ~1;
1866  st->codecpar->height &= ~1;
1867  }
1868  /* Flash Media Server uses tag H.263 with Sorenson Spark */
1869  if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1870  !memcmp(codec_name, "Sorenson H263", 13))
1872 
1873  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1874 
1875  avio_seek(pb, stsd_start, SEEK_SET);
1876 
1877  if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
1878  st->codecpar->bits_per_coded_sample &= 0x1F;
1879  sc->has_palette = 1;
1880  }
1881 }
1882 
1884  AVStream *st, MOVStreamContext *sc)
1885 {
1886  int bits_per_sample, flags;
1887  uint16_t version = avio_rb16(pb);
1888  AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1889 
1890  avio_rb16(pb); /* revision level */
1891  avio_rb32(pb); /* vendor */
1892 
1893  st->codecpar->channels = avio_rb16(pb); /* channel count */
1894  st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1895  av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1896 
1897  sc->audio_cid = avio_rb16(pb);
1898  avio_rb16(pb); /* packet size = 0 */
1899 
1900  st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1901 
1902  // Read QT version 1 fields. In version 0 these do not exist.
1903  av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1904  if (!c->isom ||
1905  (compatible_brands && strstr(compatible_brands->value, "qt "))) {
1906 
1907  if (version == 1) {
1908  sc->samples_per_frame = avio_rb32(pb);
1909  avio_rb32(pb); /* bytes per packet */
1910  sc->bytes_per_frame = avio_rb32(pb);
1911  avio_rb32(pb); /* bytes per sample */
1912  } else if (version == 2) {
1913  avio_rb32(pb); /* sizeof struct only */
1915  st->codecpar->channels = avio_rb32(pb);
1916  avio_rb32(pb); /* always 0x7F000000 */
1918 
1919  flags = avio_rb32(pb); /* lpcm format specific flag */
1920  sc->bytes_per_frame = avio_rb32(pb);
1921  sc->samples_per_frame = avio_rb32(pb);
1922  if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1923  st->codecpar->codec_id =
1925  flags);
1926  }
1927  if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1928  /* can't correctly handle variable sized packet as audio unit */
1929  switch (st->codecpar->codec_id) {
1930  case AV_CODEC_ID_MP2:
1931  case AV_CODEC_ID_MP3:
1933  break;
1934  }
1935  }
1936  }
1937 
1938  if (sc->format == 0) {
1939  if (st->codecpar->bits_per_coded_sample == 8)
1940  st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1941  else if (st->codecpar->bits_per_coded_sample == 16)
1942  st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1943  }
1944 
1945  switch (st->codecpar->codec_id) {
1946  case AV_CODEC_ID_PCM_S8:
1947  case AV_CODEC_ID_PCM_U8:
1948  if (st->codecpar->bits_per_coded_sample == 16)
1950  break;
1951  case AV_CODEC_ID_PCM_S16LE:
1952  case AV_CODEC_ID_PCM_S16BE:
1953  if (st->codecpar->bits_per_coded_sample == 8)
1955  else if (st->codecpar->bits_per_coded_sample == 24)
1956  st->codecpar->codec_id =
1959  else if (st->codecpar->bits_per_coded_sample == 32)
1960  st->codecpar->codec_id =
1963  break;
1964  /* set values for old format before stsd version 1 appeared */
1965  case AV_CODEC_ID_MACE3:
1966  sc->samples_per_frame = 6;
1967  sc->bytes_per_frame = 2 * st->codecpar->channels;
1968  break;
1969  case AV_CODEC_ID_MACE6:
1970  sc->samples_per_frame = 6;
1971  sc->bytes_per_frame = 1 * st->codecpar->channels;
1972  break;
1974  sc->samples_per_frame = 64;
1975  sc->bytes_per_frame = 34 * st->codecpar->channels;
1976  break;
1977  case AV_CODEC_ID_GSM:
1978  sc->samples_per_frame = 160;
1979  sc->bytes_per_frame = 33;
1980  break;
1981  default:
1982  break;
1983  }
1984 
1985  bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
1986  if (bits_per_sample) {
1987  st->codecpar->bits_per_coded_sample = bits_per_sample;
1988  sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
1989  }
1990 }
1991 
1993  AVStream *st, MOVStreamContext *sc,
1994  int64_t size)
1995 {
1996  // ttxt stsd contains display flags, justification, background
1997  // color, fonts, and default styles, so fake an atom to read it
1998  MOVAtom fake_atom = { .size = size };
1999  // mp4s contains a regular esds atom
2000  if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2001  mov_read_glbl(c, pb, fake_atom);
2002  st->codecpar->width = sc->width;
2003  st->codecpar->height = sc->height;
2004 }
2005 
2006 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2007 {
2008  uint8_t r, g, b;
2009  int y, cb, cr;
2010 
2011  y = (ycbcr >> 16) & 0xFF;
2012  cr = (ycbcr >> 8) & 0xFF;
2013  cb = ycbcr & 0xFF;
2014 
2015  b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
2016  g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
2017  r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
2018 
2019  return (r << 16) | (g << 8) | b;
2020 }
2021 
2023 {
2024  char buf[256] = {0};
2025  uint8_t *src = st->codecpar->extradata;
2026  int i;
2027 
2028  if (st->codecpar->extradata_size != 64)
2029  return 0;
2030 
2031  if (st->codecpar->width > 0 && st->codecpar->height > 0)
2032  snprintf(buf, sizeof(buf), "size: %dx%d\n",
2033  st->codecpar->width, st->codecpar->height);
2034  av_strlcat(buf, "palette: ", sizeof(buf));
2035 
2036  for (i = 0; i < 16; i++) {
2037  uint32_t yuv = AV_RB32(src + i * 4);
2038  uint32_t rgba = yuv_to_rgba(yuv);
2039 
2040  av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2041  }
2042 
2043  if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2044  return 0;
2045 
2046  av_freep(&st->codecpar->extradata);
2047  st->codecpar->extradata_size = 0;
2049  if (!st->codecpar->extradata)
2050  return AVERROR(ENOMEM);
2051  st->codecpar->extradata_size = strlen(buf);
2052  memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2053 
2054  return 0;
2055 }
2056 
2058  AVStream *st, MOVStreamContext *sc,
2059  int64_t size)
2060 {
2061  int ret;
2062 
2063  if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2064  if ((int)size != size)
2065  return AVERROR(ENOMEM);
2066 
2067  ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2068  if (ret < 0)
2069  return ret;
2070  if (size > 16) {
2071  MOVStreamContext *tmcd_ctx = st->priv_data;
2072  int val;
2073  val = AV_RB32(st->codecpar->extradata + 4);
2074  tmcd_ctx->tmcd_flags = val;
2075  st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2076  st->avg_frame_rate.den = 1;
2077 #if FF_API_LAVF_AVCTX
2079  st->codec->time_base = av_inv_q(st->avg_frame_rate);
2081 #endif
2082  /* adjust for per frame dur in counter mode */
2083  if (tmcd_ctx->tmcd_flags & 0x0008) {
2084  int timescale = AV_RB32(st->codecpar->extradata + 8);
2085  int framedur = AV_RB32(st->codecpar->extradata + 12);
2086  st->avg_frame_rate.num *= timescale;
2087  st->avg_frame_rate.den *= framedur;
2088 #if FF_API_LAVF_AVCTX
2090  st->codec->time_base.den *= timescale;
2091  st->codec->time_base.num *= framedur;
2093 #endif
2094  }
2095  if (size > 30) {
2096  uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2097  uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2098  if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2099  uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2100  if (str_size > 0 && size >= (int)str_size + 26) {
2101  char *reel_name = av_malloc(str_size + 1);
2102  if (!reel_name)
2103  return AVERROR(ENOMEM);
2104  memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2105  reel_name[str_size] = 0; /* Add null terminator */
2106  /* don't add reel_name if emtpy string */
2107  if (*reel_name == 0) {
2108  av_free(reel_name);
2109  } else {
2110  av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
2111  }
2112  }
2113  }
2114  }
2115  }
2116  } else {
2117  /* other codec type, just skip (rtp, mp4s ...) */
2118  avio_skip(pb, size);
2119  }
2120  return 0;
2121 }
2122 
2124  AVStream *st, MOVStreamContext *sc)
2125 {
2126  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2127  !st->codecpar->sample_rate && sc->time_scale > 1)
2128  st->codecpar->sample_rate = sc->time_scale;
2129 
2130  /* special codec parameters handling */
2131  switch (st->codecpar->codec_id) {
2132 #if CONFIG_DV_DEMUXER
2133  case AV_CODEC_ID_DVAUDIO:
2135  if (!c->dv_fctx) {
2136  av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2137  return AVERROR(ENOMEM);
2138  }
2140  if (!c->dv_demux) {
2141  av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2142  return AVERROR(ENOMEM);
2143  }
2144  sc->dv_audio_container = 1;
2146  break;
2147 #endif
2148  /* no ifdef since parameters are always those */
2149  case AV_CODEC_ID_QCELP:
2150  st->codecpar->channels = 1;
2151  // force sample rate for qcelp when not stored in mov
2152  if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2153  st->codecpar->sample_rate = 8000;
2154  // FIXME: Why is the following needed for some files?
2155  sc->samples_per_frame = 160;
2156  if (!sc->bytes_per_frame)
2157  sc->bytes_per_frame = 35;
2158  break;
2159  case AV_CODEC_ID_AMR_NB:
2160  st->codecpar->channels = 1;
2161  /* force sample rate for amr, stsd in 3gp does not store sample rate */
2162  st->codecpar->sample_rate = 8000;
2163  break;
2164  case AV_CODEC_ID_AMR_WB:
2165  st->codecpar->channels = 1;
2166  st->codecpar->sample_rate = 16000;
2167  break;
2168  case AV_CODEC_ID_MP2:
2169  case AV_CODEC_ID_MP3:
2170  /* force type after stsd for m1a hdlr */
2172  break;
2173  case AV_CODEC_ID_GSM:
2174  case AV_CODEC_ID_ADPCM_MS:
2176  case AV_CODEC_ID_ILBC:
2177  case AV_CODEC_ID_MACE3:
2178  case AV_CODEC_ID_MACE6:
2179  case AV_CODEC_ID_QDM2:
2181  break;
2182  case AV_CODEC_ID_ALAC:
2183  if (st->codecpar->extradata_size == 36) {
2184  st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
2185  st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2186  }
2187  break;
2188  case AV_CODEC_ID_AC3:
2189  case AV_CODEC_ID_EAC3:
2191  case AV_CODEC_ID_VC1:
2193  break;
2194  default:
2195  break;
2196  }
2197  return 0;
2198 }
2199 
2201  int codec_tag, int format,
2202  int64_t size)
2203 {
2204  int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2205 
2206  if (codec_tag &&
2207  (codec_tag != format &&
2208  (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2209  : codec_tag != MKTAG('j','p','e','g')))) {
2210  /* Multiple fourcc, we skip JPEG. This is not correct, we should
2211  * export it as a separate AVStream but this needs a few changes
2212  * in the MOV demuxer, patch welcome. */
2213 
2214  av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2215  avio_skip(pb, size);
2216  return 1;
2217  }
2218  if ( codec_tag == AV_RL32("avc1") ||
2219  codec_tag == AV_RL32("hvc1") ||
2220  codec_tag == AV_RL32("hev1")
2221  )
2222  av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2223 
2224  return 0;
2225 }
2226 
2228 {
2229  AVStream *st;
2230  MOVStreamContext *sc;
2231  int pseudo_stream_id;
2232 
2233  if (c->fc->nb_streams < 1)
2234  return 0;
2235  st = c->fc->streams[c->fc->nb_streams-1];
2236  sc = st->priv_data;
2237 
2238  for (pseudo_stream_id = 0;
2239  pseudo_stream_id < entries && !pb->eof_reached;
2240  pseudo_stream_id++) {
2241  //Parsing Sample description table
2242  enum AVCodecID id;
2243  int ret, dref_id = 1;
2244  MOVAtom a = { AV_RL32("stsd") };
2245  int64_t start_pos = avio_tell(pb);
2246  int64_t size = avio_rb32(pb); /* size */
2247  uint32_t format = avio_rl32(pb); /* data format */
2248 
2249  if (size >= 16) {
2250  avio_rb32(pb); /* reserved */
2251  avio_rb16(pb); /* reserved */
2252  dref_id = avio_rb16(pb);
2253  } else if (size <= 7) {
2254  av_log(c->fc, AV_LOG_ERROR,
2255  "invalid size %"PRId64" in stsd\n", size);
2256  return AVERROR_INVALIDDATA;
2257  }
2258 
2259  if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2260  size - (avio_tell(pb) - start_pos)))
2261  continue;
2262 
2263  sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2264  sc->dref_id= dref_id;
2265  sc->format = format;
2266 
2267  id = mov_codec_id(st, format);
2268 
2269  av_log(c->fc, AV_LOG_TRACE,
2270  "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2271  (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2272  (format >> 24) & 0xff, format, st->codecpar->codec_type);
2273 
2275  st->codecpar->codec_id = id;
2276  mov_parse_stsd_video(c, pb, st, sc);
2277  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2278  st->codecpar->codec_id = id;
2279  mov_parse_stsd_audio(c, pb, st, sc);
2280  } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2281  st->codecpar->codec_id = id;
2282  mov_parse_stsd_subtitle(c, pb, st, sc,
2283  size - (avio_tell(pb) - start_pos));
2284  } else {
2285  ret = mov_parse_stsd_data(c, pb, st, sc,
2286  size - (avio_tell(pb) - start_pos));
2287  if (ret < 0)
2288  return ret;
2289  }
2290  /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2291  a.size = size - (avio_tell(pb) - start_pos);
2292  if (a.size > 8) {
2293  if ((ret = mov_read_default(c, pb, a)) < 0)
2294  return ret;
2295  } else if (a.size > 0)
2296  avio_skip(pb, a.size);
2297  }
2298 
2299  if (pb->eof_reached)
2300  return AVERROR_EOF;
2301 
2302  return mov_finalize_stsd_codec(c, pb, st, sc);
2303 }
2304 
2306 {
2307  int entries;
2308 
2309  avio_r8(pb); /* version */
2310  avio_rb24(pb); /* flags */
2311  entries = avio_rb32(pb);
2312 
2313  return ff_mov_read_stsd_entries(c, pb, entries);
2314 }
2315 
2317 {
2318  AVStream *st;
2319  MOVStreamContext *sc;
2320  unsigned int i, entries;
2321 
2322  if (c->fc->nb_streams < 1)
2323  return 0;
2324  st = c->fc->streams[c->fc->nb_streams-1];
2325  sc = st->priv_data;
2326 
2327  avio_r8(pb); /* version */
2328  avio_rb24(pb); /* flags */
2329 
2330  entries = avio_rb32(pb);
2331 
2332  av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2333 
2334  if (!entries)
2335  return 0;
2336  if (sc->stsc_data)
2337  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2338  av_free(sc->stsc_data);
2339  sc->stsc_count = 0;
2340  sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2341  if (!sc->stsc_data)
2342  return AVERROR(ENOMEM);
2343 
2344  for (i = 0; i < entries && !pb->eof_reached; i++) {
2345  sc->stsc_data[i].first = avio_rb32(pb);
2346  sc->stsc_data[i].count = avio_rb32(pb);
2347  sc->stsc_data[i].id = avio_rb32(pb);
2348  }
2349 
2350  sc->stsc_count = i;
2351 
2352  if (pb->eof_reached)
2353  return AVERROR_EOF;
2354 
2355  return 0;
2356 }
2357 
2359 {
2360  AVStream *st;
2361  MOVStreamContext *sc;
2362  unsigned i, entries;
2363 
2364  if (c->fc->nb_streams < 1)
2365  return 0;
2366  st = c->fc->streams[c->fc->nb_streams-1];
2367  sc = st->priv_data;
2368 
2369  avio_rb32(pb); // version + flags
2370 
2371  entries = avio_rb32(pb);
2372  if (sc->stps_data)
2373  av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2374  av_free(sc->stps_data);
2375  sc->stps_count = 0;
2376  sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2377  if (!sc->stps_data)
2378  return AVERROR(ENOMEM);
2379 
2380  for (i = 0; i < entries && !pb->eof_reached; i++) {
2381  sc->stps_data[i] = avio_rb32(pb);
2382  //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2383  }
2384 
2385  sc->stps_count = i;
2386 
2387  if (pb->eof_reached)
2388  return AVERROR_EOF;
2389 
2390  return 0;
2391 }
2392 
2394 {
2395  AVStream *st;
2396  MOVStreamContext *sc;
2397  unsigned int i, entries;
2398 
2399  if (c->fc->nb_streams < 1)
2400  return 0;
2401  st = c->fc->streams[c->fc->nb_streams-1];
2402  sc = st->priv_data;
2403 
2404  avio_r8(pb); /* version */
2405  avio_rb24(pb); /* flags */
2406 
2407  entries = avio_rb32(pb);
2408 
2409  av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2410 
2411  if (!entries)
2412  {
2413  sc->keyframe_absent = 1;
2414  if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2416  return 0;
2417  }
2418  if (sc->keyframes)
2419  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2420  if (entries >= UINT_MAX / sizeof(int))
2421  return AVERROR_INVALIDDATA;
2422  av_freep(&sc->keyframes);
2423  sc->keyframe_count = 0;
2424  sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2425  if (!sc->keyframes)
2426  return AVERROR(ENOMEM);
2427 
2428  for (i = 0; i < entries && !pb->eof_reached; i++) {
2429  sc->keyframes[i] = avio_rb32(pb);
2430  //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2431  }
2432 
2433  sc->keyframe_count = i;
2434 
2435  if (pb->eof_reached)
2436  return AVERROR_EOF;
2437 
2438  return 0;
2439 }
2440 
2442 {
2443  AVStream *st;
2444  MOVStreamContext *sc;
2445  unsigned int i, entries, sample_size, field_size, num_bytes;
2446  GetBitContext gb;
2447  unsigned char* buf;
2448  int ret;
2449 
2450  if (c->fc->nb_streams < 1)
2451  return 0;
2452  st = c->fc->streams[c->fc->nb_streams-1];
2453  sc = st->priv_data;
2454 
2455  avio_r8(pb); /* version */
2456  avio_rb24(pb); /* flags */
2457 
2458  if (atom.type == MKTAG('s','t','s','z')) {
2459  sample_size = avio_rb32(pb);
2460  if (!sc->sample_size) /* do not overwrite value computed in stsd */
2461  sc->sample_size = sample_size;
2462  sc->stsz_sample_size = sample_size;
2463  field_size = 32;
2464  } else {
2465  sample_size = 0;
2466  avio_rb24(pb); /* reserved */
2467  field_size = avio_r8(pb);
2468  }
2469  entries = avio_rb32(pb);
2470 
2471  av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2472 
2473  sc->sample_count = entries;
2474  if (sample_size)
2475  return 0;
2476 
2477  if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2478  av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2479  return AVERROR_INVALIDDATA;
2480  }
2481 
2482  if (!entries)
2483  return 0;
2484  if (entries >= (UINT_MAX - 4) / field_size)
2485  return AVERROR_INVALIDDATA;
2486  if (sc->sample_sizes)
2487  av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2488  av_free(sc->sample_sizes);
2489  sc->sample_count = 0;
2490  sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2491  if (!sc->sample_sizes)
2492  return AVERROR(ENOMEM);
2493 
2494  num_bytes = (entries*field_size+4)>>3;
2495 
2496  buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2497  if (!buf) {
2498  av_freep(&sc->sample_sizes);
2499  return AVERROR(ENOMEM);
2500  }
2501 
2502  ret = ffio_read_size(pb, buf, num_bytes);
2503  if (ret < 0) {
2504  av_freep(&sc->sample_sizes);
2505  av_free(buf);
2506  return ret;
2507  }
2508 
2509  init_get_bits(&gb, buf, 8*num_bytes);
2510 
2511  for (i = 0; i < entries && !pb->eof_reached; i++) {
2512  sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2513  sc->data_size += sc->sample_sizes[i];
2514  }
2515 
2516  sc->sample_count = i;
2517 
2518  av_free(buf);
2519 
2520  if (pb->eof_reached)
2521  return AVERROR_EOF;
2522 
2523  return 0;
2524 }
2525 
2527 {
2528  AVStream *st;
2529  MOVStreamContext *sc;
2530  unsigned int i, entries;
2531  int64_t duration=0;
2532  int64_t total_sample_count=0;
2533 
2534  if (c->fc->nb_streams < 1)
2535  return 0;
2536  st = c->fc->streams[c->fc->nb_streams-1];
2537  sc = st->priv_data;
2538 
2539  avio_r8(pb); /* version */
2540  avio_rb24(pb); /* flags */
2541  entries = avio_rb32(pb);
2542 
2543  av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2544  c->fc->nb_streams-1, entries);
2545 
2546  if (sc->stts_data)
2547  av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2548  av_free(sc->stts_data);
2549  sc->stts_count = 0;
2550  sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2551  if (!sc->stts_data)
2552  return AVERROR(ENOMEM);
2553 
2554  for (i = 0; i < entries && !pb->eof_reached; i++) {
2555  int sample_duration;
2556  int sample_count;
2557 
2558  sample_count=avio_rb32(pb);
2559  sample_duration = avio_rb32(pb);
2560 
2561  if (sample_count < 0) {
2562  av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2563  return AVERROR_INVALIDDATA;
2564  }
2565  sc->stts_data[i].count= sample_count;
2566  sc->stts_data[i].duration= sample_duration;
2567 
2568  av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2569  sample_count, sample_duration);
2570 
2571  if ( i+1 == entries
2572  && i
2573  && sample_count == 1
2574  && total_sample_count > 100
2575  && sample_duration/10 > duration / total_sample_count)
2576  sample_duration = duration / total_sample_count;
2577  duration+=(int64_t)sample_duration*sample_count;
2578  total_sample_count+=sample_count;
2579  }
2580 
2581  sc->stts_count = i;
2582 
2583  sc->duration_for_fps += duration;
2584  sc->nb_frames_for_fps += total_sample_count;
2585 
2586  if (pb->eof_reached)
2587  return AVERROR_EOF;
2588 
2589  st->nb_frames= total_sample_count;
2590  if (duration)
2591  st->duration= duration;
2592  sc->track_end = duration;
2593  return 0;
2594 }
2595 
2597 {
2598  if (duration < 0) {
2599  if (duration == INT_MIN) {
2600  av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2601  duration++;
2602  }
2603  sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2604  }
2605 }
2606 
2608 {
2609  AVStream *st;
2610  MOVStreamContext *sc;
2611  unsigned int i, entries, ctts_count = 0;
2612 
2613  if (c->fc->nb_streams < 1)
2614  return 0;
2615  st = c->fc->streams[c->fc->nb_streams-1];
2616  sc = st->priv_data;
2617 
2618  avio_r8(pb); /* version */
2619  avio_rb24(pb); /* flags */
2620  entries = avio_rb32(pb);
2621 
2622  av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2623 
2624  if (!entries)
2625  return 0;
2626  if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2627  return AVERROR_INVALIDDATA;
2628  av_freep(&sc->ctts_data);
2629  sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2630  if (!sc->ctts_data)
2631  return AVERROR(ENOMEM);
2632 
2633  for (i = 0; i < entries && !pb->eof_reached; i++) {
2634  int count =avio_rb32(pb);
2635  int duration =avio_rb32(pb);
2636 
2637  if (count <= 0) {
2638  av_log(c->fc, AV_LOG_TRACE,
2639  "ignoring CTTS entry with count=%d duration=%d\n",
2640  count, duration);
2641  continue;
2642  }
2643 
2644  sc->ctts_data[ctts_count].count = count;
2645  sc->ctts_data[ctts_count].duration = duration;
2646  ctts_count++;
2647 
2648  av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2649  count, duration);
2650 
2651  if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2652  av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2653  av_freep(&sc->ctts_data);
2654  sc->ctts_count = 0;
2655  return 0;
2656  }
2657 
2658  if (i+2<entries)
2659  mov_update_dts_shift(sc, duration);
2660  }
2661 
2662  sc->ctts_count = ctts_count;
2663 
2664  if (pb->eof_reached)
2665  return AVERROR_EOF;
2666 
2667  av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2668 
2669  return 0;
2670 }
2671 
2673 {
2674  AVStream *st;
2675  MOVStreamContext *sc;
2676  unsigned int i, entries;
2677  uint8_t version;
2678  uint32_t grouping_type;
2679 
2680  if (c->fc->nb_streams < 1)
2681  return 0;
2682  st = c->fc->streams[c->fc->nb_streams-1];
2683  sc = st->priv_data;
2684 
2685  version = avio_r8(pb); /* version */
2686  avio_rb24(pb); /* flags */
2687  grouping_type = avio_rl32(pb);
2688  if (grouping_type != MKTAG( 'r','a','p',' '))
2689  return 0; /* only support 'rap ' grouping */
2690  if (version == 1)
2691  avio_rb32(pb); /* grouping_type_parameter */
2692 
2693  entries = avio_rb32(pb);
2694  if (!entries)
2695  return 0;
2696  if (sc->rap_group)
2697  av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2698  av_free(sc->rap_group);
2699  sc->rap_group_count = 0;
2700  sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2701  if (!sc->rap_group)
2702  return AVERROR(ENOMEM);
2703 
2704  for (i = 0; i < entries && !pb->eof_reached; i++) {
2705  sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2706  sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2707  }
2708 
2709  sc->rap_group_count = i;
2710 
2711  return pb->eof_reached ? AVERROR_EOF : 0;
2712 }
2713 
2714 static void mov_build_index(MOVContext *mov, AVStream *st)
2715 {
2716  MOVStreamContext *sc = st->priv_data;
2717  int64_t current_offset;
2718  int64_t current_dts = 0;
2719  unsigned int stts_index = 0;
2720  unsigned int stsc_index = 0;
2721  unsigned int stss_index = 0;
2722  unsigned int stps_index = 0;
2723  unsigned int i, j;
2724  uint64_t stream_size = 0;
2725 
2726  if (sc->elst_count) {
2727  int i, edit_start_index = 0, unsupported = 0;
2728  int64_t empty_duration = 0; // empty duration of the first edit list entry
2729  int64_t start_time = 0; // start time of the media
2730 
2731  for (i = 0; i < sc->elst_count; i++) {
2732  const MOVElst *e = &sc->elst_data[i];
2733  if (i == 0 && e->time == -1) {
2734  /* if empty, the first entry is the start time of the stream
2735  * relative to the presentation itself */
2736  empty_duration = e->duration;
2737  edit_start_index = 1;
2738  } else if (i == edit_start_index && e->time >= 0) {
2739  start_time = e->time;
2740  } else
2741  unsupported = 1;
2742  }
2743  if (unsupported)
2744  av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2745  "a/v desync might occur, patch welcome\n");
2746 
2747  /* adjust first dts according to edit list */
2748  if ((empty_duration || start_time) && mov->time_scale > 0) {
2749  if (empty_duration)
2750  empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2751  sc->time_offset = start_time - empty_duration;
2752  current_dts = -sc->time_offset;
2753  if (sc->ctts_count>0 && sc->stts_count>0 &&
2754  sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2755  /* more than 16 frames delay, dts are likely wrong
2756  this happens with files created by iMovie */
2757  sc->wrong_dts = 1;
2758  st->codecpar->video_delay = 1;
2759  }
2760  }
2761 
2762  if (!unsupported && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
2763  sc->start_pad = start_time;
2764  }
2765 
2766  /* only use old uncompressed audio chunk demuxing when stts specifies it */
2767  if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2768  sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2769  unsigned int current_sample = 0;
2770  unsigned int stts_sample = 0;
2771  unsigned int sample_size;
2772  unsigned int distance = 0;
2773  unsigned int rap_group_index = 0;
2774  unsigned int rap_group_sample = 0;
2775  int64_t last_dts = 0;
2776  int64_t dts_correction = 0;
2777  int rap_group_present = sc->rap_group_count && sc->rap_group;
2778  int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2779 
2780  current_dts -= sc->dts_shift;
2781  last_dts = current_dts;
2782 
2783  if (!sc->sample_count || st->nb_index_entries)
2784  return;
2785  if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2786  return;
2788  st->nb_index_entries + sc->sample_count,
2789  sizeof(*st->index_entries)) < 0) {
2790  st->nb_index_entries = 0;
2791  return;
2792  }
2794 
2795  for (i = 0; i < sc->chunk_count; i++) {
2796  int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2797  current_offset = sc->chunk_offsets[i];
2798  while (stsc_index + 1 < sc->stsc_count &&
2799  i + 1 == sc->stsc_data[stsc_index + 1].first)
2800  stsc_index++;
2801 
2802  if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2803  sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2804  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2805  sc->stsz_sample_size = sc->sample_size;
2806  }
2807  if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2808  av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2809  sc->stsz_sample_size = sc->sample_size;
2810  }
2811 
2812  for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2813  int keyframe = 0;
2814  if (current_sample >= sc->sample_count) {
2815  av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2816  return;
2817  }
2818 
2819  if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2820  keyframe = 1;
2821  if (stss_index + 1 < sc->keyframe_count)
2822  stss_index++;
2823  } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2824  keyframe = 1;
2825  if (stps_index + 1 < sc->stps_count)
2826  stps_index++;
2827  }
2828  if (rap_group_present && rap_group_index < sc->rap_group_count) {
2829  if (sc->rap_group[rap_group_index].index > 0)
2830  keyframe = 1;
2831  if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2832  rap_group_sample = 0;
2833  rap_group_index++;
2834  }
2835  }
2836  if (sc->keyframe_absent
2837  && !sc->stps_count
2838  && !rap_group_present
2839  && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2840  keyframe = 1;
2841  if (keyframe)
2842  distance = 0;
2843  sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2844  if (sc->pseudo_stream_id == -1 ||
2845  sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2846  AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2847  e->pos = current_offset;
2848  e->timestamp = current_dts;
2849  e->size = sample_size;
2850  e->min_distance = distance;
2851  e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2852  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2853  "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2854  current_offset, current_dts, sample_size, distance, keyframe);
2855  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2856  ff_rfps_add_frame(mov->fc, st, current_dts);
2857  }
2858 
2859  current_offset += sample_size;
2860  stream_size += sample_size;
2861 
2862  /* A negative sample duration is invalid based on the spec,
2863  * but some samples need it to correct the DTS. */
2864  if (sc->stts_data[stts_index].duration < 0) {
2865  av_log(mov->fc, AV_LOG_WARNING,
2866  "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2867  sc->stts_data[stts_index].duration, stts_index,
2868  st->index);
2869  dts_correction += sc->stts_data[stts_index].duration - 1;
2870  sc->stts_data[stts_index].duration = 1;
2871  }
2872  current_dts += sc->stts_data[stts_index].duration;
2873  if (!dts_correction || current_dts + dts_correction > last_dts) {
2874  current_dts += dts_correction;
2875  dts_correction = 0;
2876  } else {
2877  /* Avoid creating non-monotonous DTS */
2878  dts_correction += current_dts - last_dts - 1;
2879  current_dts = last_dts + 1;
2880  }
2881  last_dts = current_dts;
2882  distance++;
2883  stts_sample++;
2884  current_sample++;
2885  if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2886  stts_sample = 0;
2887  stts_index++;
2888  }
2889  }
2890  }
2891  if (st->duration > 0)
2892  st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2893  } else {
2894  unsigned chunk_samples, total = 0;
2895 
2896  // compute total chunk count
2897  for (i = 0; i < sc->stsc_count; i++) {
2898  unsigned count, chunk_count;
2899 
2900  chunk_samples = sc->stsc_data[i].count;
2901  if (i != sc->stsc_count - 1 &&
2902  sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2903  av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2904  return;
2905  }
2906 
2907  if (sc->samples_per_frame >= 160) { // gsm
2908  count = chunk_samples / sc->samples_per_frame;
2909  } else if (sc->samples_per_frame > 1) {
2910  unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2911  count = (chunk_samples+samples-1) / samples;
2912  } else {
2913  count = (chunk_samples+1023) / 1024;
2914  }
2915 
2916  if (i < sc->stsc_count - 1)
2917  chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2918  else
2919  chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2920  total += chunk_count * count;
2921  }
2922 
2923  av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2924  if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2925  return;
2927  st->nb_index_entries + total,
2928  sizeof(*st->index_entries)) < 0) {
2929  st->nb_index_entries = 0;
2930  return;
2931  }
2932  st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2933 
2934  // populate index
2935  for (i = 0; i < sc->chunk_count; i++) {
2936  current_offset = sc->chunk_offsets[i];
2937  if (stsc_index + 1 < sc->stsc_count &&
2938  i + 1 == sc->stsc_data[stsc_index + 1].first)
2939  stsc_index++;
2940  chunk_samples = sc->stsc_data[stsc_index].count;
2941 
2942  while (chunk_samples > 0) {
2943  AVIndexEntry *e;
2944  unsigned size, samples;
2945 
2946  if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2948  "Zero bytes per frame, but %d samples per frame",
2949  sc->samples_per_frame);
2950  return;
2951  }
2952 
2953  if (sc->samples_per_frame >= 160) { // gsm
2954  samples = sc->samples_per_frame;
2955  size = sc->bytes_per_frame;
2956  } else {
2957  if (sc->samples_per_frame > 1) {
2958  samples = FFMIN((1024 / sc->samples_per_frame)*
2959  sc->samples_per_frame, chunk_samples);
2960  size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2961  } else {
2962  samples = FFMIN(1024, chunk_samples);
2963  size = samples * sc->sample_size;
2964  }
2965  }
2966 
2967  if (st->nb_index_entries >= total) {
2968  av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2969  return;
2970  }
2971  e = &st->index_entries[st->nb_index_entries++];
2972  e->pos = current_offset;
2973  e->timestamp = current_dts;
2974  e->size = size;
2975  e->min_distance = 0;
2976  e->flags = AVINDEX_KEYFRAME;
2977  av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2978  "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2979  size, samples);
2980 
2981  current_offset += size;
2982  current_dts += samples;
2983  chunk_samples -= samples;
2984  }
2985  }
2986  }
2987 }
2988 
2989 static int test_same_origin(const char *src, const char *ref) {
2990  char src_proto[64];
2991  char ref_proto[64];
2992  char src_auth[256];
2993  char ref_auth[256];
2994  char src_host[256];
2995  char ref_host[256];
2996  int src_port=-1;
2997  int ref_port=-1;
2998 
2999  av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3000  av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3001 
3002  if (strlen(src) == 0) {
3003  return -1;
3004  } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3005  strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3006  strlen(src_host) + 1 >= sizeof(src_host) ||
3007  strlen(ref_host) + 1 >= sizeof(ref_host)) {
3008  return 0;
3009  } else if (strcmp(src_proto, ref_proto) ||
3010  strcmp(src_auth, ref_auth) ||
3011  strcmp(src_host, ref_host) ||
3012  src_port != ref_port) {
3013  return 0;
3014  } else
3015  return 1;
3016 }
3017 
3018 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3019 {
3020  /* try relative path, we do not try the absolute because it can leak information about our
3021  system to an attacker */
3022  if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3023  char filename[1025];
3024  const char *src_path;
3025  int i, l;
3026 
3027  /* find a source dir */
3028  src_path = strrchr(src, '/');
3029  if (src_path)
3030  src_path++;
3031  else
3032  src_path = src;
3033 
3034  /* find a next level down to target */
3035  for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3036  if (ref->path[l] == '/') {
3037  if (i == ref->nlvl_to - 1)
3038  break;
3039  else
3040  i++;
3041  }
3042 
3043  /* compose filename if next level down to target was found */
3044  if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
3045  memcpy(filename, src, src_path - src);
3046  filename[src_path - src] = 0;
3047 
3048  for (i = 1; i < ref->nlvl_from; i++)
3049  av_strlcat(filename, "../", sizeof(filename));
3050 
3051  av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3052  if (!c->use_absolute_path) {
3053  int same_origin = test_same_origin(src, filename);
3054 
3055  if (!same_origin) {
3056  av_log(c->fc, AV_LOG_ERROR,
3057  "Reference with mismatching origin, %s not tried for security reasons, "
3058  "set demuxer option use_absolute_path to allow it anyway\n",
3059  ref->path);
3060  return AVERROR(ENOENT);
3061  }
3062 
3063  if(strstr(ref->path + l + 1, "..") ||
3064  strstr(ref->path + l + 1, ":") ||
3065  (ref->nlvl_from > 1 && same_origin < 0) ||
3066  (filename[0] == '/' && src_path == src))
3067  return AVERROR(ENOENT);
3068  }
3069 
3070  if (strlen(filename) + 1 == sizeof(filename))
3071  return AVERROR(ENOENT);
3072  if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3073  return 0;
3074  }
3075  } else if (c->use_absolute_path) {
3076  av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3077  "this is a possible security issue\n");
3078  if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3079  return 0;
3080  } else {
3081  av_log(c->fc, AV_LOG_ERROR,
3082  "Absolute path %s not tried for security reasons, "
3083  "set demuxer option use_absolute_path to allow absolute paths\n",
3084  ref->path);
3085  }
3086 
3087  return AVERROR(ENOENT);
3088 }
3089 
3091 {
3092  if (sc->time_scale <= 0) {
3093  av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3094  sc->time_scale = c->time_scale;
3095  if (sc->time_scale <= 0)
3096  sc->time_scale = 1;
3097  }
3098 }
3099 
3101 {
3102  AVStream *st;
3103  MOVStreamContext *sc;
3104  int ret;
3105 
3106  st = avformat_new_stream(c->fc, NULL);
3107  if (!st) return AVERROR(ENOMEM);
3108  st->id = c->fc->nb_streams;
3109  sc = av_mallocz(sizeof(MOVStreamContext));
3110  if (!sc) return AVERROR(ENOMEM);
3111 
3112  st->priv_data = sc;
3114  sc->ffindex = st->index;
3115  c->trak_index = st->index;
3116 
3117  if ((ret = mov_read_default(c, pb, atom)) < 0)
3118  return ret;
3119 
3120  c->trak_index = -1;
3121 
3122  /* sanity checks */
3123  if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3124  (!sc->sample_size && !sc->sample_count))) {
3125  av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3126  st->index);
3127  return 0;
3128  }
3129 
3130  fix_timescale(c, sc);
3131 
3132  avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3133 
3134  mov_build_index(c, st);
3135 
3136  if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3137  MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3138  if (c->enable_drefs) {
3139  if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3140  av_log(c->fc, AV_LOG_ERROR,
3141  "stream %d, error opening alias: path='%s', dir='%s', "
3142  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3143  st->index, dref->path, dref->dir, dref->filename,
3144  dref->volume, dref->nlvl_from, dref->nlvl_to);
3145  } else {
3146  av_log(c->fc, AV_LOG_WARNING,
3147  "Skipped opening external track: "
3148  "stream %d, alias: path='%s', dir='%s', "
3149  "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3150  "Set enable_drefs to allow this.\n",
3151  st->index, dref->path, dref->dir, dref->filename,
3152  dref->volume, dref->nlvl_from, dref->nlvl_to);
3153  }
3154  } else {
3155  sc->pb = c->fc->pb;
3156  sc->pb_is_copied = 1;
3157  }
3158 
3159  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3160  if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
3161  sc->height && sc->width &&
3162  (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
3163  st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
3164  ((double)st->codecpar->width * sc->height), INT_MAX);
3165  }
3166 
3167 #if FF_API_R_FRAME_RATE
3168  if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3170  sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3171 #endif
3172  }
3173 
3174  // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3175  if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3176  TAG_IS_AVCI(st->codecpar->codec_tag)) {
3177  ret = ff_generate_avci_extradata(st);
3178  if (ret < 0)
3179  return ret;
3180  }
3181 
3182  switch (st->codecpar->codec_id) {
3183 #if CONFIG_H261_DECODER
3184  case AV_CODEC_ID_H261:
3185 #endif
3186 #if CONFIG_H263_DECODER
3187  case AV_CODEC_ID_H263:
3188 #endif
3189 #if CONFIG_MPEG4_DECODER
3190  case AV_CODEC_ID_MPEG4:
3191 #endif
3192  st->codecpar->width = 0; /* let decoder init width/height */
3193  st->codecpar->height= 0;
3194  break;
3195  }
3196 
3197  // If the duration of the mp3 packets is not constant, then they could need a parser
3198  if (st->codecpar->codec_id == AV_CODEC_ID_MP3
3199  && sc->stts_count > 3
3200  && sc->stts_count*10 > st->nb_frames
3201  && sc->time_scale == st->codecpar->sample_rate) {
3203  }
3204  /* Do not need those anymore. */
3205  av_freep(&sc->chunk_offsets);
3206  av_freep(&sc->stsc_data);
3207  av_freep(&sc->sample_sizes);
3208  av_freep(&sc->keyframes);
3209  av_freep(&sc->stts_data);
3210  av_freep(&sc->stps_data);
3211  av_freep(&sc->elst_data);
3212  av_freep(&sc->rap_group);
3213 
3214  return 0;
3215 }
3216 
3218 {
3219  int ret;
3220  c->itunes_metadata = 1;
3221  ret = mov_read_default(c, pb, atom);
3222  c->itunes_metadata = 0;
3223  return ret;
3224 }
3225 
3227 {
3228  uint32_t count;
3229  uint32_t i;
3230 
3231  if (atom.size < 8)
3232  return 0;
3233 
3234  avio_skip(pb, 4);
3235  count = avio_rb32(pb);
3236  if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3237  av_log(c->fc, AV_LOG_ERROR,
3238  "The 'keys' atom with the invalid key count: %d\n", count);
3239  return AVERROR_INVALIDDATA;
3240  }
3241 
3242  c->meta_keys_count = count + 1;
3243  c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3244  if (!c->meta_keys)
3245  return AVERROR(ENOMEM);
3246 
3247  for (i = 1; i <= count; ++i) {
3248  uint32_t key_size = avio_rb32(pb);
3249  uint32_t type = avio_rl32(pb);
3250  if (key_size < 8) {
3251  av_log(c->fc, AV_LOG_ERROR,
3252  "The key# %d in meta has invalid size: %d\n", i, key_size);
3253  return AVERROR_INVALIDDATA;
3254  }
3255  key_size -= 8;
3256  if (type != MKTAG('m','d','t','a')) {
3257  avio_skip(pb, key_size);
3258  }
3259  c->meta_keys[i] = av_mallocz(key_size + 1);
3260  if (!c->meta_keys[i])
3261  return AVERROR(ENOMEM);
3262  avio_read(pb, c->meta_keys[i], key_size);
3263  }
3264 
3265  return 0;
3266 }
3267 
3269 {
3270  int64_t end = avio_tell(pb) + atom.size;
3271  uint8_t *key = NULL, *val = NULL, *mean = NULL;
3272  int i;
3273  int ret = 0;
3274  AVStream *st;
3275  MOVStreamContext *sc;
3276 
3277  if (c->fc->nb_streams < 1)
3278  return 0;
3279  st = c->fc->streams[c->fc->nb_streams-1];
3280  sc = st->priv_data;
3281 
3282  for (i = 0; i < 3; i++) {
3283  uint8_t **p;
3284  uint32_t len, tag;
3285 
3286  if (end - avio_tell(pb) <= 12)
3287  break;
3288 
3289  len = avio_rb32(pb);
3290  tag = avio_rl32(pb);
3291  avio_skip(pb, 4); // flags
3292 
3293  if (len < 12 || len - 12 > end - avio_tell(pb))
3294  break;
3295  len -= 12;
3296 
3297  if (tag == MKTAG('m', 'e', 'a', 'n'))
3298  p = &mean;
3299  else if (tag == MKTAG('n', 'a', 'm', 'e'))
3300  p = &key;
3301  else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3302  avio_skip(pb, 4);
3303  len -= 4;
3304  p = &val;
3305  } else
3306  break;
3307 
3308  *p = av_malloc(len + 1);
3309  if (!*p)
3310  break;
3311  ret = ffio_read_size(pb, *p, len);
3312  if (ret < 0) {
3313  av_freep(p);
3314  break;
3315  }
3316  (*p)[len] = 0;
3317  }
3318 
3319  if (mean && key && val) {
3320  if (strcmp(key, "iTunSMPB") == 0) {
3321  int priming, remainder, samples;
3322  if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3323  if(priming>0 && priming<16384)
3324  sc->start_pad = priming;
3325  }
3326  }
3327  if (strcmp(key, "cdec") != 0) {
3328  av_dict_set(&c->fc->metadata, key, val,
3330  key = val = NULL;
3331  }
3332  } else {
3333  av_log(c->fc, AV_LOG_VERBOSE,
3334  "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3335  }
3336 
3337  avio_seek(pb, end, SEEK_SET);
3338  av_freep(&key);
3339  av_freep(&val);
3340  av_freep(&mean);
3341  return ret;
3342 }
3343 
3345 {
3346  while (atom.size > 8) {
3347  uint32_t tag = avio_rl32(pb);
3348  atom.size -= 4;
3349  if (tag == MKTAG('h','d','l','r')) {
3350  avio_seek(pb, -8, SEEK_CUR);
3351  atom.size += 8;
3352  return mov_read_default(c, pb, atom);
3353  }
3354  }
3355  return 0;
3356 }
3357 
3359 {
3360  int i;
3361  int width;
3362  int height;
3363  int display_matrix[3][3];
3364  AVStream *st;
3365  MOVStreamContext *sc;
3366  int version;
3367  int flags;
3368 
3369  if (c->fc->nb_streams < 1)
3370  return 0;
3371  st = c->fc->streams[c->fc->nb_streams-1];
3372  sc = st->priv_data;
3373 
3374  version = avio_r8(pb);
3375  flags = avio_rb24(pb);
3377 
3378  if (version == 1) {
3379  avio_rb64(pb);
3380  avio_rb64(pb);
3381  } else {
3382  avio_rb32(pb); /* creation time */
3383  avio_rb32(pb); /* modification time */
3384  }
3385  st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3386  avio_rb32(pb); /* reserved */
3387 
3388  /* highlevel (considering edits) duration in movie timebase */
3389  (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3390  avio_rb32(pb); /* reserved */
3391  avio_rb32(pb); /* reserved */
3392 
3393  avio_rb16(pb); /* layer */
3394  avio_rb16(pb); /* alternate group */
3395  avio_rb16(pb); /* volume */
3396  avio_rb16(pb); /* reserved */
3397 
3398  //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3399  // they're kept in fixed point format through all calculations
3400  // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3401  // side data, but the scale factor is not needed to calculate aspect ratio
3402  for (i = 0; i < 3; i++) {
3403  display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
3404  display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
3405  display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
3406  }
3407 
3408  width = avio_rb32(pb); // 16.16 fixed point track width
3409  height = avio_rb32(pb); // 16.16 fixed point track height
3410  sc->width = width >> 16;
3411  sc->height = height >> 16;
3412 
3413  // save the matrix and add rotate metadata when it is not the default
3414  // identity
3415  if (display_matrix[0][0] != (1 << 16) ||
3416  display_matrix[1][1] != (1 << 16) ||
3417  display_matrix[2][2] != (1 << 30) ||
3418  display_matrix[0][1] || display_matrix[0][2] ||
3419  display_matrix[1][0] || display_matrix[1][2] ||
3420  display_matrix[2][0] || display_matrix[2][1]) {
3421  int i, j;
3422  double rotate;
3423 
3424  av_freep(&sc->display_matrix);
3425  sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3426  if (!sc->display_matrix)
3427  return AVERROR(ENOMEM);
3428 
3429  for (i = 0; i < 3; i++)
3430  for (j = 0; j < 3; j++)
3431  sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3432 
3434  if (!isnan(rotate)) {
3435  char rotate_buf[64];
3436  rotate = -rotate;
3437  if (rotate < 0) // for backward compatibility
3438  rotate += 360;
3439  snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3440  av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3441  }
3442  }
3443 
3444  // transform the display width/height according to the matrix
3445  // to keep the same scale, use [width height 1<<16]
3446  if (width && height && sc->display_matrix) {
3447  double disp_transform[2];
3448 
3449  for (i = 0; i < 2; i++)
3450  disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3451 
3452  if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
3453  disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3454  fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3456  disp_transform[0] / disp_transform[1],
3457  INT_MAX);
3458  }
3459  return 0;
3460 }
3461 
3463 {
3464  MOVFragment *frag = &c->fragment;
3465  MOVTrackExt *trex = NULL;
3467  int flags, track_id, i, found = 0;
3468 
3469  avio_r8(pb); /* version */
3470  flags = avio_rb24(pb);
3471 
3472  track_id = avio_rb32(pb);
3473  if (!track_id)
3474  return AVERROR_INVALIDDATA;
3475  frag->track_id = track_id;
3476  for (i = 0; i < c->trex_count; i++)
3477  if (c->trex_data[i].track_id == frag->track_id) {
3478  trex = &c->trex_data[i];
3479  break;
3480  }
3481  if (!trex) {
3482  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3483  return AVERROR_INVALIDDATA;
3484  }
3485 
3488  frag->moof_offset : frag->implicit_offset;
3489  frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3490 
3491  frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3492  avio_rb32(pb) : trex->duration;
3493  frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
3494  avio_rb32(pb) : trex->size;
3495  frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
3496  avio_rb32(pb) : trex->flags;
3497  frag->time = AV_NOPTS_VALUE;
3498  for (i = 0; i < c->fragment_index_count; i++) {
3499  int j;
3500  MOVFragmentIndex* candidate = c->fragment_index_data[i];
3501  if (candidate->track_id == frag->track_id) {
3502  av_log(c->fc, AV_LOG_DEBUG,
3503  "found fragment index for track %u\n", frag->track_id);
3504  index = candidate;
3505  for (j = index->current_item; j < index->item_count; j++) {
3506  if (frag->implicit_offset == index->items[j].moof_offset) {
3507  av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3508  "for track %u and moof_offset %"PRId64"\n",
3509  frag->track_id, index->items[j].moof_offset);
3510  frag->time = index->items[j].time;
3511  index->current_item = j + 1;
3512  found = 1;
3513  break;
3514  }
3515  }
3516  if (found)
3517  break;
3518  }
3519  }
3520  if (index && !found) {
3521  av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3522  "it doesn't have an (in-order) entry for moof_offset "
3523  "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3524  }
3525  av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3526  return 0;
3527 }
3528 
3530 {
3531  c->chapter_track = avio_rb32(pb);
3532  return 0;
3533 }
3534 
3536 {
3537  MOVTrackExt *trex;
3538  int err;
3539 
3540  if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3541  return AVERROR_INVALIDDATA;
3542  if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3543  sizeof(*c->trex_data))) < 0) {
3544  c->trex_count = 0;
3545  return err;
3546  }
3547 
3548  c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3549 
3550  trex = &c->trex_data[c->trex_count++];
3551  avio_r8(pb); /* version */
3552  avio_rb24(pb); /* flags */
3553  trex->track_id = avio_rb32(pb);
3554  trex->stsd_id = avio_rb32(pb);
3555  trex->duration = avio_rb32(pb);
3556  trex->size = avio_rb32(pb);
3557  trex->flags = avio_rb32(pb);
3558  return 0;
3559 }
3560 
3562 {
3563  MOVFragment *frag = &c->fragment;
3564  AVStream *st = NULL;
3565  MOVStreamContext *sc;
3566  int version, i;
3567 
3568  for (i = 0; i < c->fc->nb_streams; i++) {
3569  if (c->fc->streams[i]->id == frag->track_id) {
3570  st = c->fc->streams[i];
3571  break;
3572  }
3573  }
3574  if (!st) {
3575  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3576  return AVERROR_INVALIDDATA;
3577  }
3578  sc = st->priv_data;
3579  if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3580  return 0;
3581  version = avio_r8(pb);
3582  avio_rb24(pb); /* flags */
3583  if (version) {
3584  sc->track_end = avio_rb64(pb);
3585  } else {
3586  sc->track_end = avio_rb32(pb);
3587  }
3588  return 0;
3589 }
3590 
3592 {
3593  MOVFragment *frag = &c->fragment;
3594  AVStream *st = NULL;
3595  MOVStreamContext *sc;
3596  MOVStts *ctts_data;
3597  uint64_t offset;
3598  int64_t dts;
3599  int data_offset = 0;
3600  unsigned entries, first_sample_flags = frag->flags;
3601  int flags, distance, i, err;
3602 
3603  for (i = 0; i < c->fc->nb_streams; i++) {
3604  if (c->fc->streams[i]->id == frag->track_id) {
3605  st = c->fc->streams[i];
3606  break;
3607  }
3608  }
3609  if (!st) {
3610  av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3611  return AVERROR_INVALIDDATA;
3612  }
3613  sc = st->priv_data;
3614  if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3615  return 0;
3616  avio_r8(pb); /* version */
3617  flags = avio_rb24(pb);
3618  entries = avio_rb32(pb);
3619  av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3620 
3621  /* Always assume the presence of composition time offsets.
3622  * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3623  * 1) in the initial movie, there are no samples.
3624  * 2) in the first movie fragment, there is only one sample without composition time offset.
3625  * 3) in the subsequent movie fragments, there are samples with composition time offset. */
3626  if (!sc->ctts_count && sc->sample_count)
3627  {
3628  /* Complement ctts table if moov atom doesn't have ctts atom. */
3629  ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3630  if (!ctts_data)
3631  return AVERROR(ENOMEM);
3632  sc->ctts_data = ctts_data;
3633  sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3634  sc->ctts_data[sc->ctts_count].duration = 0;
3635  sc->ctts_count++;
3636  }
3637  if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3638  return AVERROR_INVALIDDATA;
3639  if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3640  sizeof(*sc->ctts_data))) < 0) {
3641  sc->ctts_count = 0;
3642  return err;
3643  }
3644  if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
3645  if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3646  dts = sc->track_end - sc->time_offset;
3647  offset = frag->base_data_offset + data_offset;
3648  distance = 0;
3649  av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3650  for (i = 0; i < entries && !pb->eof_reached; i++) {
3651  unsigned sample_size = frag->size;
3652  int sample_flags = i ? frag->flags : first_sample_flags;
3653  unsigned sample_duration = frag->duration;
3654  int keyframe = 0;
3655 
3656  if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3657  if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
3658  if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
3659  sc->ctts_data[sc->ctts_count].count = 1;
3660  sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3661  avio_rb32(pb) : 0;
3663  if (frag->time != AV_NOPTS_VALUE) {
3664  if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3665  int64_t pts = frag->time;
3666  av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3667  " sc->dts_shift %d ctts.duration %d"
3668  " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3669  sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3670  sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3671  dts = pts - sc->dts_shift;
3672  if (flags & MOV_TRUN_SAMPLE_CTS) {
3673  dts -= sc->ctts_data[sc->ctts_count].duration;
3674  } else {
3675  dts -= sc->time_offset;
3676  }
3677  av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3678  } else {
3679  dts = frag->time - sc->time_offset;
3680  av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3681  ", using it for dts\n", dts);
3682  }
3683  frag->time = AV_NOPTS_VALUE;
3684  }
3685  sc->ctts_count++;
3687  keyframe = 1;
3688  else
3689  keyframe =
3690  !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3692  if (keyframe)
3693  distance = 0;
3694  err = av_add_index_entry(st, offset, dts, sample_size, distance,
3695  keyframe ? AVINDEX_KEYFRAME : 0);
3696  if (err < 0) {
3697  av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3698  }
3699  av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3700  "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3701  offset, dts, sample_size, distance, keyframe);
3702  distance++;
3703  dts += sample_duration;
3704  offset += sample_size;
3705  sc->data_size += sample_size;
3706  sc->duration_for_fps += sample_duration;
3707  sc->nb_frames_for_fps ++;
3708  }
3709 
3710  if (pb->eof_reached)
3711  return AVERROR_EOF;
3712 
3713  frag->implicit_offset = offset;
3714 
3715  sc->track_end = dts + sc->time_offset;
3716  if (st->duration < sc->track_end)
3717  st->duration = sc->track_end;
3718 
3719  return 0;
3720 }
3721 
3723 {
3724  int64_t offset = avio_tell(pb) + atom.size, pts;
3725  uint8_t version;
3726  unsigned i, track_id;
3727  AVStream *st = NULL;
3728  MOVStreamContext *sc;
3731  AVRational timescale;
3732 
3733  version = avio_r8(pb);
3734  if (version > 1) {
3735  avpriv_request_sample(c->fc, "sidx version %u", version);
3736  return 0;
3737  }
3738 
3739  avio_rb24(pb); // flags
3740 
3741  track_id = avio_rb32(pb); // Reference ID
3742  for (i = 0; i < c->fc->nb_streams; i++) {
3743  if (c->fc->streams[i]->id == track_id) {
3744  st = c->fc->streams[i];
3745  break;
3746  }
3747  }
3748  if (!st) {
3749  av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
3750  return 0;
3751  }
3752 
3753  sc = st->priv_data;
3754 
3755  timescale = av_make_q(1, avio_rb32(pb));
3756 
3757  if (version == 0) {
3758  pts = avio_rb32(pb);
3759  offset += avio_rb32(pb);
3760  } else {
3761  pts = avio_rb64(pb);
3762  offset += avio_rb64(pb);
3763  }
3764 
3765  avio_rb16(pb); // reserved
3766 
3767  index = av_mallocz(sizeof(MOVFragmentIndex));
3768  if (!index)
3769  return AVERROR(ENOMEM);
3770 
3771  index->track_id = track_id;
3772 
3773  index->item_count = avio_rb16(pb);
3774  index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3775 
3776  if (!index->items) {
3777  av_freep(&index);
3778  return AVERROR(ENOMEM);
3779  }
3780 
3781  for (i = 0; i < index->item_count; i++) {
3782  uint32_t size = avio_rb32(pb);
3783  uint32_t duration = avio_rb32(pb);
3784  if (size & 0x80000000) {
3785  avpriv_request_sample(c->fc, "sidx reference_type 1");
3786  av_freep(&index->items);
3787  av_freep(&index);
3788  return AVERROR_PATCHWELCOME;
3789  }
3790  avio_rb32(pb); // sap_flags
3791  index->items[i].moof_offset = offset;
3792  index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3793  offset += size;
3794  pts += duration;
3795  }
3796 
3797  st->duration = sc->track_end = pts;
3798 
3800  c->fragment_index_count + 1,
3801  sizeof(MOVFragmentIndex*));
3802  if (!tmp) {
3803  av_freep(&index->items);
3804  av_freep(&index);
3805  return AVERROR(ENOMEM);
3806  }
3807 
3808  c->fragment_index_data = tmp;
3810 
3811  if (offset == avio_size(pb))
3812  c->fragment_index_complete = 1;
3813 
3814  return 0;
3815 }
3816 
3817 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3818 /* like the files created with Adobe Premiere 5.0, for samples see */
3819 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3821 {
3822  int err;
3823 
3824  if (atom.size < 8)
3825  return 0; /* continue */
3826  if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3827  avio_skip(pb, atom.size - 4);
3828  return 0;
3829  }
3830  atom.type = avio_rl32(pb);
3831  atom.size -= 8;
3832  if (atom.type != MKTAG('m','d','a','t')) {
3833  avio_skip(pb, atom.size);
3834  return 0;
3835  }
3836  err = mov_read_mdat(c, pb, atom);
3837  return err;
3838 }
3839 
3841 {
3842 #if CONFIG_ZLIB
3843  AVIOContext ctx;
3844  uint8_t *cmov_data;
3845  uint8_t *moov_data; /* uncompressed data */
3846  long cmov_len, moov_len;
3847  int ret = -1;
3848 
3849  avio_rb32(pb); /* dcom atom */
3850  if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3851  return AVERROR_INVALIDDATA;
3852  if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3853  av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3854  return AVERROR_INVALIDDATA;
3855  }
3856  avio_rb32(pb); /* cmvd atom */
3857  if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3858  return AVERROR_INVALIDDATA;
3859  moov_len = avio_rb32(pb); /* uncompressed size */
3860  cmov_len = atom.size - 6 * 4;
3861 
3862  cmov_data = av_malloc(cmov_len);
3863  if (!cmov_data)
3864  return AVERROR(ENOMEM);
3865  moov_data = av_malloc(moov_len);
3866  if (!moov_data) {
3867  av_free(cmov_data);
3868  return AVERROR(ENOMEM);
3869  }
3870  ret = ffio_read_size(pb, cmov_data, cmov_len);
3871  if (ret < 0)
3872  goto free_and_return;
3873 
3874  if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3875  goto free_and_return;
3876  if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3877  goto free_and_return;
3879  atom.type = MKTAG('m','o','o','v');
3880  atom.size = moov_len;
3881  ret = mov_read_default(c, &ctx, atom);
3882 free_and_return:
3883  av_free(moov_data);
3884  av_free(cmov_data);
3885  return ret;
3886 #else
3887  av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3888  return AVERROR(ENOSYS);
3889 #endif
3890 }
3891 
3892 /* edit list atom */
3894 {
3895  MOVStreamContext *sc;
3896  int i, edit_count, version;
3897 
3898  if (c->fc->nb_streams < 1 || c->ignore_editlist)
3899  return 0;
3900  sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3901 
3902  version = avio_r8(pb); /* version */
3903  avio_rb24(pb); /* flags */
3904  edit_count = avio_rb32(pb); /* entries */
3905 
3906  if (!edit_count)
3907  return 0;
3908  if (sc->elst_data)
3909  av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3910  av_free(sc->elst_data);
3911  sc->elst_count = 0;
3912  sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3913  if (!sc->elst_data)
3914  return AVERROR(ENOMEM);
3915 
3916  av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3917  for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3918  MOVElst *e = &sc->elst_data[i];
3919 
3920  if (version == 1) {
3921  e->duration = avio_rb64(pb);
3922  e->time = avio_rb64(pb);
3923  } else {
3924  e->duration = avio_rb32(pb); /* segment duration */
3925  e->time = (int32_t)avio_rb32(pb); /* media time */
3926  }
3927  e->rate = avio_rb32(pb) / 65536.0;
3928  av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3929  e->duration, e->time, e->rate);
3930  }
3931  sc->elst_count = i;
3932 
3933  return 0;
3934 }
3935 
3937 {
3938  MOVStreamContext *sc;
3939 
3940  if (c->fc->nb_streams < 1)
3941  return AVERROR_INVALIDDATA;
3942  sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3943  sc->timecode_track = avio_rb32(pb);
3944  return 0;
3945 }
3946 
3948 {
3949  int ret;
3950  uint8_t uuid[16];
3951  static const uint8_t uuid_isml_manifest[] = {
3952  0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3953  0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3954  };
3955  static const uint8_t uuid_xmp[] = {
3956  0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
3957  0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
3958  };
3959 
3960  if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3961  return AVERROR_INVALIDDATA;
3962 
3963  ret = avio_read(pb, uuid, sizeof(uuid));
3964  if (ret < 0) {
3965  return ret;
3966  } else if (ret != sizeof(uuid)) {
3967  return AVERROR_INVALIDDATA;
3968  }
3969  if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3970  uint8_t *buffer, *ptr;
3971  char *endptr;
3972  size_t len = atom.size - sizeof(uuid);
3973 
3974  if (len < 4) {
3975  return AVERROR_INVALIDDATA;
3976  }
3977  ret = avio_skip(pb, 4); // zeroes
3978  len -= 4;
3979 
3980  buffer = av_mallocz(len + 1);
3981  if (!buffer) {
3982  return AVERROR(ENOMEM);
3983  }
3984  ret = avio_read(pb, buffer, len);
3985  if (ret < 0) {
3986  av_free(buffer);
3987  return ret;
3988  } else if (ret != len) {
3989  av_free(buffer);
3990  return AVERROR_INVALIDDATA;
3991  }
3992 
3993  ptr = buffer;
3994  while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3995  ptr += sizeof("systemBitrate=\"") - 1;
3996  c->bitrates_count++;
3997  c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3998  if (!c->bitrates) {
3999  c->bitrates_count = 0;
4000  av_free(buffer);
4001  return AVERROR(ENOMEM);
4002  }
4003  errno = 0;
4004  ret = strtol(ptr, &endptr, 10);
4005  if (ret < 0 || errno || *endptr != '"') {
4006  c->bitrates[c->bitrates_count - 1] = 0;
4007  } else {
4008  c->bitrates[c->bitrates_count - 1] = ret;
4009  }
4010  }
4011 
4012  av_free(buffer);
4013  } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
4014  uint8_t *buffer;
4015  size_t len = atom.size - sizeof(uuid);
4016 
4017  buffer = av_mallocz(len + 1);
4018  if (!buffer) {
4019  return AVERROR(ENOMEM);
4020  }
4021  ret = avio_read(pb, buffer, len);
4022  if (ret < 0) {
4023  av_free(buffer);
4024  return ret;
4025  } else if (ret != len) {
4026  av_free(buffer);
4027  return AVERROR_INVALIDDATA;
4028  }
4029  if (c->export_xmp) {
4030  buffer[len] = '\0';
4031  av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
4032  }
4033  av_free(buffer);
4034  }
4035  return 0;
4036 }
4037 
4039 {
4040  int ret;
4041  uint8_t content[16];
4042 
4043  if (atom.size < 8)
4044  return 0;
4045 
4046  ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
4047  if (ret < 0)
4048  return ret;
4049 
4050  if ( !c->found_moov
4051  && !c->found_mdat
4052  && !memcmp(content, "Anevia\x1A\x1A", 8)
4055  }
4056 
4057  return 0;
4058 }
4059 
4061 {
4062  uint32_t format = avio_rl32(pb);
4063  MOVStreamContext *sc;
4064  enum AVCodecID id;
4065  AVStream *st;
4066 
4067  if (c->fc->nb_streams < 1)
4068  return 0;
4069  st = c->fc->streams[c->fc->nb_streams - 1];
4070  sc = st->priv_data;
4071 
4072  switch (sc->format)
4073  {
4074  case MKTAG('e','n','c','v'): // encrypted video
4075  case MKTAG('e','n','c','a'): // encrypted audio
4076  id = mov_codec_id(st, format);
4077  if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
4078  st->codecpar->codec_id != id) {
4079  av_log(c->fc, AV_LOG_WARNING,
4080  "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
4081  (char*)&format, st->codecpar->codec_id);
4082  break;
4083  }
4084 
4085  st->codecpar->codec_id = id;
4086  sc->format = format;
4087  break;
4088 
4089  default:
4090  if (format != sc->format) {
4091  av_log(c->fc, AV_LOG_WARNING,
4092  "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
4093  (char*)&format, (char*)&sc->format);
4094  }
4095  break;
4096  }
4097 
4098  return 0;
4099 }
4100 
4102 {
4103  AVStream *st;
4104  MOVStreamContext *sc;
4105  size_t auxiliary_info_size;
4106 
4107  if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4108  return 0;
4109 
4110  st = c->fc->streams[c->fc->nb_streams - 1];
4111  sc = st->priv_data;
4112 
4113  if (sc->cenc.aes_ctr) {
4114  av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
4115  return AVERROR_INVALIDDATA;
4116  }
4117 
4118  avio_r8(pb); /* version */
4119  sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
4120 
4121  avio_rb32(pb); /* entries */
4122 
4123  if (atom.size < 8) {
4124  av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
4125  return AVERROR_INVALIDDATA;
4126  }
4127 
4128  /* save the auxiliary info as is */
4129  auxiliary_info_size = atom.size - 8;
4130 
4131  sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
4132  if (!sc->cenc.auxiliary_info) {
4133  return AVERROR(ENOMEM);
4134  }
4135 
4136  sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
4137 
4139 
4140  if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
4141  av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
4142  return AVERROR_INVALIDDATA;
4143  }
4144 
4145  /* initialize the cipher */
4146  sc->cenc.aes_ctr = av_aes_ctr_alloc();
4147  if (!sc->cenc.aes_ctr) {
4148  return AVERROR(ENOMEM);
4149  }
4150 
4151  return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
4152 }
4153 
4155 {
4156  AVStream *st;
4157  MOVStreamContext *sc;
4158  size_t data_size;
4159  int atom_header_size;
4160  int flags;
4161 
4162  if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4163  return 0;
4164 
4165  st = c->fc->streams[c->fc->nb_streams - 1];
4166  sc = st->priv_data;
4167 
4169  av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
4170  return AVERROR_INVALIDDATA;
4171  }
4172 
4173  atom_header_size = 9;
4174 
4175  avio_r8(pb); /* version */
4176  flags = avio_rb24(pb);
4177 
4178  if ((flags & 0x01) != 0) {
4179  atom_header_size += 8;
4180 
4181  avio_rb32(pb); /* info type */
4182  avio_rb32(pb); /* info type param */
4183  }
4184 
4186  avio_rb32(pb); /* entries */
4187 
4188  if (atom.size <= atom_header_size) {
4189  return 0;
4190  }
4191 
4192  /* save the auxiliary info sizes as is */
4193  data_size = atom.size - atom_header_size;
4194 
4195  sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
4196  if (!sc->cenc.auxiliary_info_sizes) {
4197  return AVERROR(ENOMEM);
4198  }
4199 
4200  sc->cenc.auxiliary_info_sizes_count = data_size;
4201 
4202  if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
4203  av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
4204  return AVERROR_INVALIDDATA;
4205  }
4206 
4207  return 0;
4208 }
4209 
4210 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
4211 {
4212  uint32_t encrypted_bytes;
4213  uint16_t subsample_count;
4214  uint16_t clear_bytes;
4215  uint8_t* input_end = input + size;
4216 
4217  /* read the iv */
4219  av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
4220  return AVERROR_INVALIDDATA;
4221  }
4222 
4225 
4226  if (!sc->cenc.use_subsamples)
4227  {
4228  /* decrypt the whole packet */
4229  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
4230  return 0;
4231  }
4232 
4233  /* read the subsample count */
4234  if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4235  av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
4236  return AVERROR_INVALIDDATA;
4237  }
4238 
4239  subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
4240  sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4241 
4242  for (; subsample_count > 0; subsample_count--)
4243  {
4244  if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4245  av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
4246  return AVERROR_INVALIDDATA;
4247  }
4248 
4249  /* read the number of clear / encrypted bytes */
4250  clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
4251  sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4252  encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
4253  sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
4254 
4255  if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
4256  av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
4257  return AVERROR_INVALIDDATA;
4258  }
4259 
4260  /* skip the clear bytes */
4261  input += clear_bytes;
4262 
4263  /* decrypt the encrypted bytes */
4264  av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
4265  input += encrypted_bytes;
4266  }
4267 
4268  if (input < input_end) {
4269  av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
4270  return AVERROR_INVALIDDATA;
4271  }
4272 
4273  return 0;
4274 }
4275 
4277 {
4278  size_t auxiliary_info_seek_offset = 0;
4279  int i;
4280 
4282  auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * sc->current_sample;
4283  } else if (sc->cenc.auxiliary_info_sizes) {
4285  av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
4287  return AVERROR_INVALIDDATA;
4288  }
4289 
4290  for (i = 0; i < sc->current_sample; i++) {
4291  auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
4292  }
4293  }
4294 
4295  if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
4296  av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
4297  auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
4298  return AVERROR_INVALIDDATA;
4299  }
4300 
4301  sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
4302 
4303  return 0;
4304 }
4305 
4307 { MKTAG('A','C','L','R'), mov_read_aclr },
4308 { MKTAG('A','P','R','G'), mov_read_avid },
4309 { MKTAG('A','A','L','P'), mov_read_avid },
4310 { MKTAG('A','R','E','S'), mov_read_ares },
4311 { MKTAG('a','v','s','s'), mov_read_avss },
4312 { MKTAG('c','h','p','l'), mov_read_chpl },
4313 { MKTAG('c','o','6','4'), mov_read_stco },
4314 { MKTAG('c','o','l','r'), mov_read_colr },
4315 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4316 { MKTAG('d','i','n','f'), mov_read_default },
4317 { MKTAG('D','p','x','E'), mov_read_dpxe },
4318 { MKTAG('d','r','e','f'), mov_read_dref },
4319 { MKTAG('e','d','t','s'), mov_read_default },
4320 { MKTAG('e','l','s','t'), mov_read_elst },
4321 { MKTAG('e','n','d','a'), mov_read_enda },
4322 { MKTAG('f','i','e','l'), mov_read_fiel },
4323 { MKTAG('a','d','r','m'), mov_read_adrm },
4324 { MKTAG('f','t','y','p'), mov_read_ftyp },
4325 { MKTAG('g','l','b','l'), mov_read_glbl },
4326 { MKTAG('h','d','l','r'), mov_read_hdlr },
4327 { MKTAG('i','l','s','t'), mov_read_ilst },
4328 { MKTAG('j','p','2','h'), mov_read_jp2h },
4329 { MKTAG('m','d','a','t'), mov_read_mdat },
4330 { MKTAG('m','d','h','d'), mov_read_mdhd },
4331 { MKTAG('m','d','i','a'), mov_read_default },
4332 { MKTAG('m','e','t','a'), mov_read_meta },
4333 { MKTAG('m','i','n','f'), mov_read_default },
4334 { MKTAG('m','o','o','f'), mov_read_moof },
4335 { MKTAG('m','o','o','v'), mov_read_moov },
4336 { MKTAG('m','v','e','x'), mov_read_default },
4337 { MKTAG('m','v','h','d'), mov_read_mvhd },
4338 { MKTAG('S','M','I',' '), mov_read_svq3 },
4339 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4340 { MKTAG('a','v','c','C'), mov_read_glbl },
4341 { MKTAG('p','a','s','p'), mov_read_pasp },
4342 { MKTAG('s','i','d','x'), mov_read_sidx },
4343 { MKTAG('s','t','b','l'), mov_read_default },
4344 { MKTAG('s','t','c','o'), mov_read_stco },
4345 { MKTAG('s','t','p','s'), mov_read_stps },
4346 { MKTAG('s','t','r','f'), mov_read_strf },
4347 { MKTAG('s','t','s','c'), mov_read_stsc },
4348 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4349 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4350 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4351 { MKTAG('s','t','t','s'), mov_read_stts },
4352 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4353 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4354 { MKTAG('t','f','d','t'), mov_read_tfdt },
4355 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4356 { MKTAG('t','r','a','k'), mov_read_trak },
4357 { MKTAG('t','r','a','f'), mov_read_default },
4358 { MKTAG('t','r','e','f'), mov_read_default },
4359 { MKTAG('t','m','c','d'), mov_read_tmcd },
4360 { MKTAG('c','h','a','p'), mov_read_chap },
4361 { MKTAG('t','r','e','x'), mov_read_trex },
4362 { MKTAG('t','r','u','n'), mov_read_trun },
4363 { MKTAG('u','d','t','a'), mov_read_default },
4364 { MKTAG('w','a','v','e'), mov_read_wave },
4365 { MKTAG('e','s','d','s'), mov_read_esds },
4366 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4367 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4368 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4369 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4370 { MKTAG('w','f','e','x'), mov_read_wfex },
4371 { MKTAG('c','m','o','v'), mov_read_cmov },
4372 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4373 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4374 { MKTAG('s','b','g','p'), mov_read_sbgp },
4375 { MKTAG('h','v','c','C'), mov_read_glbl },
4376 { MKTAG('u','u','i','d'), mov_read_uuid },
4377 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4378 { MKTAG('f','r','e','e'), mov_read_free },
4379 { MKTAG('-','-','-','-'), mov_read_custom },
4380 { MKTAG('s','i','n','f'), mov_read_default },
4381 { MKTAG('f','r','m','a'), mov_read_frma },
4382 { MKTAG('s','e','n','c'), mov_read_senc },
4383 { MKTAG('s','a','i','z'), mov_read_saiz },
4384 { 0, NULL }
4385 };
4386 
4388 {
4389  int64_t total_size = 0;
4390  MOVAtom a;
4391  int i;
4392 
4393  if (c->atom_depth > 10) {
4394  av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4395  return AVERROR_INVALIDDATA;
4396  }
4397  c->atom_depth ++;
4398 
4399  if (atom.size < 0)
4400  atom.size = INT64_MAX;
4401  while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4402  int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4403  a.size = atom.size;
4404  a.type=0;
4405  if (atom.size >= 8) {
4406  a.size = avio_rb32(pb);
4407  a.type = avio_rl32(pb);
4408  if (a.type == MKTAG('f','r','e','e') &&
4409  a.size >= 8 &&
4410  c->moov_retry) {
4411  uint8_t buf[8];
4412  uint32_t *type = (uint32_t *)buf + 1;
4413  if (avio_read(pb, buf, 8) != 8)
4414  return AVERROR_INVALIDDATA;
4415  avio_seek(pb, -8, SEEK_CUR);
4416  if (*type == MKTAG('m','v','h','d') ||
4417  *type == MKTAG('c','m','o','v')) {
4418  av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4419  a.type = MKTAG('m','o','o','v');
4420  }
4421  }
4422  if (atom.type != MKTAG('r','o','o','t') &&
4423  atom.type != MKTAG('m','o','o','v'))
4424  {
4425  if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4426  {
4427  av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4428  avio_skip(pb, -8);
4429  c->atom_depth --;
4430  return 0;
4431  }
4432  }
4433  total_size += 8;
4434  if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4435  a.size = avio_rb64(pb) - 8;
4436  total_size += 8;
4437  }
4438  }
4439  av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4440  a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4441  if (a.size == 0) {
4442  a.size = atom.size - total_size + 8;
4443  }
4444  a.size -= 8;
4445  if (a.size < 0)
4446  break;
4447  a.size = FFMIN(a.size, atom.size - total_size);
4448 
4449  for (i = 0; mov_default_parse_table[i].type; i++)
4450  if (mov_default_parse_table[i].type == a.type) {
4451  parse = mov_default_parse_table[i].parse;
4452  break;
4453  }
4454 
4455  // container is user data
4456  if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4457  atom.type == MKTAG('i','l','s','t')))
4459 
4460  // Supports parsing the QuickTime Metadata Keys.
4461  // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4462  if (!parse && c->found_hdlr_mdta &&
4463  atom.type == MKTAG('m','e','t','a') &&
4464  a.type == MKTAG('k','e','y','s')) {
4465  parse = mov_read_keys;
4466  }
4467 
4468  if (!parse) { /* skip leaf atoms data */
4469  avio_skip(pb, a.size);
4470  } else {
4471  int64_t start_pos = avio_tell(pb);
4472  int64_t left;
4473  int err = parse(c, pb, a);
4474  if (err < 0) {
4475  c->atom_depth --;
4476  return err;
4477  }
4478  if (c->found_moov && c->found_mdat &&
4479  ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4480  start_pos + a.size == avio_size(pb))) {
4481  if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4482  c->next_root_atom = start_pos + a.size;
4483  c->atom_depth --;
4484  return 0;
4485  }
4486  left = a.size - avio_tell(pb) + start_pos;
4487  if (left > 0) /* skip garbage at atom end */
4488  avio_skip(pb, left);
4489  else if (left < 0) {
4490  av_log(c->fc, AV_LOG_WARNING,
4491  "overread end of atom '%.4s' by %"PRId64" bytes\n",
4492  (char*)&a.type, -left);
4493  avio_seek(pb, left, SEEK_CUR);
4494  }
4495  }
4496 
4497  total_size += a.size;
4498  }
4499 
4500  if (total_size < atom.size && atom.size < 0x7ffff)
4501  avio_skip(pb, atom.size - total_size);
4502 
4503  c->atom_depth --;
4504  return 0;
4505 }
4506 
4507 static int mov_probe(AVProbeData *p)
4508 {
4509  int64_t offset;
4510  uint32_t tag;
4511  int score = 0;
4512  int moov_offset = -1;
4513 
4514  /* check file header */
4515  offset = 0;
4516  for (;;) {
4517  /* ignore invalid offset */
4518  if ((offset + 8) > (unsigned int)p->buf_size)
4519  break;
4520  tag = AV_RL32(p->buf + offset + 4);
4521  switch(tag) {
4522  /* check for obvious tags */
4523  case MKTAG('m','o','o','v'):
4524  moov_offset = offset + 4;
4525  case MKTAG('m','d','a','t'):
4526  case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4527  case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4528  case MKTAG('f','t','y','p'):
4529  if (AV_RB32(p->buf+offset) < 8 &&
4530  (AV_RB32(p->buf+offset) != 1 ||
4531  offset + 12 > (unsigned int)p->buf_size ||
4532  AV_RB64(p->buf+offset + 8) == 0)) {
4533  score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4534  } else if (tag == MKTAG('f','t','y','p') &&
4535  ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4536  || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4537  )) {
4538  score = FFMAX(score, 5);
4539  } else {
4540  score = AVPROBE_SCORE_MAX;
4541  }
4542  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4543  break;
4544  /* those are more common words, so rate then a bit less */
4545  case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4546  case MKTAG('w','i','d','e'):
4547  case MKTAG('f','r','e','e'):
4548  case MKTAG('j','u','n','k'):
4549  case MKTAG('p','i','c','t'):
4550  score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4551  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4552  break;
4553  case MKTAG(0x82,0x82,0x7f,0x7d):
4554  case MKTAG('s','k','i','p'):
4555  case MKTAG('u','u','i','d'):
4556  case MKTAG('p','r','f','l'):
4557  /* if we only find those cause probedata is too small at least rate them */
4558  score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4559  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4560  break;
4561  default:
4562  offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4563  }
4564  }
4565  if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4566  /* moov atom in the header - we should make sure that this is not a
4567  * MOV-packed MPEG-PS */
4568  offset = moov_offset;
4569 
4570  while(offset < (p->buf_size - 16)){ /* Sufficient space */
4571  /* We found an actual hdlr atom */
4572  if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
4573  AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
4574  AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4575  av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4576  /* We found a media handler reference atom describing an
4577  * MPEG-PS-in-MOV, return a
4578  * low score to force expanding the probe window until
4579  * mpegps_probe finds what it needs */
4580  return 5;
4581  }else
4582  /* Keep looking */
4583  offset+=2;
4584  }
4585  }
4586 
4587  return score;
4588 }
4589 
4590 // must be done after parsing all trak because there's no order requirement
4592 {
4593  MOVContext *mov = s->priv_data;
4594  AVStream *st = NULL;
4595  MOVStreamContext *sc;
4596  int64_t cur_pos;
4597  int i;
4598 
4599  for (i = 0; i < s->nb_streams; i++)
4600  if (s->streams[i]->id == mov->chapter_track) {
4601  st = s->streams[i];
4602  break;
4603  }
4604  if (!st) {
4605  av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4606  return;
4607  }
4608 
4609  st->discard = AVDISCARD_ALL;
4610  sc = st->priv_data;
4611  cur_pos = avio_tell(sc->pb);
4612 
4613  for (i = 0; i < st->nb_index_entries; i++) {
4614  AVIndexEntry *sample = &st->index_entries[i];
4615  int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4616  uint8_t *title;
4617  uint16_t ch;
4618  int len, title_len;
4619 
4620  if (end < sample->timestamp) {
4621  av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4622  end = AV_NOPTS_VALUE;
4623  }
4624 
4625  if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4626  av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4627  goto finish;
4628  }
4629 
4630  // the first two bytes are the length of the title
4631  len = avio_rb16(sc->pb);
4632  if (len > sample->size-2)
4633  continue;
4634  title_len = 2*len + 1;
4635  if (!(title = av_mallocz(title_len)))
4636  goto finish;
4637 
4638  // The samples could theoretically be in any encoding if there's an encd
4639  // atom following, but in practice are only utf-8 or utf-16, distinguished
4640  // instead by the presence of a BOM
4641  if (!len) {
4642  title[0] = 0;
4643  } else {
4644  ch = avio_rb16(sc->pb);
4645  if (ch == 0xfeff)
4646  avio_get_str16be(sc->pb, len, title, title_len);
4647  else if (ch == 0xfffe)
4648  avio_get_str16le(sc->pb, len, title, title_len);
4649  else {
4650  AV_WB16(title, ch);
4651  if (len == 1 || len == 2)
4652  title[len] = 0;
4653  else
4654  avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4655  }
4656  }
4657 
4658  avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4659  av_freep(&title);
4660  }
4661 finish:
4662  avio_seek(sc->pb, cur_pos, SEEK_SET);
4663 }
4664 
4666  uint32_t value, int flags)
4667 {
4668  AVTimecode tc;
4669  char buf[AV_TIMECODE_STR_SIZE];
4670  AVRational rate = st->avg_frame_rate;
4671  int ret = av_timecode_init(&tc, rate, flags, 0, s);
4672  if (ret < 0)
4673  return ret;
4674  av_dict_set(&st->metadata, "timecode",
4675  av_timecode_make_string(&tc, buf, value), 0);
4676  return 0;
4677 }
4678 
4680 {
4681  MOVStreamContext *sc = st->priv_data;
4682  int flags = 0;
4683  int64_t cur_pos = avio_tell(sc->pb);
4684  uint32_t value;
4685 
4686  if (!st->nb_index_entries)
4687  return -1;
4688 
4689  avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4690  value = avio_rb32(s->pb);
4691 
4692  if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4693  if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4694  if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4695 
4696  /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4697  * not the case) and thus assume "frame number format" instead of QT one.
4698  * No sample with tmcd track can be found with a QT timecode at the moment,
4699  * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4700  * format). */
4701  parse_timecode_in_framenum_format(s, st, value, flags);
4702 
4703  avio_seek(sc->pb, cur_pos, SEEK_SET);
4704  return 0;
4705 }
4706 
4708 {
4709  MOVContext *mov = s->priv_data;
4710  int i, j;
4711 
4712  for (i = 0; i < s->nb_streams; i++) {
4713  AVStream *st = s->streams[i];
4714  MOVStreamContext *sc = st->priv_data;
4715 
4716  if (!sc)
4717  continue;
4718 
4719  av_freep(&sc->ctts_data);
4720  for (j = 0; j < sc->drefs_count; j++) {
4721  av_freep(&sc->drefs[j].path);
4722  av_freep(&sc->drefs[j].dir);
4723  }
4724  av_freep(&sc->drefs);
4725 
4726  sc->drefs_count = 0;
4727 
4728  if (!sc->pb_is_copied)
4729  ff_format_io_close(s, &sc->pb);
4730 
4731  sc->pb = NULL;
4732  av_freep(&sc->chunk_offsets);
4733  av_freep(&sc->stsc_data);
4734  av_freep(&sc->sample_sizes);
4735  av_freep(&sc->keyframes);
4736  av_freep(&sc->stts_data);
4737  av_freep(&sc->stps_data);
4738  av_freep(&sc->elst_data);
4739  av_freep(&sc->rap_group);
4740  av_freep(&sc->display_matrix);
4741 
4745  }
4746 
4747  if (mov->dv_demux) {
4749  mov->dv_fctx = NULL;
4750  }
4751 
4752  if (mov->meta_keys) {
4753  for (i = 1; i < mov->meta_keys_count; i++) {
4754  av_freep(&mov->meta_keys[i]);
4755  }
4756  av_freep(&mov->meta_keys);
4757  }
4758 
4759  av_freep(&mov->trex_data);
4760  av_freep(&mov->bitrates);
4761 
4762  for (i = 0; i < mov->fragment_index_count; i++) {
4764  av_freep(&index->items);
4765  av_freep(&mov->fragment_index_data[i]);
4766  }
4768 
4769  av_freep(&mov->aes_decrypt);
4770 
4771  return 0;
4772 }
4773 
4774 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4775 {
4776  int i;
4777 
4778  for (i = 0; i < s->nb_streams; i++) {
4779  AVStream *st = s->streams[i];
4780  MOVStreamContext *sc = st->priv_data;
4781 
4782  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
4783  sc->timecode_track == tmcd_id)
4784  return 1;
4785  }
4786  return 0;
4787 }
4788 
4789 /* look for a tmcd track not referenced by any video track, and export it globally */
4791 {
4792  int i;
4793 
4794  for (i = 0; i < s->nb_streams; i++) {
4795  AVStream *st = s->streams[i];
4796 
4797  if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
4798  !tmcd_is_referenced(s, i + 1)) {
4799  AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4800  if (tcr) {
4801  av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4802  break;
4803  }
4804  }
4805  }
4806 }
4807 
4808 static int read_tfra(MOVContext *mov, AVIOContext *f)
4809 {
4811  int version, fieldlength, i, j;
4812  int64_t pos = avio_tell(f);
4813  uint32_t size = avio_rb32(f);
4814  void *tmp;
4815 
4816  if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4817  return 1;
4818  }
4819  av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4820  index = av_mallocz(sizeof(MOVFragmentIndex));
4821  if (!index) {
4822  return AVERROR(ENOMEM);
4823  }
4824 
4826  mov->fragment_index_count + 1,
4827  sizeof(MOVFragmentIndex*));
4828  if (!tmp) {
4829  av_freep(&index);
4830  return AVERROR(ENOMEM);
4831  }
4832  mov->fragment_index_data = tmp;
4834 
4835  version = avio_r8(f);
4836  avio_rb24(f);
4837  index->track_id = avio_rb32(f);
4838  fieldlength = avio_rb32(f);
4839  index->item_count = avio_rb32(f);
4840  index->items = av_mallocz_array(
4841  index->item_count, sizeof(MOVFragmentIndexItem));
4842  if (!index->items) {
4843  index->item_count = 0;
4844  return AVERROR(ENOMEM);
4845  }
4846  for (i = 0; i < index->item_count; i++) {
4847  int64_t time, offset;
4848  if (version == 1) {
4849  time = avio_rb64(f);
4850  offset = avio_rb64(f);
4851  } else {
4852  time = avio_rb32(f);
4853  offset = avio_rb32(f);
4854  }
4855  index->items[i].time = time;
4856  index->items[i].moof_offset = offset;
4857  for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4858  avio_r8(f);
4859  for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4860  avio_r8(f);
4861  for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4862  avio_r8(f);
4863  }
4864 
4865  avio_seek(f, pos + size, SEEK_SET);
4866  return 0;
4867 }
4868 
4870 {
4871  int64_t stream_size = avio_size(f);
4872  int64_t original_pos = avio_tell(f);
4873  int64_t seek_ret;
4874  int32_t mfra_size;
4875  int ret = -1;
4876  if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4877  ret = seek_ret;
4878  goto fail;
4879  }
4880  mfra_size = avio_rb32(f);
4881  if (mfra_size < 0 || mfra_size > stream_size) {
4882  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4883  goto fail;
4884  }
4885  if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4886  ret = seek_ret;
4887  goto fail;
4888  }
4889  if (avio_rb32(f) != mfra_size) {
4890  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4891  goto fail;
4892  }
4893  if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4894  av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4895  goto fail;
4896  }
4897  av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4898  do {
4899  ret = read_tfra(c, f);
4900  if (ret < 0)
4901  goto fail;
4902  } while (!ret);
4903  ret = 0;
4904 fail:
4905  seek_ret = avio_seek(f, original_pos, SEEK_SET);
4906  if (seek_ret < 0) {
4907  av_log(c->fc, AV_LOG_ERROR,
4908  "failed to seek back after looking for mfra\n");
4909  ret = seek_ret;
4910  }
4911  return ret;
4912 }
4913 
4915 {
4916  MOVContext *mov = s->priv_data;
4917  AVIOContext *pb = s->pb;
4918  int j, err;
4919  MOVAtom atom = { AV_RL32("root") };
4920  int i;
4921 
4922  if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
4923  av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
4925  return AVERROR(EINVAL);
4926  }
4927 
4928  mov->fc = s;
4929  mov->trak_index = -1;
4930  /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4931  if (pb->seekable)
4932  atom.size = avio_size(pb);
4933  else
4934  atom.size = INT64_MAX;
4935 
4936  /* check MOV header */
4937  do {
4938  if (mov->moov_retry)
4939  avio_seek(pb, 0, SEEK_SET);
4940  if ((err = mov_read_default(mov, pb, atom)) < 0) {
4941  av_log(s, AV_LOG_ERROR, "error reading header\n");
4942  mov_read_close(s);
4943  return err;
4944  }
4945  } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4946  if (!mov->found_moov) {
4947  av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4948  mov_read_close(s);
4949  return AVERROR_INVALIDDATA;
4950  }
4951  av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4952 
4953  if (pb->seekable) {
4954  if (mov->chapter_track > 0 && !mov->ignore_chapters)
4955  mov_read_chapters(s);
4956  for (i = 0; i < s->nb_streams; i++)
4957  if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd"))
4958  mov_read_timecode_track(s, s->streams[i]);
4959  }
4960 
4961  /* copy timecode metadata from tmcd tracks to the related video streams */
4962  for (i = 0; i < s->nb_streams; i++) {
4963  AVStream *st = s->streams[i];
4964  MOVStreamContext *sc = st->priv_data;
4965  if (sc->timecode_track > 0) {
4966  AVDictionaryEntry *tcr;
4967  int tmcd_st_id = -1;
4968 
4969  for (j = 0; j < s->nb_streams; j++)
4970  if (s->streams[j]->id == sc->timecode_track)
4971  tmcd_st_id = j;
4972 
4973  if (tmcd_st_id < 0 || tmcd_st_id == i)
4974  continue;
4975  tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4976  if (tcr)
4977  av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4978  }
4979  }
4981 
4982  for (i = 0; i < s->nb_streams; i++) {
4983  AVStream *st = s->streams[i];
4984  MOVStreamContext *sc = st->priv_data;
4985  fix_timescale(mov, sc);
4987  st->skip_samples = sc->start_pad;
4988  }
4989  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4991  sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4993  if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
4994  st->codecpar->width = sc->width;
4995  st->codecpar->height = sc->height;
4996  }
4998  if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4999  return err;
5000  }
5001  }
5002  if (mov->handbrake_version &&
5003  mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
5005  ) {
5006  av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
5008  }
5009  }
5010 
5011  if (mov->trex_data) {
5012  for (i = 0; i < s->nb_streams; i++) {
5013  AVStream *st = s->streams[i];
5014  MOVStreamContext *sc = st->priv_data;
5015  if (st->duration > 0)
5016  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
5017  }
5018  }
5019 
5020  if (mov->use_mfra_for > 0) {
5021  for (i = 0; i < s->nb_streams; i++) {
5022  AVStream *st = s->streams[i];
5023  MOVStreamContext *sc = st->priv_data;
5024  if (sc->duration_for_fps > 0) {
5025  st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
5026  sc->duration_for_fps;
5027  }
5028  }
5029  }
5030 
5031  for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
5032  if (mov->bitrates[i]) {
5033  s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
5034  }
5035  }
5036 
5037  ff_rfps_calculate(s);
5038 
5039  for (i = 0; i < s->nb_streams; i++) {
5040  AVStream *st = s->streams[i];
5041  MOVStreamContext *sc = st->priv_data;
5042 
5043  switch (st->codecpar->codec_type) {
5044  case AVMEDIA_TYPE_AUDIO:
5045  err = ff_replaygain_export(st, s->metadata);
5046  if (err < 0) {
5047  mov_read_close(s);
5048  return err;
5049  }
5050  break;
5051  case AVMEDIA_TYPE_VIDEO:
5052  if (sc->display_matrix) {
5053  AVPacketSideData *sd, *tmp;
5054 
5055  tmp = av_realloc_array(st->side_data,
5056  st->nb_side_data + 1, sizeof(*tmp));
5057  if (!tmp)
5058  return AVERROR(ENOMEM);
5059 
5060  st->side_data = tmp;
5061  st->nb_side_data++;
5062 
5063  sd = &st->side_data[st->nb_side_data - 1];
5065  sd->size = sizeof(int32_t) * 9;
5066  sd->data = (uint8_t*)sc->display_matrix;
5067  sc->display_matrix = NULL;
5068  }
5069  break;
5070  }
5071  }
5073 
5074  return 0;
5075 }
5076 
5078 {
5080  int64_t best_dts = INT64_MAX;
5081  int i;
5082  for (i = 0; i < s->nb_streams; i++) {
5083  AVStream *avst = s->streams[i];
5084  MOVStreamContext *msc = avst->priv_data;
5085  if (msc->pb && msc->current_sample < avst->nb_index_entries) {
5086  AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
5087  int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
5088  av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
5089  if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
5090  (s->pb->seekable &&
5091  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
5092  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
5093  (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
5094  sample = current_sample;
5095  best_dts = dts;
5096  *st = avst;
5097  }
5098  }
5099  }
5100  return sample;
5101 }
5102 
5103 static int should_retry(AVIOContext *pb, int error_code) {
5104  if (error_code == AVERROR_EOF || avio_feof(pb))
5105  return 0;
5106 
5107  return 1;
5108 }
5109 
5110 static int mov_switch_root(AVFormatContext *s, int64_t target)
5111 {
5112  MOVContext *mov = s->priv_data;
5113  int i, j;
5114  int already_read = 0;
5115 
5116  if (avio_seek(s->pb, target, SEEK_SET) != target) {
5117  av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
5118  return AVERROR_INVALIDDATA;
5119  }
5120 
5121  mov->next_root_atom = 0;
5122 
5123  for (i = 0; i < mov->fragment_index_count; i++) {
5125  int found = 0;
5126  for (j = 0; j < index->item_count; j++) {
5127  MOVFragmentIndexItem *item = &index->items[j];
5128  if (found) {
5129  mov->next_root_atom = item->moof_offset;
5130  break; // Advance to next index in outer loop
5131  } else if (item->moof_offset == target) {
5132  index->current_item = FFMIN(j, index->current_item);
5133  if (item->headers_read)
5134  already_read = 1;
5135  item->headers_read = 1;
5136  found = 1;
5137  }
5138  }
5139  if (!found)
5140  index->current_item = 0;
5141  }
5142 
5143  if (already_read)
5144  return 0;
5145 
5146  mov->found_mdat = 0;
5147 
5148  if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
5149  avio_feof(s->pb))
5150  return AVERROR_EOF;
5151  av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
5152 
5153  return 1;
5154 }
5155 
5157 {
5158  MOVContext *mov = s->priv_data;
5159  MOVStreamContext *sc;
5161  AVStream *st = NULL;
5162  int ret;
5163  mov->fc = s;
5164  retry:
5165  sample = mov_find_next_sample(s, &st);
5166  if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
5167  if (!mov->next_root_atom)
5168  return AVERROR_EOF;
5169  if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
5170  return ret;
5171  goto retry;
5172  }
5173  sc = st->priv_data;
5174  /* must be done just before reading, to avoid infinite loop on sample */
5175  sc->current_sample++;
5176 
5177  if (mov->next_root_atom) {
5178  sample->pos = FFMIN(sample->pos, mov->next_root_atom);
5179  sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
5180  }
5181 
5182  if (st->discard != AVDISCARD_ALL) {
5183  int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
5184  if (ret64 != sample->pos) {
5185  av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
5186  sc->ffindex, sample->pos);
5187  sc->current_sample -= should_retry(sc->pb, ret64);
5188  return AVERROR_INVALIDDATA;
5189  }
5190  ret = av_get_packet(sc->pb, pkt, sample->size);
5191  if (ret < 0) {
5192  sc->current_sample -= should_retry(sc->pb, ret);
5193  return ret;
5194  }
5195  if (sc->has_palette) {
5196  uint8_t *pal;
5197 
5199  if (!pal) {
5200  av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
5201  } else {
5202  memcpy(pal, sc->palette, AVPALETTE_SIZE);
5203  sc->has_palette = 0;
5204  }
5205  }
5206 #if CONFIG_DV_DEMUXER
5207  if (mov->dv_demux && sc->dv_audio_container) {
5208  avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
5209  av_freep(&pkt->data);
5210  pkt->size = 0;
5211  ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
5212  if (ret < 0)
5213  return ret;
5214  }
5215 #endif
5216  }
5217 
5218  pkt->stream_index = sc->ffindex;
5219  pkt->dts = sample->timestamp;
5220  if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
5221  pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
5222  /* update ctts context */
5223  sc->ctts_sample++;
5224  if (sc->ctts_index < sc->ctts_count &&
5225  sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
5226  sc->ctts_index++;
5227  sc->ctts_sample = 0;
5228  }
5229  if (sc->wrong_dts)
5230  pkt->dts = AV_NOPTS_VALUE;
5231  } else {
5232  int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
5234  pkt->duration = next_dts - pkt->dts;
5235  pkt->pts = pkt->dts;
5236  }
5237  if (st->discard == AVDISCARD_ALL)
5238  goto retry;
5239  pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
5240  pkt->pos = sample->pos;
5241 
5242  if (mov->aax_mode)
5243  aax_filter(pkt->data, pkt->size, mov);
5244 
5245  if (sc->cenc.aes_ctr) {
5246  ret = cenc_filter(mov, sc, pkt->data, pkt->size);
5247  if (ret) {
5248  return ret;
5249  }
5250  }
5251 
5252  return 0;
5253 }
5254 
5255 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
5256 {
5257  MOVContext *mov = s->priv_data;
5258  int i, j;
5259 
5260  if (!mov->fragment_index_complete)
5261  return 0;
5262 
5263  for (i = 0; i < mov->fragment_index_count; i++) {
5264  if (mov->fragment_index_data[i]->track_id == st->id) {
5266  for (j = index->item_count - 1; j >= 0; j--) {
5267  if (index->items[j].time <= timestamp) {
5268  if (index->items[j].headers_read)
5269  return 0;
5270 
5271  return mov_switch_root(s, index->items[j].moof_offset);
5272  }
5273  }
5274  }
5275  }
5276 
5277  return 0;
5278 }
5279 
5280 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
5281 {
5282  MOVStreamContext *sc = st->priv_data;
5283  int sample, time_sample;
5284  int i;
5285 
5286  int ret = mov_seek_fragment(s, st, timestamp);
5287  if (ret < 0)
5288  return ret;
5289 
5290  sample = av_index_search_timestamp(st, timestamp, flags);
5291  av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
5292  if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
5293  sample = 0;
5294  if (sample < 0) /* not sure what to do */
5295  return AVERROR_INVALIDDATA;
5296  sc->current_sample = sample;
5297  av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
5298  /* adjust ctts index */
5299  if (sc->ctts_data) {
5300  time_sample = 0;
5301  for (i = 0; i < sc->ctts_count; i++) {
5302  int next = time_sample + sc->ctts_data[i].count;
5303  if (next > sc->current_sample) {
5304  sc->ctts_index = i;
5305  sc->ctts_sample = sc->current_sample - time_sample;
5306  break;
5307  }
5308  time_sample = next;
5309  }
5310  }
5311 
5312  ret = mov_seek_auxiliary_info(s, sc);
5313  if (ret < 0) {
5314  return ret;
5315  }
5316 
5317  return sample;
5318 }
5319 
5320 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
5321 {
5322  MOVContext *mc = s->priv_data;
5323  AVStream *st;
5324  int sample;
5325  int i;
5326 
5327  if (stream_index >= s->nb_streams)
5328  return AVERROR_INVALIDDATA;
5329 
5330  st = s->streams[stream_index];
5331  sample = mov_seek_stream(s, st, sample_time, flags);
5332  if (sample < 0)
5333  return sample;
5334 
5335  if (mc->seek_individually) {
5336  /* adjust seek timestamp to found sample timestamp */
5337  int64_t seek_timestamp = st->index_entries[sample].timestamp;
5338 
5339  for (i = 0; i < s->nb_streams; i++) {
5340  int64_t timestamp;
5341  MOVStreamContext *sc = s->streams[i]->priv_data;
5342  st = s->streams[i];
5343  st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5344 
5345  if (stream_index == i)
5346  continue;
5347 
5348  timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5349  mov_seek_stream(s, st, timestamp, flags);
5350  }
5351  } else {
5352  for (i = 0; i < s->nb_streams; i++) {
5353  MOVStreamContext *sc;
5354  st = s->streams[i];
5355  sc = st->priv_data;
5356  sc->current_sample = 0;
5357  }
5358  while (1) {
5359  MOVStreamContext *sc;
5360  AVIndexEntry *entry = mov_find_next_sample(s, &st);
5361  if (!entry)
5362  return AVERROR_INVALIDDATA;
5363  sc = st->priv_data;
5364  if (sc->ffindex == stream_index && sc->current_sample == sample)
5365  break;
5366  sc->current_sample++;
5367  }
5368  }
5369  return 0;
5370 }
5371 
5372 #define OFFSET(x) offsetof(MOVContext, x)
5373 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5374 static const AVOption mov_options[] = {
5375  {"use_absolute_path",
5376  "allow using absolute path when opening alias, this is a possible security issue",
5377  OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
5378  0, 1, FLAGS},
5379  {"seek_streams_individually",
5380  "Seek each stream individually to the to the closest point",
5381  OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
5382  0, 1, FLAGS},
5383  {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
5384  0, 1, FLAGS},
5385  {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5386  0, 1, FLAGS},
5387  {"use_mfra_for",
5388  "use mfra for fragment timestamps",
5389  OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5391  "use_mfra_for"},
5392  {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5393  FLAGS, "use_mfra_for" },
5394  {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5395  FLAGS, "use_mfra_for" },
5396  {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5397  FLAGS, "use_mfra_for" },
5398  { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5399  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5400  { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5401  AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5402  { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5404  { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5405  "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5406  AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5407  .flags = AV_OPT_FLAG_DECODING_PARAM },
5408  { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5409  { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
5410  {.i64 = 0}, 0, 1, FLAGS },
5411 
5412  { NULL },
5413 };
5414 
5415 static const AVClass mov_class = {
5416  .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5417  .item_name = av_default_item_name,
5418  .option = mov_options,
5419  .version = LIBAVUTIL_VERSION_INT,
5420 };
5421 
5423  .name = "mov,mp4,m4a,3gp,3g2,mj2",
5424  .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5425  .priv_class = &mov_class,
5426  .priv_data_size = sizeof(MOVContext),
5427  .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
5428  .read_probe = mov_probe,
5434 };
int chapter_track
Definition: isom.h:206
static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1489
int itunes_metadata
metadata are itunes style
Definition: isom.h:204
int * bitrates
bitrates read before streams creation
Definition: isom.h:214
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
Definition: pixfmt.h:436
static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1134
void av_sha_final(AVSHA *ctx, uint8_t *digest)
Finish hashing and output digest value.
Definition: sha.c:341
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:4307
int64_t moof_offset
Definition: isom.h:106
#define NULL
Definition: coverity.c:32
#define DRM_BLOB_SIZE
Definition: mov.c:964
const char const char void * val
Definition: avisynth_c.h:634
enum AVFieldOrder field_order
Video only.
Definition: avcodec.h:4003
static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:762
const char * s
Definition: avisynth_c.h:631
static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1259
Bytestream IO Context.
Definition: avio.h:147
enum AVColorTransferCharacteristic color_trc
Definition: avcodec.h:4010
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
enum AVCodecID codec_id
Definition: ffmpeg_vaapi.c:149
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:309
#define MP4ESDescrTag
Definition: isom.h:243
static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:803
#define av_realloc_f(p, o, n)
uint32_t tmcd_flags
tmcd track flags
Definition: isom.h:163
uint8_t * auxiliary_info_end
Definition: isom.h:178
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:166
void ff_mp4_parse_es_descr(AVIOContext *pb, int *es_id)
Definition: isom.c:454
unsigned int elst_count
Definition: isom.h:134
static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3820
AVOption.
Definition: opt.h:245
hash context
Definition: sha.c:34
MOVTrackExt * trex_data
Definition: isom.h:202
int export_all
Definition: isom.h:212
"Linear transfer characteristics"
Definition: pixfmt.h:417
unsigned track_id
Definition: isom.h:81
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:1900
#define MOV_TFHD_DEFAULT_DURATION
Definition: isom.h:250
static AVIndexEntry * mov_find_next_sample(AVFormatContext *s, AVStream **st)
Definition: mov.c:5077
enum AVCodecID id
Definition: mxfenc.c:104
uint32_t format
Definition: isom.h:173
static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:500
static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3226
enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2946
unsigned int samples_per_frame
Definition: isom.h:148
static void mov_build_index(MOVContext *mov, AVStream *st)
Definition: mov.c:2714
int dv_audio_container
Definition: isom.h:149
Definition: isom.h:47
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:247
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:61
uint64_t base_data_offset
Definition: isom.h:82
#define LIBAVUTIL_VERSION_INT
Definition: version.h:70
int64_t duration
Definition: isom.h:59
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1600
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:4427
static void skip_bits_long(GetBitContext *s, int n)
Definition: get_bits.h:204
const char * g
Definition: vf_curves.c:108
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:647
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:816
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:129
int has_palette
Definition: isom.h:161
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 ...
Definition: pixfmt.h:440
static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:115
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3922
static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3100
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:943
int num
numerator
Definition: rational.h:44
int index
stream index in AVFormatContext
Definition: avformat.h:877
unsigned item_count
Definition: isom.h:113
int size
Definition: avcodec.h:1581
const char * b
Definition: vf_curves.c:109
#define MOV_TRUN_SAMPLE_CTS
Definition: isom.h:261
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:230
#define AVIO_FLAG_READ
read-only
Definition: avio.h:606
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:231
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1085
int ignore_chapters
Definition: isom.h:209
static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
Definition: mov.c:4774
void * activation_bytes
Definition: isom.h:226
#define tc
Definition: regdef.h:69
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1614
static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4154
color_range
void * priv_data
Definition: avformat.h:891
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:304
int version
Definition: avisynth_c.h:629
int16_t audio_cid
stsd audio compression id
Definition: isom.h:151
char ** meta_keys
Definition: isom.h:196
#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:784
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:983
static AVPacket pkt
int height
tkhd height
Definition: isom.h:158
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:736
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:87
static AVRational av_make_q(int num, int den)
Create a rational.
Definition: rational.h:53
static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:269
#define sample
uint32_t type
Definition: isom.h:74
static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3947
MOVElst * elst_data
Definition: isom.h:133
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.
MOVStsc * stsc_data
Definition: isom.h:130
#define FF_INPUT_BUFFER_PADDING_SIZE
Definition: avcodec.h:744
enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
Compute codec id for 'lpcm' tag.
Definition: mov.c:1784
unsigned fragment_index_count
Definition: isom.h:220
static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1217
int ctts_index
Definition: isom.h:135
unsigned stsd_id
Definition: isom.h:94
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3914
functionally identical to above
Definition: pixfmt.h:442
int found_moov
'moov' atom has been found
Definition: isom.h:192
static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2358
static void export_orphan_timecode(AVFormatContext *s)
Definition: mov.c:4790
enum AVColorSpace color_space
Definition: avcodec.h:4011
static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1542
#define MOV_TFHD_DEFAULT_BASE_IS_MOOF
Definition: isom.h:254
Macro definitions for various function/variable attributes.
int frame_size
Audio only.
Definition: avcodec.h:4043
static int should_retry(AVIOContext *pb, int error_code)
Definition: mov.c:5103
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function...
Definition: dict.h:73
static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
Definition: mov.c:1398
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:97
#define MOV_TKHD_FLAG_ENABLED
Definition: isom.h:273
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:4189
int isom
1 if file is ISO Media (mp4/3gp)
Definition: isom.h:200
int found_mdat
'mdat' atom has been found
Definition: isom.h:193
int width
tkhd width
Definition: isom.h:157
unsigned drefs_count
Definition: isom.h:152
Format I/O context.
Definition: avformat.h:1325
static int mov_probe(AVProbeData *p)
Definition: mov.c:4507
static int mov_read_header(AVFormatContext *s)
Definition: mov.c:4914
char filename[64]
Definition: isom.h:69
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define AVFMT_FLAG_IGNIDX
Ignore index.
Definition: avformat.h:1438
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 parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
Definition: vp3_parser.c:23
static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition: mov.c:2057
Public dictionary API.
MOVDref * drefs
Definition: isom.h:153
static double cb(void *priv, double x, double y)
Definition: vf_geq.c:97
int fragment_index_complete
Definition: isom.h:221
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:1116
static const AVOption mov_options[]
Definition: mov.c:5374
static int64_t start_time
Definition: ffplay.c:330
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:53
uint8_t
#define FF_MOV_FLAG_MFRA_DTS
Definition: isom.h:302
#define av_malloc(s)
Opaque data information usually continuous.
Definition: avutil.h:195
uint8_t * auxiliary_info
Definition: isom.h:177
int width
Video only.
Definition: avcodec.h:3988
AVOptions.
unsigned int sample_count
Definition: isom.h:139
const AVCodecTag ff_codec_movvideo_tags[]
Definition: isom.c:72
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:751
int count
Definition: isom.h:54
int dts_shift
dts shift when ctts is negative
Definition: isom.h:159
static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:843
#define AVPALETTE_SIZE
Definition: pixfmt.h:32
timecode is drop frame
Definition: timecode.h:36
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1598
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: avcodec.h:1404
uint8_t * auxiliary_info_pos
Definition: isom.h:179
int id
Format-specific stream ID.
Definition: avformat.h:883
enum AVStreamParseType need_parsing
Definition: avformat.h:1074
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5106
AVInputFormat ff_mov_demuxer
Definition: mov.c:5422
unsigned int count
Definition: isom.h:101
static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3840
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
Definition: mov.c:740
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:987
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4065
int16_t nlvl_to
Definition: isom.h:70
#define AV_CH_LOW_FREQUENCY
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_RB32
Definition: bytestream.h:87
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1393
int64_t duration
Definition: movenc.c:63
char volume[28]
Definition: isom.h:68
static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:106
static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:917
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:132
static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb, int codec_tag, int format, int64_t size)
Definition: mov.c:2200
int activation_bytes_size
Definition: isom.h:227
MOVFragmentIndex ** fragment_index_data
Definition: isom.h:219
#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:39
static void finish(void)
Definition: movenc.c:338
#define ALAC_EXTRADATA_SIZE
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1436
DVDemuxContext * avpriv_dv_init_demux(AVFormatContext *s)
Definition: dv.c:324
uint8_t * data
Definition: avcodec.h:1580
#define MOV_TRUN_SAMPLE_SIZE
Definition: isom.h:259
uint32_t tag
Definition: movenc.c:1367
void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)
Definition: utils.c:1942
int nb_frames_for_fps
Definition: isom.h:169
#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
uint8_t * data
Definition: avcodec.h:1524
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:260
struct AVAESCTR * aes_ctr
Definition: isom.h:183
static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:677
ptrdiff_t size
Definition: opengl_enc.c:101
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:818
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:511
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:2989
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
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:1485
uint64_t channel_layout
Audio only.
Definition: avcodec.h:4024
#define av_log(a,...)
int current_sample
Definition: isom.h:146
#define MOV_TFHD_DEFAULT_SIZE
Definition: isom.h:251
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:598
int ff_get_wav_header(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, int size, int big_endian)
Definition: riffdec.c:88
static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4060
unsigned track_id
Definition: isom.h:93
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition: avcodec.h:3951
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1612
void ff_rfps_calculate(AVFormatContext *ic)
Definition: utils.c:3202
int64_t time_offset
time offset of the edit list entries
Definition: isom.h:145
static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3268
unsigned int keyframe_count
Definition: isom.h:142
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:183
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:1364
static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2305
static int mov_rewrite_dvd_sub_extradata(AVStream *st)
Definition: mov.c:2022
#define AVINDEX_KEYFRAME
Definition: avformat.h:823
int ff_mp4_read_dec_config_descr(AVFormatContext *fc, AVStream *st, AVIOContext *pb)
Definition: isom.c:479
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:215
static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size)
Definition: mov.c:1992
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: avcodec.h:189
#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:3446
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1539
unsigned int ctts_count
Definition: isom.h:127
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1999
static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:932
static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3893
AVAudioServiceType
Definition: avcodec.h:787
av_default_item_name
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:720
#define AVERROR(e)
Definition: error.h:43
static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2607
int atom_depth
Definition: isom.h:222
static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1585
static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1590
int64_t timestamp
Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are...
Definition: avformat.h:817
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:176
enum AVColorPrimaries color_primaries
Definition: avcodec.h:4009
int video_delay
Video only.
Definition: avcodec.h:4017
const char * r
Definition: vf_curves.c:107
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
int * keyframes
Definition: isom.h:143
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:515
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3918
AVFormatContext * fc
Definition: isom.h:189
also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
Definition: pixfmt.h:391
static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
Definition: mov.c:3018
static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3591
enum AVPacketSideDataType type
Definition: avcodec.h:1526
#define FFNABS(a)
Negative Absolute value.
Definition: common.h:81
GLsizei GLsizei * length
Definition: opengl_enc.c:115
int handbrake_version
Definition: isom.h:205
int ctts_sample
Definition: isom.h:136
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition: aes.c:31
#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:1130
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
GLsizei count
Definition: opengl_enc.c:109
int keyframe_absent
Definition: isom.h:141
static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3722
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:954
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:432
#define FFMAX(a, b)
Definition: common.h:94
int16_t nlvl_from
Definition: isom.h:70
#define MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES
Definition: isom.h:271
int min_distance
Minimum distance between this and the previous keyframe, used to avoid unneeded searching.
Definition: avformat.h:826
#define fail()
Definition: checkasm.h:81
static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
Definition: mov.c:1156
void * audible_fixed_key
Definition: isom.h:228
const AVCodecTag ff_codec_movsubtitle_tags[]
Definition: isom.c:350
static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:966
#define MIN_DATA_ENTRY_BOX_SIZE
Definition: mov.c:538
static struct tm * gmtime_r(const time_t *clock, struct tm *result)
Definition: time_internal.h:26
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1586
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3940
Only parse headers, do not repack.
Definition: avformat.h:807
int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
Definition: mov.c:2227
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:589
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:3358
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 buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:462
static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4387
int use_subsamples
Definition: isom.h:176
static int aax_filter(uint8_t *input, int size, MOVContext *c)
Definition: mov.c:1065
static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1291
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:461
int64_t time
Definition: isom.h:107
common internal API header
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1381
static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1172
int ff_generate_avci_extradata(AVStream *st)
Generate standard extradata for AVC-Intra based on width/height and field order.
Definition: utils.c:4803
static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
Definition: mov.c:5280
uint8_t file_key[20]
Definition: isom.h:224
static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:72
int block_align
Audio only.
Definition: avcodec.h:4039
static av_const double hypot(double x, double y)
Definition: libm.h:366
struct AVAES * aes_decrypt
Definition: isom.h:230
static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2526
static const uint16_t fc[]
Definition: dcaenc.h:41
uint8_t auxiliary_info_default_size
Definition: isom.h:180
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:243
struct MOVStreamContext::@190 cenc
audio channel layout utility functions
AVRational av_d2q(double d, int max)
Convert a double precision floating point number to a rational.
Definition: rational.c:106
unsigned int avio_rb24(AVIOContext *s)
Definition: aviobuf.c:744
char filename[1024]
input or output filename
Definition: avformat.h:1401
static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3529
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
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:246
#define FFMIN(a, b)
Definition: common.h:96
const AVCodecTag ff_codec_bmp_tags[]
Definition: riff.c:32
static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1079
#define width
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:76
static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3936
colour filters using Illuminant C
Definition: pixfmt.h:399
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
char * dir
Definition: isom.h:67
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:109
static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4101
int id
Definition: isom.h:55
ITU-R BT2020 non-constant luminance system.
Definition: pixfmt.h:444
int decryption_key_len
Definition: isom.h:232
static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1471
#define FLAGS
Definition: mov.c:5373
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:4679
AVFormatContext * ctx
Definition: movenc.c:48
int audible_fixed_key_size
Definition: isom.h:229
static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3462
static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1503
static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3561
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1615
char * path
Definition: isom.h:66
#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:144
int64_t time
Definition: isom.h:89
MOVFragmentIndexItem * items
Definition: isom.h:115
uint64_t moof_offset
Definition: isom.h:83
MOVStts * ctts_data
Definition: isom.h:128
#define OFFSET(x)
Definition: mov.c:5372
#define MOV_TRUN_SAMPLE_DURATION
Definition: isom.h:258
AVDictionary * metadata
Definition: avformat.h:945
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, int size)
Allocate new information from stream.
Definition: utils.c:4954
unsigned size
Definition: isom.h:96
#define AV_CH_FRONT_CENTER
enum AVColorRange color_range
Video only.
Definition: avcodec.h:4008
int ignore_editlist
Definition: isom.h:208
int64_t * chunk_offsets
Definition: isom.h:124
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: mov.c:5156
static int mov_read_close(AVFormatContext *s)
Definition: mov.c:4707
#define src
Definition: vp9dsp.c:530
unsigned int index
Definition: isom.h:102
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:1648
int ff_mov_read_chan(AVFormatContext *s, AVIOContext *pb, AVStream *st, int64_t size)
Read 'chan' tag from the input stream.
Definition: mov_chan.c:547
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:851
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:303
the normal 2^n-1 "JPEG" YUV ranges
Definition: pixfmt.h:457
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:638
#define mc
unsigned current_item
Definition: isom.h:114
size_t auxiliary_info_sizes_count
Definition: isom.h:182
int64_t duration
duration of the longest track
Definition: isom.h:191
int ff_mov_lang_to_iso639(unsigned code, char to[4])
Definition: isom.c:410
Stream structure.
Definition: avformat.h:876
static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
Definition: mov.c:168
#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
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
unsigned duration
Definition: isom.h:95
DVDemuxContext * dv_demux
Definition: isom.h:198
also ITU-R BT1361
Definition: pixfmt.h:410
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:37
int timecode_track
Definition: isom.h:155
int * sample_sizes
Definition: isom.h:140
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_WB16 unsigned int_TMPL AV_RB8
Definition: bytestream.h:87
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
Definition: mov.c:5320
int ff_rfps_add_frame(AVFormatContext *ic, AVStream *st, int64_t dts)
add frame for rfps calculation.
Definition: utils.c:3144
static const uint32_t mac_to_unicode[128]
Definition: mov.c:131
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:829
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:539
#define av_bswap32
Definition: bswap.h:33
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:86
#define MP4DecConfigDescrTag
Definition: isom.h:244
MOVSbgp * rap_group
Definition: isom.h:167
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:295
functionally identical to above
Definition: pixfmt.h:398
int duration
Definition: isom.h:49
static void mov_read_chapters(AVFormatContext *s)
Definition: mov.c:4591
Timecode helpers header.
AVIOContext * pb
I/O context.
Definition: avformat.h:1367
static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:1827
unsigned int stsz_sample_size
always contains sample size from stsz atom
Definition: isom.h:138
static int read_tfra(MOVContext *mov, AVIOContext *f)
Definition: mov.c:4808
static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:767
unsigned trex_count
Definition: isom.h:203
#define MOV_TRUN_FIRST_SAMPLE_FLAGS
Definition: isom.h:257
#define AV_CH_FRONT_LEFT
static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3217
timecode wraps after 24 hours
Definition: timecode.h:37
int enable_drefs
Definition: isom.h:233
struct AVSHA * av_sha_alloc(void)
Allocate an AVSHA context.
Definition: sha.c:45
int64_t data_size
Definition: isom.h:162
static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:4038
int has_looked_for_mfra
Definition: isom.h:218
void * buf
Definition: avisynth_c.h:553
GLint GLenum type
Definition: opengl_enc.c:105
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:69
uint32_t type
Definition: isom.h:65
int nb_index_entries
Definition: avformat.h:1087
MOVStts * stts_data
Definition: isom.h:126
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:292
#define AV_WB32(p, v)
Definition: intreadwrite.h:419
int count
Definition: isom.h:48
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:2958
rational number numerator/denominator
Definition: rational.h:43
unsigned int aax_mode
'aax' file has been detected
Definition: isom.h:223
#define isnan(x)
Definition: libm.h:340
static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1476
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:276
"Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)"
Definition: pixfmt.h:419
MOVFragment fragment
current fragment in moof atom
Definition: isom.h:201
AVFieldOrder
Definition: avcodec.h:1627
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:406
AVRational display_aspect_ratio
display aspect ratio (0 if unknown)
Definition: avformat.h:1220
int64_t track_end
used for dts generation in fragmented movie files
Definition: isom.h:164
Definition: isom.h:73
int use_mfra_for
Definition: isom.h:217
static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:1883
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:150
#define MOV_TFHD_DEFAULT_FLAGS
Definition: isom.h:252
#define snprintf
Definition: snprintf.h:34
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:469
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4001
#define FF_MOV_FLAG_MFRA_AUTO
Definition: isom.h:301
int64_t time
Definition: isom.h:60
int pb_is_copied
Definition: isom.h:120
#define MOV_TRUN_SAMPLE_FLAGS
Definition: isom.h:260
This structure contains the data a format has to probe a file.
Definition: avformat.h:459
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition: get_bits.h:332
#define TAG_IS_AVCI(tag)
Definition: isom.h:278
#define MOV_TFHD_STSD_ID
Definition: isom.h:249
static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2393
AVFormatContext * dv_fctx
Definition: isom.h:199
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:84
static int64_t pts
Global timestamp for the audio frames.
#define SIZE_SPECIFIER
Definition: internal.h:252
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:133
static int flags
Definition: cpu.c:47
static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
Definition: mov.c:2596
static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3344
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:132
uint8_t * auxiliary_info_sizes
Definition: isom.h:181
the normal 219*2^(n-8) "MPEG" YUV ranges
Definition: pixfmt.h:456
int(* parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:66
static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:956
static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key)
Definition: mov.c:92
int ffio_ensure_seekback(AVIOContext *s, int64_t buf_size)
Ensures that the requested seekback buffer size will be available.
Definition: aviobuf.c:924
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:930
int sample_rate
Audio only.
Definition: avcodec.h:4032
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:471
static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1481
int start_pad
amount of samples to skip due to enc-dec delay
Definition: isom.h:165
int trak_index
Index of the current 'trak'.
Definition: isom.h:195
negative time values are allowed
Definition: timecode.h:38
full parsing and repack
Definition: avformat.h:806
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_RB64
Definition: bytestream.h:87
Main libavformat public API header.
int32_t * display_matrix
Definition: isom.h:172
int ff_mp4_read_descr(AVFormatContext *fc, AVIOContext *pb, int *tag)
Definition: isom.c:445
AVIOContext * pb
Definition: isom.h:119
static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
An strf atom is a BITMAPINFOHEADER struct.
Definition: mov.c:1712
unsigned int bytes_per_frame
Definition: isom.h:147
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:80
unsigned flags
Definition: isom.h:88
int bitrates_count
Definition: isom.h:215
int wrong_dts
dts are wrong due to huge ctts offset (iMovie files)
Definition: isom.h:156
if(ret< 0)
Definition: vf_mcdeint.c:282
#define MOV_TFHD_BASE_DATA_OFFSET
Definition: isom.h:248
static int ref[MAX_W *MAX_W]
Definition: jpeg2000dwt.c:107
int64_t size
Definition: isom.h:75
int export_xmp
Definition: isom.h:213
int seek_individually
Definition: isom.h:210
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
void * av_realloc(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:145
int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen)
static const MOVParseTableEntry mov_default_parse_table[]
Definition: mov.c:4306
static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, uint32_t value, int flags)
Definition: mov.c:4665
static double c[64]
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:146
int av_reallocp(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:187
static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:898
unsigned int stps_count
Definition: isom.h:131
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:934
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:3128
unsigned int chunk_count
Definition: isom.h:123
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:208
static int mov_codec_id(AVStream *st, uint32_t format)
Definition: mov.c:1794
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:932
int den
denominator
Definition: rational.h:45
unsigned bps
Definition: movenc.c:1368
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
unsigned meta_keys_count
Definition: isom.h:197
static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
Definition: mov.c:219
#define MKBETAG(a, b, c, d)
Definition: common.h:343
static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1735
uint32_t palette[256]
Definition: isom.h:160
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:731
unsigned stsd_id
Definition: isom.h:85
static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
Definition: mov.c:5255
unsigned int index_entries_allocated_size
Definition: avformat.h:1088
#define av_free(p)
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition: avformat.h:492
static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc)
Definition: mov.c:2123
char * value
Definition: dict.h:87
int eof_reached
true if eof reached
Definition: avio.h:222
static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1466
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:81
as in Berlin toast format
Definition: avcodec.h:532
int len
static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum AVCodecID codec_id)
Definition: mov.c:1435
unsigned int stts_count
Definition: isom.h:125
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:137
static uint8_t tmp[8]
Definition: des.c:38
uint32_t type
Definition: mov.c:65
void * priv_data
Format private data.
Definition: avformat.h:1353
static int mov_read_mfra(MOVContext *c, AVIOContext *f)
Definition: mov.c:4869
uint8_t file_iv[20]
Definition: isom.h:225
static const AVClass mov_class
Definition: mov.c:5415
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition: avcodec.h:3964
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3936
#define MOV_TRUN_DATA_OFFSET
Definition: isom.h:256
int64_t next_root_atom
offset of the next root atom
Definition: isom.h:211
int channels
Audio only.
Definition: avcodec.h:4028
static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
Definition: mov.c:4210
ITU-R BT2020 for 10-bit system.
Definition: pixfmt.h:423
int time_scale
Definition: isom.h:190
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1579
static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1681
Definition: isom.h:58
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
Definition: pixfmt.h:397
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:229
int pseudo_stream_id
-1 means demux all ids
Definition: isom.h:150
#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:1413
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1420
int ffindex
AVStream index.
Definition: isom.h:121
int use_absolute_path
Definition: isom.h:207
#define av_freep(p)
static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:3535
void INT64 start
Definition: avisynth_c.h:553
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:660
static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2316
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:170
AVCodecParameters * codecpar
Definition: avformat.h:1006
unsigned size
Definition: isom.h:87
#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:776
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:328
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: avcodec.h:3926
static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:1461
int64_t duration_for_fps
Definition: isom.h:170
#define AV_CH_SIDE_LEFT
static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2441
static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
Definition: mov.c:4276
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:313
int stream_index
Definition: avcodec.h:1582
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:913
static int unsupported(AVCodecContext *avctx)
Definition: iff.c:1406
unsigned track_id
Definition: isom.h:112
static double cr(void *priv, double x, double y)
Definition: vf_geq.c:98
#define MKTAG(a, b, c, d)
Definition: common.h:342
int moov_retry
Definition: isom.h:216
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:936
static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
Definition: mov.c:3090
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1101
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
Definition: avformat.h:1883
static int mov_switch_root(AVFormatContext *s, int64_t target)
Definition: mov.c:5110
#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
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:87
This structure stores compressed data.
Definition: avcodec.h:1557
static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:2672
#define AES_CTR_IV_SIZE
Definition: aes_ctr.h:31
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:252
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1573
int found_hdlr_mdta
'hdlr' atom with type 'mdta' has been found
Definition: isom.h:194
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition: avformat.h:963
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
GLuint buffer
Definition: opengl_enc.c:102
#define av_unused
Definition: attributes.h:126
Definition: isom.h:64
static uint32_t yuv_to_rgba(uint32_t ycbcr)
Definition: mov.c:2006
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
#define MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC
Definition: isom.h:264
This side data should be associated with an audio stream and corresponds to enum AVAudioServiceType.
Definition: avcodec.h:1416