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