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