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