]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
134953efd93ee5ce3e761a9030a28fb089584de3
[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     char buffer[32];
1160     if (time) {
1161         struct tm *ptm, tmbuf;
1162         time_t timet;
1163         if(time >= 2082844800)
1164             time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
1165         timet = time;
1166         ptm = gmtime_r(&timet, &tmbuf);
1167         if (!ptm) return;
1168         if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
1169             av_dict_set(metadata, "creation_time", buffer, 0);
1170     }
1171 }
1172
1173 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1174 {
1175     AVStream *st;
1176     MOVStreamContext *sc;
1177     int version;
1178     char language[4] = {0};
1179     unsigned lang;
1180     int64_t creation_time;
1181
1182     if (c->fc->nb_streams < 1)
1183         return 0;
1184     st = c->fc->streams[c->fc->nb_streams-1];
1185     sc = st->priv_data;
1186
1187     if (sc->time_scale) {
1188         av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1189         return AVERROR_INVALIDDATA;
1190     }
1191
1192     version = avio_r8(pb);
1193     if (version > 1) {
1194         avpriv_request_sample(c->fc, "Version %d", version);
1195         return AVERROR_PATCHWELCOME;
1196     }
1197     avio_rb24(pb); /* flags */
1198     if (version == 1) {
1199         creation_time = avio_rb64(pb);
1200         avio_rb64(pb);
1201     } else {
1202         creation_time = avio_rb32(pb);
1203         avio_rb32(pb); /* modification time */
1204     }
1205     mov_metadata_creation_time(&st->metadata, creation_time);
1206
1207     sc->time_scale = avio_rb32(pb);
1208     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1209
1210     lang = avio_rb16(pb); /* language */
1211     if (ff_mov_lang_to_iso639(lang, language))
1212         av_dict_set(&st->metadata, "language", language, 0);
1213     avio_rb16(pb); /* quality */
1214
1215     return 0;
1216 }
1217
1218 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1219 {
1220     int64_t creation_time;
1221     int version = avio_r8(pb); /* version */
1222     avio_rb24(pb); /* flags */
1223
1224     if (version == 1) {
1225         creation_time = avio_rb64(pb);
1226         avio_rb64(pb);
1227     } else {
1228         creation_time = avio_rb32(pb);
1229         avio_rb32(pb); /* modification time */
1230     }
1231     mov_metadata_creation_time(&c->fc->metadata, creation_time);
1232     c->time_scale = avio_rb32(pb); /* time scale */
1233
1234     av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1235
1236     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1237     // set the AVCodecContext duration because the duration of individual tracks
1238     // may be inaccurate
1239     if (c->time_scale > 0 && !c->trex_data)
1240         c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1241     avio_rb32(pb); /* preferred scale */
1242
1243     avio_rb16(pb); /* preferred volume */
1244
1245     avio_skip(pb, 10); /* reserved */
1246
1247     avio_skip(pb, 36); /* display matrix */
1248
1249     avio_rb32(pb); /* preview time */
1250     avio_rb32(pb); /* preview duration */
1251     avio_rb32(pb); /* poster time */
1252     avio_rb32(pb); /* selection time */
1253     avio_rb32(pb); /* selection duration */
1254     avio_rb32(pb); /* current time */
1255     avio_rb32(pb); /* next track ID */
1256
1257     return 0;
1258 }
1259
1260 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1261 {
1262     AVStream *st;
1263     int little_endian;
1264
1265     if (c->fc->nb_streams < 1)
1266         return 0;
1267     st = c->fc->streams[c->fc->nb_streams-1];
1268
1269     little_endian = avio_rb16(pb) & 0xFF;
1270     av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1271     if (little_endian == 1) {
1272         switch (st->codecpar->codec_id) {
1273         case AV_CODEC_ID_PCM_S24BE:
1274             st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1275             break;
1276         case AV_CODEC_ID_PCM_S32BE:
1277             st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1278             break;
1279         case AV_CODEC_ID_PCM_F32BE:
1280             st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1281             break;
1282         case AV_CODEC_ID_PCM_F64BE:
1283             st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1284             break;
1285         default:
1286             break;
1287         }
1288     }
1289     return 0;
1290 }
1291
1292 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1293 {
1294     AVStream *st;
1295     char color_parameter_type[5] = { 0 };
1296     uint16_t color_primaries, color_trc, color_matrix;
1297     int ret;
1298
1299     if (c->fc->nb_streams < 1)
1300         return 0;
1301     st = c->fc->streams[c->fc->nb_streams - 1];
1302
1303     ret = ffio_read_size(pb, color_parameter_type, 4);
1304     if (ret < 0)
1305         return ret;
1306     if (strncmp(color_parameter_type, "nclx", 4) &&
1307         strncmp(color_parameter_type, "nclc", 4)) {
1308         av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1309                color_parameter_type);
1310         return 0;
1311     }
1312
1313     color_primaries = avio_rb16(pb);
1314     color_trc = avio_rb16(pb);
1315     color_matrix = avio_rb16(pb);
1316
1317     av_log(c->fc, AV_LOG_TRACE,
1318            "%s: pri %d trc %d matrix %d",
1319            color_parameter_type, color_primaries, color_trc, color_matrix);
1320
1321     if (!strncmp(color_parameter_type, "nclx", 4)) {
1322         uint8_t color_range = avio_r8(pb) >> 7;
1323         av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1324         if (color_range)
1325             st->codecpar->color_range = AVCOL_RANGE_JPEG;
1326         else
1327             st->codecpar->color_range = AVCOL_RANGE_MPEG;
1328         /* 14496-12 references JPEG XR specs (rather than the more complete
1329          * 23001-8) so some adjusting is required */
1330         if (color_primaries >= AVCOL_PRI_FILM)
1331             color_primaries = AVCOL_PRI_UNSPECIFIED;
1332         if ((color_trc >= AVCOL_TRC_LINEAR &&
1333              color_trc <= AVCOL_TRC_LOG_SQRT) ||
1334             color_trc >= AVCOL_TRC_BT2020_10)
1335             color_trc = AVCOL_TRC_UNSPECIFIED;
1336         if (color_matrix >= AVCOL_SPC_BT2020_NCL)
1337             color_matrix = AVCOL_SPC_UNSPECIFIED;
1338         st->codecpar->color_primaries = color_primaries;
1339         st->codecpar->color_trc       = color_trc;
1340         st->codecpar->color_space     = color_matrix;
1341     } else if (!strncmp(color_parameter_type, "nclc", 4)) {
1342         /* color primaries, Table 4-4 */
1343         switch (color_primaries) {
1344         case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
1345         case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
1346         case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
1347         }
1348         /* color transfer, Table 4-5 */
1349         switch (color_trc) {
1350         case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
1351         case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
1352         }
1353         /* color matrix, Table 4-6 */
1354         switch (color_matrix) {
1355         case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
1356         case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
1357         case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
1358         }
1359     }
1360     av_log(c->fc, AV_LOG_TRACE, "\n");
1361
1362     return 0;
1363 }
1364
1365 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1366 {
1367     AVStream *st;
1368     unsigned mov_field_order;
1369     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1370
1371     if (c->fc->nb_streams < 1) // will happen with jp2 files
1372         return 0;
1373     st = c->fc->streams[c->fc->nb_streams-1];
1374     if (atom.size < 2)
1375         return AVERROR_INVALIDDATA;
1376     mov_field_order = avio_rb16(pb);
1377     if ((mov_field_order & 0xFF00) == 0x0100)
1378         decoded_field_order = AV_FIELD_PROGRESSIVE;
1379     else if ((mov_field_order & 0xFF00) == 0x0200) {
1380         switch (mov_field_order & 0xFF) {
1381         case 0x01: decoded_field_order = AV_FIELD_TT;
1382                    break;
1383         case 0x06: decoded_field_order = AV_FIELD_BB;
1384                    break;
1385         case 0x09: decoded_field_order = AV_FIELD_TB;
1386                    break;
1387         case 0x0E: decoded_field_order = AV_FIELD_BT;
1388                    break;
1389         }
1390     }
1391     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1392         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1393     }
1394     st->codecpar->field_order = decoded_field_order;
1395
1396     return 0;
1397 }
1398
1399 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1400 {
1401     int err = 0;
1402     uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1403     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1404         return AVERROR_INVALIDDATA;
1405     if ((err = av_reallocp(&par->extradata, size)) < 0) {
1406         par->extradata_size = 0;
1407         return err;
1408     }
1409     par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1410     return 0;
1411 }
1412
1413 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1414 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1415                                         AVCodecParameters *par, uint8_t *buf)
1416 {
1417     int64_t result = atom.size;
1418     int err;
1419
1420     AV_WB32(buf    , atom.size + 8);
1421     AV_WL32(buf + 4, atom.type);
1422     err = ffio_read_size(pb, buf + 8, atom.size);
1423     if (err < 0) {
1424         par->extradata_size -= atom.size;
1425         return err;
1426     } else if (err < atom.size) {
1427         av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1428         par->extradata_size -= atom.size - err;
1429         result = err;
1430     }
1431     memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1432     return result;
1433 }
1434
1435 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1436 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1437                               enum AVCodecID codec_id)
1438 {
1439     AVStream *st;
1440     uint64_t original_size;
1441     int err;
1442
1443     if (c->fc->nb_streams < 1) // will happen with jp2 files
1444         return 0;
1445     st = c->fc->streams[c->fc->nb_streams-1];
1446
1447     if (st->codecpar->codec_id != codec_id)
1448         return 0; /* unexpected codec_id - don't mess with extradata */
1449
1450     original_size = st->codecpar->extradata_size;
1451     err = mov_realloc_extradata(st->codecpar, atom);
1452     if (err)
1453         return err;
1454
1455     err =  mov_read_atom_into_extradata(c, pb, atom, st->codecpar,  st->codecpar->extradata + original_size);
1456     if (err < 0)
1457         return err;
1458     return 0; // Note: this is the original behavior to ignore truncation.
1459 }
1460
1461 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1462 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1463 {
1464     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1465 }
1466
1467 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1468 {
1469     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1470 }
1471
1472 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1473 {
1474     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1475 }
1476
1477 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1478 {
1479     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1480 }
1481
1482 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1483 {
1484     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1485     if(ret == 0)
1486         ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1487     return ret;
1488 }
1489
1490 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1491 {
1492     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1493
1494     if (!ret && c->fc->nb_streams >= 1) {
1495         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1496         if (par->extradata_size >= 40) {
1497             par->height = AV_RB16(&par->extradata[36]);
1498             par->width  = AV_RB16(&par->extradata[38]);
1499         }
1500     }
1501     return ret;
1502 }
1503
1504 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1505 {
1506     if (c->fc->nb_streams >= 1) {
1507         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1508         if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1509             par->codec_id == AV_CODEC_ID_H264 &&
1510             atom.size > 11) {
1511             int cid;
1512             avio_skip(pb, 10);
1513             cid = avio_rb16(pb);
1514             /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1515             if (cid == 0xd4d || cid == 0xd4e)
1516                 par->width = 1440;
1517             return 0;
1518         } else if (par->codec_tag == MKTAG('A', 'V', 'd', '1') &&
1519                    atom.size >= 24) {
1520             int num, den;
1521             avio_skip(pb, 12);
1522             num = avio_rb32(pb);
1523             den = avio_rb32(pb);
1524             if (num <= 0 || den <= 0)
1525                 return 0;
1526             switch (avio_rb32(pb)) {
1527             case 2:
1528                 if (den >= INT_MAX / 2)
1529                     return 0;
1530                 den *= 2;
1531             case 1:
1532                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1533                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1534             default:
1535                 return 0;
1536             }
1537         }
1538     }
1539
1540     return mov_read_avid(c, pb, atom);
1541 }
1542
1543 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1544 {
1545     int ret = 0;
1546     int length = 0;
1547     uint64_t original_size;
1548     if (c->fc->nb_streams >= 1) {
1549         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1550         if (par->codec_id == AV_CODEC_ID_H264)
1551             return 0;
1552         if (atom.size == 16) {
1553             original_size = par->extradata_size;
1554             ret = mov_realloc_extradata(par, atom);
1555             if (!ret) {
1556                 length =  mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1557                 if (length == atom.size) {
1558                     const uint8_t range_value = par->extradata[original_size + 19];
1559                     switch (range_value) {
1560                     case 1:
1561                         par->color_range = AVCOL_RANGE_MPEG;
1562                         break;
1563                     case 2:
1564                         par->color_range = AVCOL_RANGE_JPEG;
1565                         break;
1566                     default:
1567                         av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1568                         break;
1569                     }
1570                     ff_dlog(c, "color_range: %d\n", par->color_range);
1571                 } else {
1572                   /* For some reason the whole atom was not added to the extradata */
1573                   av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1574                 }
1575             } else {
1576                 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1577             }
1578         } else {
1579             av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1580         }
1581     }
1582
1583     return ret;
1584 }
1585
1586 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1587 {
1588     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1589 }
1590
1591 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1592 {
1593     AVStream *st;
1594     int ret;
1595
1596     if (c->fc->nb_streams < 1)
1597         return 0;
1598     st = c->fc->streams[c->fc->nb_streams-1];
1599
1600     if ((uint64_t)atom.size > (1<<30))
1601         return AVERROR_INVALIDDATA;
1602
1603     if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1604         st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1605         st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1606         // pass all frma atom to codec, needed at least for QDMC and QDM2
1607         av_freep(&st->codecpar->extradata);
1608         ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1609         if (ret < 0)
1610             return ret;
1611     } else if (atom.size > 8) { /* to read frma, esds atoms */
1612         if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1613             uint64_t buffer;
1614             ret = ffio_ensure_seekback(pb, 8);
1615             if (ret < 0)
1616                 return ret;
1617             buffer = avio_rb64(pb);
1618             atom.size -= 8;
1619             if (  (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1620                 && buffer >> 32 <= atom.size
1621                 && buffer >> 32 >= 8) {
1622                 avio_skip(pb, -8);
1623                 atom.size += 8;
1624             } else if (!st->codecpar->extradata_size) {
1625 #define ALAC_EXTRADATA_SIZE 36
1626                 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1627                 if (!st->codecpar->extradata)
1628                     return AVERROR(ENOMEM);
1629                 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1630                 AV_WB32(st->codecpar->extradata    , ALAC_EXTRADATA_SIZE);
1631                 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1632                 AV_WB64(st->codecpar->extradata + 12, buffer);
1633                 avio_read(pb, st->codecpar->extradata + 20, 16);
1634                 avio_skip(pb, atom.size - 24);
1635                 return 0;
1636             }
1637         }
1638         if ((ret = mov_read_default(c, pb, atom)) < 0)
1639             return ret;
1640     } else
1641         avio_skip(pb, atom.size);
1642     return 0;
1643 }
1644
1645 /**
1646  * This function reads atom content and puts data in extradata without tag
1647  * nor size unlike mov_read_extradata.
1648  */
1649 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1650 {
1651     AVStream *st;
1652     int ret;
1653
1654     if (c->fc->nb_streams < 1)
1655         return 0;
1656     st = c->fc->streams[c->fc->nb_streams-1];
1657
1658     if ((uint64_t)atom.size > (1<<30))
1659         return AVERROR_INVALIDDATA;
1660
1661     if (atom.size >= 10) {
1662         // Broken files created by legacy versions of libavformat will
1663         // wrap a whole fiel atom inside of a glbl atom.
1664         unsigned size = avio_rb32(pb);
1665         unsigned type = avio_rl32(pb);
1666         avio_seek(pb, -8, SEEK_CUR);
1667         if (type == MKTAG('f','i','e','l') && size == atom.size)
1668             return mov_read_default(c, pb, atom);
1669     }
1670     if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1671         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1672         return 0;
1673     }
1674     av_freep(&st->codecpar->extradata);
1675     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1676     if (ret < 0)
1677         return ret;
1678
1679     return 0;
1680 }
1681
1682 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1683 {
1684     AVStream *st;
1685     uint8_t profile_level;
1686     int ret;
1687
1688     if (c->fc->nb_streams < 1)
1689         return 0;
1690     st = c->fc->streams[c->fc->nb_streams-1];
1691
1692     if (atom.size >= (1<<28) || atom.size < 7)
1693         return AVERROR_INVALIDDATA;
1694
1695     profile_level = avio_r8(pb);
1696     if ((profile_level & 0xf0) != 0xc0)
1697         return 0;
1698
1699     avio_seek(pb, 6, SEEK_CUR);
1700     av_freep(&st->codecpar->extradata);
1701     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1702     if (ret < 0)
1703         return ret;
1704
1705     return 0;
1706 }
1707
1708 /**
1709  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1710  * but can have extradata appended at the end after the 40 bytes belonging
1711  * to the struct.
1712  */
1713 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1714 {
1715     AVStream *st;
1716     int ret;
1717
1718     if (c->fc->nb_streams < 1)
1719         return 0;
1720     if (atom.size <= 40)
1721         return 0;
1722     st = c->fc->streams[c->fc->nb_streams-1];
1723
1724     if ((uint64_t)atom.size > (1<<30))
1725         return AVERROR_INVALIDDATA;
1726
1727     avio_skip(pb, 40);
1728     av_freep(&st->codecpar->extradata);
1729     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1730     if (ret < 0)
1731         return ret;
1732
1733     return 0;
1734 }
1735
1736 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1737 {
1738     AVStream *st;
1739     MOVStreamContext *sc;
1740     unsigned int i, entries;
1741
1742     if (c->fc->nb_streams < 1)
1743         return 0;
1744     st = c->fc->streams[c->fc->nb_streams-1];
1745     sc = st->priv_data;
1746
1747     avio_r8(pb); /* version */
1748     avio_rb24(pb); /* flags */
1749
1750     entries = avio_rb32(pb);
1751
1752     if (!entries)
1753         return 0;
1754
1755     if (sc->chunk_offsets)
1756         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1757     av_free(sc->chunk_offsets);
1758     sc->chunk_count = 0;
1759     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1760     if (!sc->chunk_offsets)
1761         return AVERROR(ENOMEM);
1762     sc->chunk_count = entries;
1763
1764     if      (atom.type == MKTAG('s','t','c','o'))
1765         for (i = 0; i < entries && !pb->eof_reached; i++)
1766             sc->chunk_offsets[i] = avio_rb32(pb);
1767     else if (atom.type == MKTAG('c','o','6','4'))
1768         for (i = 0; i < entries && !pb->eof_reached; i++)
1769             sc->chunk_offsets[i] = avio_rb64(pb);
1770     else
1771         return AVERROR_INVALIDDATA;
1772
1773     sc->chunk_count = i;
1774
1775     if (pb->eof_reached)
1776         return AVERROR_EOF;
1777
1778     return 0;
1779 }
1780
1781 /**
1782  * Compute codec id for 'lpcm' tag.
1783  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1784  */
1785 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1786 {
1787     /* lpcm flags:
1788      * 0x1 = float
1789      * 0x2 = big-endian
1790      * 0x4 = signed
1791      */
1792     return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1793 }
1794
1795 static int mov_codec_id(AVStream *st, uint32_t format)
1796 {
1797     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1798
1799     if (id <= 0 &&
1800         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1801          (format & 0xFFFF) == 'T' + ('S' << 8)))
1802         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1803
1804     if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1805         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
1806     } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
1807                /* skip old ASF MPEG-4 tag */
1808                format && format != MKTAG('m','p','4','s')) {
1809         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1810         if (id <= 0)
1811             id = ff_codec_get_id(ff_codec_bmp_tags, format);
1812         if (id > 0)
1813             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
1814         else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
1815                     (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1816                     st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
1817             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1818             if (id > 0)
1819                 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
1820         }
1821     }
1822
1823     st->codecpar->codec_tag = format;
1824
1825     return id;
1826 }
1827
1828 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1829                                  AVStream *st, MOVStreamContext *sc)
1830 {
1831     uint8_t codec_name[32];
1832     int64_t stsd_start;
1833     unsigned int len;
1834
1835     /* The first 16 bytes of the video sample description are already
1836      * read in ff_mov_read_stsd_entries() */
1837     stsd_start = avio_tell(pb) - 16;
1838
1839     avio_rb16(pb); /* version */
1840     avio_rb16(pb); /* revision level */
1841     avio_rb32(pb); /* vendor */
1842     avio_rb32(pb); /* temporal quality */
1843     avio_rb32(pb); /* spatial quality */
1844
1845     st->codecpar->width  = avio_rb16(pb); /* width */
1846     st->codecpar->height = avio_rb16(pb); /* height */
1847
1848     avio_rb32(pb); /* horiz resolution */
1849     avio_rb32(pb); /* vert resolution */
1850     avio_rb32(pb); /* data size, always 0 */
1851     avio_rb16(pb); /* frames per samples */
1852
1853     len = avio_r8(pb); /* codec name, pascal string */
1854     if (len > 31)
1855         len = 31;
1856     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1857     if (len < 31)
1858         avio_skip(pb, 31 - len);
1859
1860     if (codec_name[0])
1861         av_dict_set(&st->metadata, "encoder", codec_name, 0);
1862
1863     /* codec_tag YV12 triggers an UV swap in rawdec.c */
1864     if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1865         st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
1866         st->codecpar->width &= ~1;
1867         st->codecpar->height &= ~1;
1868     }
1869     /* Flash Media Server uses tag H.263 with Sorenson Spark */
1870     if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
1871         !memcmp(codec_name, "Sorenson H263", 13))
1872         st->codecpar->codec_id = AV_CODEC_ID_FLV1;
1873
1874     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
1875
1876     avio_seek(pb, stsd_start, SEEK_SET);
1877
1878     if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
1879         st->codecpar->bits_per_coded_sample &= 0x1F;
1880         sc->has_palette = 1;
1881     }
1882 }
1883
1884 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1885                                  AVStream *st, MOVStreamContext *sc)
1886 {
1887     int bits_per_sample, flags;
1888     uint16_t version = avio_rb16(pb);
1889     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1890
1891     avio_rb16(pb); /* revision level */
1892     avio_rb32(pb); /* vendor */
1893
1894     st->codecpar->channels              = avio_rb16(pb); /* channel count */
1895     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1896     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
1897
1898     sc->audio_cid = avio_rb16(pb);
1899     avio_rb16(pb); /* packet size = 0 */
1900
1901     st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
1902
1903     // Read QT version 1 fields. In version 0 these do not exist.
1904     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1905     if (!c->isom ||
1906         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
1907
1908         if (version == 1) {
1909             sc->samples_per_frame = avio_rb32(pb);
1910             avio_rb32(pb); /* bytes per packet */
1911             sc->bytes_per_frame = avio_rb32(pb);
1912             avio_rb32(pb); /* bytes per sample */
1913         } else if (version == 2) {
1914             avio_rb32(pb); /* sizeof struct only */
1915             st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
1916             st->codecpar->channels    = avio_rb32(pb);
1917             avio_rb32(pb); /* always 0x7F000000 */
1918             st->codecpar->bits_per_coded_sample = avio_rb32(pb);
1919
1920             flags = avio_rb32(pb); /* lpcm format specific flag */
1921             sc->bytes_per_frame   = avio_rb32(pb);
1922             sc->samples_per_frame = avio_rb32(pb);
1923             if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
1924                 st->codecpar->codec_id =
1925                     ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
1926                                              flags);
1927         }
1928         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1929             /* can't correctly handle variable sized packet as audio unit */
1930             switch (st->codecpar->codec_id) {
1931             case AV_CODEC_ID_MP2:
1932             case AV_CODEC_ID_MP3:
1933                 st->need_parsing = AVSTREAM_PARSE_FULL;
1934                 break;
1935             }
1936         }
1937     }
1938
1939     if (sc->format == 0) {
1940         if (st->codecpar->bits_per_coded_sample == 8)
1941             st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1942         else if (st->codecpar->bits_per_coded_sample == 16)
1943             st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1944     }
1945
1946     switch (st->codecpar->codec_id) {
1947     case AV_CODEC_ID_PCM_S8:
1948     case AV_CODEC_ID_PCM_U8:
1949         if (st->codecpar->bits_per_coded_sample == 16)
1950             st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
1951         break;
1952     case AV_CODEC_ID_PCM_S16LE:
1953     case AV_CODEC_ID_PCM_S16BE:
1954         if (st->codecpar->bits_per_coded_sample == 8)
1955             st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
1956         else if (st->codecpar->bits_per_coded_sample == 24)
1957             st->codecpar->codec_id =
1958                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1959                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1960         else if (st->codecpar->bits_per_coded_sample == 32)
1961              st->codecpar->codec_id =
1962                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
1963                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1964         break;
1965     /* set values for old format before stsd version 1 appeared */
1966     case AV_CODEC_ID_MACE3:
1967         sc->samples_per_frame = 6;
1968         sc->bytes_per_frame   = 2 * st->codecpar->channels;
1969         break;
1970     case AV_CODEC_ID_MACE6:
1971         sc->samples_per_frame = 6;
1972         sc->bytes_per_frame   = 1 * st->codecpar->channels;
1973         break;
1974     case AV_CODEC_ID_ADPCM_IMA_QT:
1975         sc->samples_per_frame = 64;
1976         sc->bytes_per_frame   = 34 * st->codecpar->channels;
1977         break;
1978     case AV_CODEC_ID_GSM:
1979         sc->samples_per_frame = 160;
1980         sc->bytes_per_frame   = 33;
1981         break;
1982     default:
1983         break;
1984     }
1985
1986     bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
1987     if (bits_per_sample) {
1988         st->codecpar->bits_per_coded_sample = bits_per_sample;
1989         sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
1990     }
1991 }
1992
1993 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1994                                     AVStream *st, MOVStreamContext *sc,
1995                                     int64_t size)
1996 {
1997     // ttxt stsd contains display flags, justification, background
1998     // color, fonts, and default styles, so fake an atom to read it
1999     MOVAtom fake_atom = { .size = size };
2000     // mp4s contains a regular esds atom
2001     if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2002         mov_read_glbl(c, pb, fake_atom);
2003     st->codecpar->width  = sc->width;
2004     st->codecpar->height = sc->height;
2005 }
2006
2007 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2008 {
2009     uint8_t r, g, b;
2010     int y, cb, cr;
2011
2012     y  = (ycbcr >> 16) & 0xFF;
2013     cr = (ycbcr >> 8)  & 0xFF;
2014     cb =  ycbcr        & 0xFF;
2015
2016     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
2017     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
2018     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
2019
2020     return (r << 16) | (g << 8) | b;
2021 }
2022
2023 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2024 {
2025     char buf[256] = {0};
2026     uint8_t *src = st->codecpar->extradata;
2027     int i;
2028
2029     if (st->codecpar->extradata_size != 64)
2030         return 0;
2031
2032     if (st->codecpar->width > 0 &&  st->codecpar->height > 0)
2033         snprintf(buf, sizeof(buf), "size: %dx%d\n",
2034                  st->codecpar->width, st->codecpar->height);
2035     av_strlcat(buf, "palette: ", sizeof(buf));
2036
2037     for (i = 0; i < 16; i++) {
2038         uint32_t yuv = AV_RB32(src + i * 4);
2039         uint32_t rgba = yuv_to_rgba(yuv);
2040
2041         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2042     }
2043
2044     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2045         return 0;
2046
2047     av_freep(&st->codecpar->extradata);
2048     st->codecpar->extradata_size = 0;
2049     st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2050     if (!st->codecpar->extradata)
2051         return AVERROR(ENOMEM);
2052     st->codecpar->extradata_size = strlen(buf);
2053     memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2054
2055     return 0;
2056 }
2057
2058 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2059                                 AVStream *st, MOVStreamContext *sc,
2060                                 int64_t size)
2061 {
2062     int ret;
2063
2064     if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2065         if ((int)size != size)
2066             return AVERROR(ENOMEM);
2067
2068         ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2069         if (ret < 0)
2070             return ret;
2071         if (size > 16) {
2072             MOVStreamContext *tmcd_ctx = st->priv_data;
2073             int val;
2074             val = AV_RB32(st->codecpar->extradata + 4);
2075             tmcd_ctx->tmcd_flags = val;
2076             st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2077             st->avg_frame_rate.den = 1;
2078 #if FF_API_LAVF_AVCTX
2079 FF_DISABLE_DEPRECATION_WARNINGS
2080             st->codec->time_base = av_inv_q(st->avg_frame_rate);
2081 FF_ENABLE_DEPRECATION_WARNINGS
2082 #endif
2083             /* adjust for per frame dur in counter mode */
2084             if (tmcd_ctx->tmcd_flags & 0x0008) {
2085                 int timescale = AV_RB32(st->codecpar->extradata + 8);
2086                 int framedur = AV_RB32(st->codecpar->extradata + 12);
2087                 st->avg_frame_rate.num *= timescale;
2088                 st->avg_frame_rate.den *= framedur;
2089 #if FF_API_LAVF_AVCTX
2090 FF_DISABLE_DEPRECATION_WARNINGS
2091                 st->codec->time_base.den *= timescale;
2092                 st->codec->time_base.num *= framedur;
2093 FF_ENABLE_DEPRECATION_WARNINGS
2094 #endif
2095             }
2096             if (size > 30) {
2097                 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2098                 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2099                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2100                     uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2101                     if (str_size > 0 && size >= (int)str_size + 26) {
2102                         char *reel_name = av_malloc(str_size + 1);
2103                         if (!reel_name)
2104                             return AVERROR(ENOMEM);
2105                         memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2106                         reel_name[str_size] = 0; /* Add null terminator */
2107                         /* don't add reel_name if emtpy string */
2108                         if (*reel_name == 0) {
2109                             av_free(reel_name);
2110                         } else {
2111                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
2112                         }
2113                     }
2114                 }
2115             }
2116         }
2117     } else {
2118         /* other codec type, just skip (rtp, mp4s ...) */
2119         avio_skip(pb, size);
2120     }
2121     return 0;
2122 }
2123
2124 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2125                                    AVStream *st, MOVStreamContext *sc)
2126 {
2127     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2128         !st->codecpar->sample_rate && sc->time_scale > 1)
2129         st->codecpar->sample_rate = sc->time_scale;
2130
2131     /* special codec parameters handling */
2132     switch (st->codecpar->codec_id) {
2133 #if CONFIG_DV_DEMUXER
2134     case AV_CODEC_ID_DVAUDIO:
2135         c->dv_fctx = avformat_alloc_context();
2136         if (!c->dv_fctx) {
2137             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2138             return AVERROR(ENOMEM);
2139         }
2140         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2141         if (!c->dv_demux) {
2142             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2143             return AVERROR(ENOMEM);
2144         }
2145         sc->dv_audio_container = 1;
2146         st->codecpar->codec_id    = AV_CODEC_ID_PCM_S16LE;
2147         break;
2148 #endif
2149     /* no ifdef since parameters are always those */
2150     case AV_CODEC_ID_QCELP:
2151         st->codecpar->channels = 1;
2152         // force sample rate for qcelp when not stored in mov
2153         if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2154             st->codecpar->sample_rate = 8000;
2155         // FIXME: Why is the following needed for some files?
2156         sc->samples_per_frame = 160;
2157         if (!sc->bytes_per_frame)
2158             sc->bytes_per_frame = 35;
2159         break;
2160     case AV_CODEC_ID_AMR_NB:
2161         st->codecpar->channels    = 1;
2162         /* force sample rate for amr, stsd in 3gp does not store sample rate */
2163         st->codecpar->sample_rate = 8000;
2164         break;
2165     case AV_CODEC_ID_AMR_WB:
2166         st->codecpar->channels    = 1;
2167         st->codecpar->sample_rate = 16000;
2168         break;
2169     case AV_CODEC_ID_MP2:
2170     case AV_CODEC_ID_MP3:
2171         /* force type after stsd for m1a hdlr */
2172         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2173         break;
2174     case AV_CODEC_ID_GSM:
2175     case AV_CODEC_ID_ADPCM_MS:
2176     case AV_CODEC_ID_ADPCM_IMA_WAV:
2177     case AV_CODEC_ID_ILBC:
2178     case AV_CODEC_ID_MACE3:
2179     case AV_CODEC_ID_MACE6:
2180     case AV_CODEC_ID_QDM2:
2181         st->codecpar->block_align = sc->bytes_per_frame;
2182         break;
2183     case AV_CODEC_ID_ALAC:
2184         if (st->codecpar->extradata_size == 36) {
2185             st->codecpar->channels    = AV_RB8 (st->codecpar->extradata + 21);
2186             st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2187         }
2188         break;
2189     case AV_CODEC_ID_AC3:
2190     case AV_CODEC_ID_EAC3:
2191     case AV_CODEC_ID_MPEG1VIDEO:
2192     case AV_CODEC_ID_VC1:
2193         st->need_parsing = AVSTREAM_PARSE_FULL;
2194         break;
2195     default:
2196         break;
2197     }
2198     return 0;
2199 }
2200
2201 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2202                                   int codec_tag, int format,
2203                                   int64_t size)
2204 {
2205     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2206
2207     if (codec_tag &&
2208          (codec_tag != format &&
2209           // prores is allowed to have differing data format and codec tag
2210           codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2211           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2212                                  : codec_tag != MKTAG('j','p','e','g')))) {
2213         /* Multiple fourcc, we skip JPEG. This is not correct, we should
2214          * export it as a separate AVStream but this needs a few changes
2215          * in the MOV demuxer, patch welcome. */
2216
2217         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2218         avio_skip(pb, size);
2219         return 1;
2220     }
2221     if ( codec_tag == AV_RL32("hvc1") ||
2222          codec_tag == AV_RL32("hev1")
2223     )
2224         av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2225
2226     return 0;
2227 }
2228
2229 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2230 {
2231     AVStream *st;
2232     MOVStreamContext *sc;
2233     int pseudo_stream_id;
2234
2235     if (c->fc->nb_streams < 1)
2236         return 0;
2237     st = c->fc->streams[c->fc->nb_streams-1];
2238     sc = st->priv_data;
2239
2240     for (pseudo_stream_id = 0;
2241          pseudo_stream_id < entries && !pb->eof_reached;
2242          pseudo_stream_id++) {
2243         //Parsing Sample description table
2244         enum AVCodecID id;
2245         int ret, dref_id = 1;
2246         MOVAtom a = { AV_RL32("stsd") };
2247         int64_t start_pos = avio_tell(pb);
2248         int64_t size    = avio_rb32(pb); /* size */
2249         uint32_t format = avio_rl32(pb); /* data format */
2250
2251         if (size >= 16) {
2252             avio_rb32(pb); /* reserved */
2253             avio_rb16(pb); /* reserved */
2254             dref_id = avio_rb16(pb);
2255         } else if (size <= 7) {
2256             av_log(c->fc, AV_LOG_ERROR,
2257                    "invalid size %"PRId64" in stsd\n", size);
2258             return AVERROR_INVALIDDATA;
2259         }
2260
2261         if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2262                                    size - (avio_tell(pb) - start_pos)))
2263             continue;
2264
2265         sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2266         sc->dref_id= dref_id;
2267         sc->format = format;
2268
2269         id = mov_codec_id(st, format);
2270
2271         av_log(c->fc, AV_LOG_TRACE,
2272                "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2273                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2274                 (format >> 24) & 0xff, format, st->codecpar->codec_type);
2275
2276         if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2277             st->codecpar->codec_id = id;
2278             mov_parse_stsd_video(c, pb, st, sc);
2279         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2280             st->codecpar->codec_id = id;
2281             mov_parse_stsd_audio(c, pb, st, sc);
2282         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2283             st->codecpar->codec_id = id;
2284             mov_parse_stsd_subtitle(c, pb, st, sc,
2285                                     size - (avio_tell(pb) - start_pos));
2286         } else {
2287             ret = mov_parse_stsd_data(c, pb, st, sc,
2288                                       size - (avio_tell(pb) - start_pos));
2289             if (ret < 0)
2290                 return ret;
2291         }
2292         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2293         a.size = size - (avio_tell(pb) - start_pos);
2294         if (a.size > 8) {
2295             if ((ret = mov_read_default(c, pb, a)) < 0)
2296                 return ret;
2297         } else if (a.size > 0)
2298             avio_skip(pb, a.size);
2299
2300         if (sc->extradata) {
2301             int extra_size = st->codecpar->extradata_size;
2302
2303             /* Move the current stream extradata to the stream context one. */
2304             sc->extradata_size[pseudo_stream_id] = extra_size;
2305             sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2306             if (!sc->extradata[pseudo_stream_id])
2307                 return AVERROR(ENOMEM);
2308             memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2309             av_freep(&st->codecpar->extradata);
2310             st->codecpar->extradata_size = 0;
2311         }
2312     }
2313
2314     if (pb->eof_reached)
2315         return AVERROR_EOF;
2316
2317     return mov_finalize_stsd_codec(c, pb, st, sc);
2318 }
2319
2320 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2321 {
2322     AVStream *st;
2323     MOVStreamContext *sc;
2324     int ret;
2325
2326     if (c->fc->nb_streams < 1)
2327         return 0;
2328     st = c->fc->streams[c->fc->nb_streams - 1];
2329     sc = st->priv_data;
2330
2331     avio_r8(pb); /* version */
2332     avio_rb24(pb); /* flags */
2333     sc->stsd_count = avio_rb32(pb); /* entries */
2334
2335     /* Prepare space for hosting multiple extradata. */
2336     sc->extradata = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata));
2337     if (!sc->extradata)
2338         return AVERROR(ENOMEM);
2339
2340     sc->extradata_size = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata_size));
2341     if (!sc->extradata_size)
2342         return AVERROR(ENOMEM);
2343
2344     ret = ff_mov_read_stsd_entries(c, pb, sc->stsd_count);
2345     if (ret < 0)
2346         return ret;
2347
2348     /* Restore back the primary extradata. */
2349     av_freep(&st->codecpar->extradata);
2350     st->codecpar->extradata_size = sc->extradata_size[0];
2351     if (sc->extradata_size[0]) {
2352         st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2353         if (!st->codecpar->extradata)
2354             return AVERROR(ENOMEM);
2355         memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2356     }
2357
2358     return 0;
2359 }
2360
2361 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2362 {
2363     AVStream *st;
2364     MOVStreamContext *sc;
2365     unsigned int i, entries;
2366
2367     if (c->fc->nb_streams < 1)
2368         return 0;
2369     st = c->fc->streams[c->fc->nb_streams-1];
2370     sc = st->priv_data;
2371
2372     avio_r8(pb); /* version */
2373     avio_rb24(pb); /* flags */
2374
2375     entries = avio_rb32(pb);
2376
2377     av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2378
2379     if (!entries)
2380         return 0;
2381     if (sc->stsc_data)
2382         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2383     av_free(sc->stsc_data);
2384     sc->stsc_count = 0;
2385     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2386     if (!sc->stsc_data)
2387         return AVERROR(ENOMEM);
2388
2389     for (i = 0; i < entries && !pb->eof_reached; i++) {
2390         sc->stsc_data[i].first = avio_rb32(pb);
2391         sc->stsc_data[i].count = avio_rb32(pb);
2392         sc->stsc_data[i].id = avio_rb32(pb);
2393     }
2394
2395     sc->stsc_count = i;
2396
2397     if (pb->eof_reached)
2398         return AVERROR_EOF;
2399
2400     return 0;
2401 }
2402
2403 /* Compute the samples value for the stsc entry at the given index. */
2404 static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
2405 {
2406     int chunk_count;
2407
2408     if (index < sc->stsc_count - 1)
2409         chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2410     else
2411         chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2412
2413     return sc->stsc_data[index].count * chunk_count;
2414 }
2415
2416 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2417 {
2418     AVStream *st;
2419     MOVStreamContext *sc;
2420     unsigned i, entries;
2421
2422     if (c->fc->nb_streams < 1)
2423         return 0;
2424     st = c->fc->streams[c->fc->nb_streams-1];
2425     sc = st->priv_data;
2426
2427     avio_rb32(pb); // version + flags
2428
2429     entries = avio_rb32(pb);
2430     if (sc->stps_data)
2431         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2432     av_free(sc->stps_data);
2433     sc->stps_count = 0;
2434     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2435     if (!sc->stps_data)
2436         return AVERROR(ENOMEM);
2437
2438     for (i = 0; i < entries && !pb->eof_reached; i++) {
2439         sc->stps_data[i] = avio_rb32(pb);
2440         //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2441     }
2442
2443     sc->stps_count = i;
2444
2445     if (pb->eof_reached)
2446         return AVERROR_EOF;
2447
2448     return 0;
2449 }
2450
2451 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2452 {
2453     AVStream *st;
2454     MOVStreamContext *sc;
2455     unsigned int i, entries;
2456
2457     if (c->fc->nb_streams < 1)
2458         return 0;
2459     st = c->fc->streams[c->fc->nb_streams-1];
2460     sc = st->priv_data;
2461
2462     avio_r8(pb); /* version */
2463     avio_rb24(pb); /* flags */
2464
2465     entries = avio_rb32(pb);
2466
2467     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2468
2469     if (!entries)
2470     {
2471         sc->keyframe_absent = 1;
2472         if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2473             st->need_parsing = AVSTREAM_PARSE_HEADERS;
2474         return 0;
2475     }
2476     if (sc->keyframes)
2477         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2478     if (entries >= UINT_MAX / sizeof(int))
2479         return AVERROR_INVALIDDATA;
2480     av_freep(&sc->keyframes);
2481     sc->keyframe_count = 0;
2482     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2483     if (!sc->keyframes)
2484         return AVERROR(ENOMEM);
2485
2486     for (i = 0; i < entries && !pb->eof_reached; i++) {
2487         sc->keyframes[i] = avio_rb32(pb);
2488         //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2489     }
2490
2491     sc->keyframe_count = i;
2492
2493     if (pb->eof_reached)
2494         return AVERROR_EOF;
2495
2496     return 0;
2497 }
2498
2499 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2500 {
2501     AVStream *st;
2502     MOVStreamContext *sc;
2503     unsigned int i, entries, sample_size, field_size, num_bytes;
2504     GetBitContext gb;
2505     unsigned char* buf;
2506     int ret;
2507
2508     if (c->fc->nb_streams < 1)
2509         return 0;
2510     st = c->fc->streams[c->fc->nb_streams-1];
2511     sc = st->priv_data;
2512
2513     avio_r8(pb); /* version */
2514     avio_rb24(pb); /* flags */
2515
2516     if (atom.type == MKTAG('s','t','s','z')) {
2517         sample_size = avio_rb32(pb);
2518         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2519             sc->sample_size = sample_size;
2520         sc->stsz_sample_size = sample_size;
2521         field_size = 32;
2522     } else {
2523         sample_size = 0;
2524         avio_rb24(pb); /* reserved */
2525         field_size = avio_r8(pb);
2526     }
2527     entries = avio_rb32(pb);
2528
2529     av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2530
2531     sc->sample_count = entries;
2532     if (sample_size)
2533         return 0;
2534
2535     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2536         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2537         return AVERROR_INVALIDDATA;
2538     }
2539
2540     if (!entries)
2541         return 0;
2542     if (entries >= (UINT_MAX - 4) / field_size)
2543         return AVERROR_INVALIDDATA;
2544     if (sc->sample_sizes)
2545         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2546     av_free(sc->sample_sizes);
2547     sc->sample_count = 0;
2548     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2549     if (!sc->sample_sizes)
2550         return AVERROR(ENOMEM);
2551
2552     num_bytes = (entries*field_size+4)>>3;
2553
2554     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2555     if (!buf) {
2556         av_freep(&sc->sample_sizes);
2557         return AVERROR(ENOMEM);
2558     }
2559
2560     ret = ffio_read_size(pb, buf, num_bytes);
2561     if (ret < 0) {
2562         av_freep(&sc->sample_sizes);
2563         av_free(buf);
2564         return ret;
2565     }
2566
2567     init_get_bits(&gb, buf, 8*num_bytes);
2568
2569     for (i = 0; i < entries && !pb->eof_reached; i++) {
2570         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2571         sc->data_size += sc->sample_sizes[i];
2572     }
2573
2574     sc->sample_count = i;
2575
2576     av_free(buf);
2577
2578     if (pb->eof_reached)
2579         return AVERROR_EOF;
2580
2581     return 0;
2582 }
2583
2584 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2585 {
2586     AVStream *st;
2587     MOVStreamContext *sc;
2588     unsigned int i, entries;
2589     int64_t duration=0;
2590     int64_t total_sample_count=0;
2591
2592     if (c->fc->nb_streams < 1)
2593         return 0;
2594     st = c->fc->streams[c->fc->nb_streams-1];
2595     sc = st->priv_data;
2596
2597     avio_r8(pb); /* version */
2598     avio_rb24(pb); /* flags */
2599     entries = avio_rb32(pb);
2600
2601     av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2602             c->fc->nb_streams-1, entries);
2603
2604     if (sc->stts_data)
2605         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2606     av_free(sc->stts_data);
2607     sc->stts_count = 0;
2608     sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2609     if (!sc->stts_data)
2610         return AVERROR(ENOMEM);
2611
2612     for (i = 0; i < entries && !pb->eof_reached; i++) {
2613         int sample_duration;
2614         int sample_count;
2615
2616         sample_count=avio_rb32(pb);
2617         sample_duration = avio_rb32(pb);
2618
2619         if (sample_count < 0) {
2620             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2621             return AVERROR_INVALIDDATA;
2622         }
2623         sc->stts_data[i].count= sample_count;
2624         sc->stts_data[i].duration= sample_duration;
2625
2626         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2627                 sample_count, sample_duration);
2628
2629         if (   i+1 == entries
2630             && i
2631             && sample_count == 1
2632             && total_sample_count > 100
2633             && sample_duration/10 > duration / total_sample_count)
2634             sample_duration = duration / total_sample_count;
2635         duration+=(int64_t)sample_duration*sample_count;
2636         total_sample_count+=sample_count;
2637     }
2638
2639     sc->stts_count = i;
2640
2641     sc->duration_for_fps  += duration;
2642     sc->nb_frames_for_fps += total_sample_count;
2643
2644     if (pb->eof_reached)
2645         return AVERROR_EOF;
2646
2647     st->nb_frames= total_sample_count;
2648     if (duration)
2649         st->duration= duration;
2650     sc->track_end = duration;
2651     return 0;
2652 }
2653
2654 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2655 {
2656     if (duration < 0) {
2657         if (duration == INT_MIN) {
2658             av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2659             duration++;
2660         }
2661         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2662     }
2663 }
2664
2665 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2666 {
2667     AVStream *st;
2668     MOVStreamContext *sc;
2669     unsigned int i, entries, ctts_count = 0;
2670
2671     if (c->fc->nb_streams < 1)
2672         return 0;
2673     st = c->fc->streams[c->fc->nb_streams-1];
2674     sc = st->priv_data;
2675
2676     avio_r8(pb); /* version */
2677     avio_rb24(pb); /* flags */
2678     entries = avio_rb32(pb);
2679
2680     av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2681
2682     if (!entries)
2683         return 0;
2684     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2685         return AVERROR_INVALIDDATA;
2686     av_freep(&sc->ctts_data);
2687     sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2688     if (!sc->ctts_data)
2689         return AVERROR(ENOMEM);
2690
2691     for (i = 0; i < entries && !pb->eof_reached; i++) {
2692         int count    =avio_rb32(pb);
2693         int duration =avio_rb32(pb);
2694
2695         if (count <= 0) {
2696             av_log(c->fc, AV_LOG_TRACE,
2697                    "ignoring CTTS entry with count=%d duration=%d\n",
2698                    count, duration);
2699             continue;
2700         }
2701
2702         sc->ctts_data[ctts_count].count    = count;
2703         sc->ctts_data[ctts_count].duration = duration;
2704         ctts_count++;
2705
2706         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2707                 count, duration);
2708
2709         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2710             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2711             av_freep(&sc->ctts_data);
2712             sc->ctts_count = 0;
2713             return 0;
2714         }
2715
2716         if (i+2<entries)
2717             mov_update_dts_shift(sc, duration);
2718     }
2719
2720     sc->ctts_count = ctts_count;
2721
2722     if (pb->eof_reached)
2723         return AVERROR_EOF;
2724
2725     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2726
2727     return 0;
2728 }
2729
2730 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2731 {
2732     AVStream *st;
2733     MOVStreamContext *sc;
2734     unsigned int i, entries;
2735     uint8_t version;
2736     uint32_t grouping_type;
2737
2738     if (c->fc->nb_streams < 1)
2739         return 0;
2740     st = c->fc->streams[c->fc->nb_streams-1];
2741     sc = st->priv_data;
2742
2743     version = avio_r8(pb); /* version */
2744     avio_rb24(pb); /* flags */
2745     grouping_type = avio_rl32(pb);
2746     if (grouping_type != MKTAG( 'r','a','p',' '))
2747         return 0; /* only support 'rap ' grouping */
2748     if (version == 1)
2749         avio_rb32(pb); /* grouping_type_parameter */
2750
2751     entries = avio_rb32(pb);
2752     if (!entries)
2753         return 0;
2754     if (sc->rap_group)
2755         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2756     av_free(sc->rap_group);
2757     sc->rap_group_count = 0;
2758     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2759     if (!sc->rap_group)
2760         return AVERROR(ENOMEM);
2761
2762     for (i = 0; i < entries && !pb->eof_reached; i++) {
2763         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2764         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2765     }
2766
2767     sc->rap_group_count = i;
2768
2769     return pb->eof_reached ? AVERROR_EOF : 0;
2770 }
2771
2772 static void mov_build_index(MOVContext *mov, AVStream *st)
2773 {
2774     MOVStreamContext *sc = st->priv_data;
2775     int64_t current_offset;
2776     int64_t current_dts = 0;
2777     unsigned int stts_index = 0;
2778     unsigned int stsc_index = 0;
2779     unsigned int stss_index = 0;
2780     unsigned int stps_index = 0;
2781     unsigned int i, j;
2782     uint64_t stream_size = 0;
2783
2784     if (sc->elst_count) {
2785         int i, edit_start_index = 0, unsupported = 0;
2786         int64_t empty_duration = 0; // empty duration of the first edit list entry
2787         int64_t start_time = 0; // start time of the media
2788
2789         for (i = 0; i < sc->elst_count; i++) {
2790             const MOVElst *e = &sc->elst_data[i];
2791             if (i == 0 && e->time == -1) {
2792                 /* if empty, the first entry is the start time of the stream
2793                  * relative to the presentation itself */
2794                 empty_duration = e->duration;
2795                 edit_start_index = 1;
2796             } else if (i == edit_start_index && e->time >= 0) {
2797                 start_time = e->time;
2798             } else
2799                 unsupported = 1;
2800         }
2801         if (unsupported)
2802             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2803                    "a/v desync might occur, patch welcome\n");
2804
2805         /* adjust first dts according to edit list */
2806         if ((empty_duration || start_time) && mov->time_scale > 0) {
2807             if (empty_duration)
2808                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2809             sc->time_offset = start_time - empty_duration;
2810             current_dts = -sc->time_offset;
2811             if (sc->ctts_count>0 && sc->stts_count>0 &&
2812                 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2813                 /* more than 16 frames delay, dts are likely wrong
2814                    this happens with files created by iMovie */
2815                 sc->wrong_dts = 1;
2816                 st->codecpar->video_delay = 1;
2817             }
2818         }
2819
2820         if (!unsupported && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
2821             sc->start_pad = start_time;
2822     }
2823
2824     /* only use old uncompressed audio chunk demuxing when stts specifies it */
2825     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2826           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2827         unsigned int current_sample = 0;
2828         unsigned int stts_sample = 0;
2829         unsigned int sample_size;
2830         unsigned int distance = 0;
2831         unsigned int rap_group_index = 0;
2832         unsigned int rap_group_sample = 0;
2833         int64_t last_dts = 0;
2834         int64_t dts_correction = 0;
2835         int rap_group_present = sc->rap_group_count && sc->rap_group;
2836         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2837
2838         current_dts -= sc->dts_shift;
2839         last_dts     = current_dts;
2840
2841         if (!sc->sample_count || st->nb_index_entries)
2842             return;
2843         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2844             return;
2845         if (av_reallocp_array(&st->index_entries,
2846                               st->nb_index_entries + sc->sample_count,
2847                               sizeof(*st->index_entries)) < 0) {
2848             st->nb_index_entries = 0;
2849             return;
2850         }
2851         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2852
2853         for (i = 0; i < sc->chunk_count; i++) {
2854             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2855             current_offset = sc->chunk_offsets[i];
2856             while (stsc_index + 1 < sc->stsc_count &&
2857                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2858                 stsc_index++;
2859
2860             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2861                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2862                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2863                 sc->stsz_sample_size = sc->sample_size;
2864             }
2865             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2866                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2867                 sc->stsz_sample_size = sc->sample_size;
2868             }
2869
2870             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2871                 int keyframe = 0;
2872                 if (current_sample >= sc->sample_count) {
2873                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2874                     return;
2875                 }
2876
2877                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2878                     keyframe = 1;
2879                     if (stss_index + 1 < sc->keyframe_count)
2880                         stss_index++;
2881                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2882                     keyframe = 1;
2883                     if (stps_index + 1 < sc->stps_count)
2884                         stps_index++;
2885                 }
2886                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2887                     if (sc->rap_group[rap_group_index].index > 0)
2888                         keyframe = 1;
2889                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2890                         rap_group_sample = 0;
2891                         rap_group_index++;
2892                     }
2893                 }
2894                 if (sc->keyframe_absent
2895                     && !sc->stps_count
2896                     && !rap_group_present
2897                     && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2898                      keyframe = 1;
2899                 if (keyframe)
2900                     distance = 0;
2901                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2902                 if (sc->pseudo_stream_id == -1 ||
2903                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2904                     AVIndexEntry *e;
2905                     if (sample_size > 0x3FFFFFFF) {
2906                         av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
2907                         return;
2908                     }
2909                     e = &st->index_entries[st->nb_index_entries++];
2910                     e->pos = current_offset;
2911                     e->timestamp = current_dts;
2912                     e->size = sample_size;
2913                     e->min_distance = distance;
2914                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2915                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2916                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2917                             current_offset, current_dts, sample_size, distance, keyframe);
2918                     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2919                         ff_rfps_add_frame(mov->fc, st, current_dts);
2920                 }
2921
2922                 current_offset += sample_size;
2923                 stream_size += sample_size;
2924
2925                 /* A negative sample duration is invalid based on the spec,
2926                  * but some samples need it to correct the DTS. */
2927                 if (sc->stts_data[stts_index].duration < 0) {
2928                     av_log(mov->fc, AV_LOG_WARNING,
2929                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2930                            sc->stts_data[stts_index].duration, stts_index,
2931                            st->index);
2932                     dts_correction += sc->stts_data[stts_index].duration - 1;
2933                     sc->stts_data[stts_index].duration = 1;
2934                 }
2935                 current_dts += sc->stts_data[stts_index].duration;
2936                 if (!dts_correction || current_dts + dts_correction > last_dts) {
2937                     current_dts += dts_correction;
2938                     dts_correction = 0;
2939                 } else {
2940                     /* Avoid creating non-monotonous DTS */
2941                     dts_correction += current_dts - last_dts - 1;
2942                     current_dts = last_dts + 1;
2943                 }
2944                 last_dts = current_dts;
2945                 distance++;
2946                 stts_sample++;
2947                 current_sample++;
2948                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2949                     stts_sample = 0;
2950                     stts_index++;
2951                 }
2952             }
2953         }
2954         if (st->duration > 0)
2955             st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2956     } else {
2957         unsigned chunk_samples, total = 0;
2958
2959         // compute total chunk count
2960         for (i = 0; i < sc->stsc_count; i++) {
2961             unsigned count, chunk_count;
2962
2963             chunk_samples = sc->stsc_data[i].count;
2964             if (i != sc->stsc_count - 1 &&
2965                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2966                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2967                 return;
2968             }
2969
2970             if (sc->samples_per_frame >= 160) { // gsm
2971                 count = chunk_samples / sc->samples_per_frame;
2972             } else if (sc->samples_per_frame > 1) {
2973                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2974                 count = (chunk_samples+samples-1) / samples;
2975             } else {
2976                 count = (chunk_samples+1023) / 1024;
2977             }
2978
2979             if (i < sc->stsc_count - 1)
2980                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2981             else
2982                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2983             total += chunk_count * count;
2984         }
2985
2986         av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2987         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2988             return;
2989         if (av_reallocp_array(&st->index_entries,
2990                               st->nb_index_entries + total,
2991                               sizeof(*st->index_entries)) < 0) {
2992             st->nb_index_entries = 0;
2993             return;
2994         }
2995         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2996
2997         // populate index
2998         for (i = 0; i < sc->chunk_count; i++) {
2999             current_offset = sc->chunk_offsets[i];
3000             if (stsc_index + 1 < sc->stsc_count &&
3001                 i + 1 == sc->stsc_data[stsc_index + 1].first)
3002                 stsc_index++;
3003             chunk_samples = sc->stsc_data[stsc_index].count;
3004
3005             while (chunk_samples > 0) {
3006                 AVIndexEntry *e;
3007                 unsigned size, samples;
3008
3009                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3010                     avpriv_request_sample(mov->fc,
3011                            "Zero bytes per frame, but %d samples per frame",
3012                            sc->samples_per_frame);
3013                     return;
3014                 }
3015
3016                 if (sc->samples_per_frame >= 160) { // gsm
3017                     samples = sc->samples_per_frame;
3018                     size = sc->bytes_per_frame;
3019                 } else {
3020                     if (sc->samples_per_frame > 1) {
3021                         samples = FFMIN((1024 / sc->samples_per_frame)*
3022                                         sc->samples_per_frame, chunk_samples);
3023                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3024                     } else {
3025                         samples = FFMIN(1024, chunk_samples);
3026                         size = samples * sc->sample_size;
3027                     }
3028                 }
3029
3030                 if (st->nb_index_entries >= total) {
3031                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
3032                     return;
3033                 }
3034                 if (size > 0x3FFFFFFF) {
3035                     av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3036                     return;
3037                 }
3038                 e = &st->index_entries[st->nb_index_entries++];
3039                 e->pos = current_offset;
3040                 e->timestamp = current_dts;
3041                 e->size = size;
3042                 e->min_distance = 0;
3043                 e->flags = AVINDEX_KEYFRAME;
3044                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
3045                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
3046                         size, samples);
3047
3048                 current_offset += size;
3049                 current_dts += samples;
3050                 chunk_samples -= samples;
3051             }
3052         }
3053     }
3054 }
3055
3056 static int test_same_origin(const char *src, const char *ref) {
3057     char src_proto[64];
3058     char ref_proto[64];
3059     char src_auth[256];
3060     char ref_auth[256];
3061     char src_host[256];
3062     char ref_host[256];
3063     int src_port=-1;
3064     int ref_port=-1;
3065
3066     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3067     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3068
3069     if (strlen(src) == 0) {
3070         return -1;
3071     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3072         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3073         strlen(src_host) + 1 >= sizeof(src_host) ||
3074         strlen(ref_host) + 1 >= sizeof(ref_host)) {
3075         return 0;
3076     } else if (strcmp(src_proto, ref_proto) ||
3077                strcmp(src_auth, ref_auth) ||
3078                strcmp(src_host, ref_host) ||
3079                src_port != ref_port) {
3080         return 0;
3081     } else
3082         return 1;
3083 }
3084
3085 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
3086 {
3087     /* try relative path, we do not try the absolute because it can leak information about our
3088        system to an attacker */
3089     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
3090         char filename[1025];
3091         const char *src_path;
3092         int i, l;
3093
3094         /* find a source dir */
3095         src_path = strrchr(src, '/');
3096         if (src_path)
3097             src_path++;
3098         else
3099             src_path = src;
3100
3101         /* find a next level down to target */
3102         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
3103             if (ref->path[l] == '/') {
3104                 if (i == ref->nlvl_to - 1)
3105                     break;
3106                 else
3107                     i++;
3108             }
3109
3110         /* compose filename if next level down to target was found */
3111         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
3112             memcpy(filename, src, src_path - src);
3113             filename[src_path - src] = 0;
3114
3115             for (i = 1; i < ref->nlvl_from; i++)
3116                 av_strlcat(filename, "../", sizeof(filename));
3117
3118             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
3119             if (!c->use_absolute_path) {
3120                 int same_origin = test_same_origin(src, filename);
3121
3122                 if (!same_origin) {
3123                     av_log(c->fc, AV_LOG_ERROR,
3124                         "Reference with mismatching origin, %s not tried for security reasons, "
3125                         "set demuxer option use_absolute_path to allow it anyway\n",
3126                         ref->path);
3127                     return AVERROR(ENOENT);
3128                 }
3129
3130                 if(strstr(ref->path + l + 1, "..") ||
3131                    strstr(ref->path + l + 1, ":") ||
3132                    (ref->nlvl_from > 1 && same_origin < 0) ||
3133                    (filename[0] == '/' && src_path == src))
3134                     return AVERROR(ENOENT);
3135             }
3136
3137             if (strlen(filename) + 1 == sizeof(filename))
3138                 return AVERROR(ENOENT);
3139             if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3140                 return 0;
3141         }
3142     } else if (c->use_absolute_path) {
3143         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3144                "this is a possible security issue\n");
3145         if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3146             return 0;
3147     } else {
3148         av_log(c->fc, AV_LOG_ERROR,
3149                "Absolute path %s not tried for security reasons, "
3150                "set demuxer option use_absolute_path to allow absolute paths\n",
3151                ref->path);
3152     }
3153
3154     return AVERROR(ENOENT);
3155 }
3156
3157 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3158 {
3159     if (sc->time_scale <= 0) {
3160         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3161         sc->time_scale = c->time_scale;
3162         if (sc->time_scale <= 0)
3163             sc->time_scale = 1;
3164     }
3165 }
3166
3167 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3168 {
3169     AVStream *st;
3170     MOVStreamContext *sc;
3171     int ret;
3172
3173     st = avformat_new_stream(c->fc, NULL);
3174     if (!st) return AVERROR(ENOMEM);
3175     st->id = c->fc->nb_streams;
3176     sc = av_mallocz(sizeof(MOVStreamContext));
3177     if (!sc) return AVERROR(ENOMEM);
3178
3179     st->priv_data = sc;
3180     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3181     sc->ffindex = st->index;
3182     c->trak_index = st->index;
3183
3184     if ((ret = mov_read_default(c, pb, atom)) < 0)
3185         return ret;
3186
3187     c->trak_index = -1;
3188
3189     /* sanity checks */
3190     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3191                             (!sc->sample_size && !sc->sample_count))) {
3192         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3193                st->index);
3194         return 0;
3195     }
3196
3197     fix_timescale(c, sc);
3198
3199     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3200
3201     mov_build_index(c, st);
3202
3203     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3204         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3205         if (c->enable_drefs) {
3206             if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3207                 av_log(c->fc, AV_LOG_ERROR,
3208                        "stream %d, error opening alias: path='%s', dir='%s', "
3209                        "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3210                        st->index, dref->path, dref->dir, dref->filename,
3211                        dref->volume, dref->nlvl_from, dref->nlvl_to);
3212         } else {
3213             av_log(c->fc, AV_LOG_WARNING,
3214                    "Skipped opening external track: "
3215                    "stream %d, alias: path='%s', dir='%s', "
3216                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3217                    "Set enable_drefs to allow this.\n",
3218                    st->index, dref->path, dref->dir, dref->filename,
3219                    dref->volume, dref->nlvl_from, dref->nlvl_to);
3220         }
3221     } else {
3222         sc->pb = c->fc->pb;
3223         sc->pb_is_copied = 1;
3224     }
3225
3226     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3227         if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
3228             sc->height && sc->width &&
3229             (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
3230             st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
3231                                              ((double)st->codecpar->width * sc->height), INT_MAX);
3232         }
3233
3234 #if FF_API_R_FRAME_RATE
3235         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3236             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3237                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3238 #endif
3239     }
3240
3241     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3242     if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3243         TAG_IS_AVCI(st->codecpar->codec_tag)) {
3244         ret = ff_generate_avci_extradata(st);
3245         if (ret < 0)
3246             return ret;
3247     }
3248
3249     switch (st->codecpar->codec_id) {
3250 #if CONFIG_H261_DECODER
3251     case AV_CODEC_ID_H261:
3252 #endif
3253 #if CONFIG_H263_DECODER
3254     case AV_CODEC_ID_H263:
3255 #endif
3256 #if CONFIG_MPEG4_DECODER
3257     case AV_CODEC_ID_MPEG4:
3258 #endif
3259         st->codecpar->width = 0; /* let decoder init width/height */
3260         st->codecpar->height= 0;
3261         break;
3262     }
3263
3264     // If the duration of the mp3 packets is not constant, then they could need a parser
3265     if (st->codecpar->codec_id == AV_CODEC_ID_MP3
3266         && sc->stts_count > 3
3267         && sc->stts_count*10 > st->nb_frames
3268         && sc->time_scale == st->codecpar->sample_rate) {
3269             st->need_parsing = AVSTREAM_PARSE_FULL;
3270     }
3271     /* Do not need those anymore. */
3272     av_freep(&sc->chunk_offsets);
3273     av_freep(&sc->sample_sizes);
3274     av_freep(&sc->keyframes);
3275     av_freep(&sc->stts_data);
3276     av_freep(&sc->stps_data);
3277     av_freep(&sc->elst_data);
3278     av_freep(&sc->rap_group);
3279
3280     return 0;
3281 }
3282
3283 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3284 {
3285     int ret;
3286     c->itunes_metadata = 1;
3287     ret = mov_read_default(c, pb, atom);
3288     c->itunes_metadata = 0;
3289     return ret;
3290 }
3291
3292 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3293 {
3294     uint32_t count;
3295     uint32_t i;
3296
3297     if (atom.size < 8)
3298         return 0;
3299
3300     avio_skip(pb, 4);
3301     count = avio_rb32(pb);
3302     if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3303         av_log(c->fc, AV_LOG_ERROR,
3304                "The 'keys' atom with the invalid key count: %d\n", count);
3305         return AVERROR_INVALIDDATA;
3306     }
3307
3308     c->meta_keys_count = count + 1;
3309     c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3310     if (!c->meta_keys)
3311         return AVERROR(ENOMEM);
3312
3313     for (i = 1; i <= count; ++i) {
3314         uint32_t key_size = avio_rb32(pb);
3315         uint32_t type = avio_rl32(pb);
3316         if (key_size < 8) {
3317             av_log(c->fc, AV_LOG_ERROR,
3318                    "The key# %d in meta has invalid size: %d\n", i, key_size);
3319             return AVERROR_INVALIDDATA;
3320         }
3321         key_size -= 8;
3322         if (type != MKTAG('m','d','t','a')) {
3323             avio_skip(pb, key_size);
3324         }
3325         c->meta_keys[i] = av_mallocz(key_size + 1);
3326         if (!c->meta_keys[i])
3327             return AVERROR(ENOMEM);
3328         avio_read(pb, c->meta_keys[i], key_size);
3329     }
3330
3331     return 0;
3332 }
3333
3334 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3335 {
3336     int64_t end = avio_tell(pb) + atom.size;
3337     uint8_t *key = NULL, *val = NULL, *mean = NULL;
3338     int i;
3339     int ret = 0;
3340     AVStream *st;
3341     MOVStreamContext *sc;
3342
3343     if (c->fc->nb_streams < 1)
3344         return 0;
3345     st = c->fc->streams[c->fc->nb_streams-1];
3346     sc = st->priv_data;
3347
3348     for (i = 0; i < 3; i++) {
3349         uint8_t **p;
3350         uint32_t len, tag;
3351
3352         if (end - avio_tell(pb) <= 12)
3353             break;
3354
3355         len = avio_rb32(pb);
3356         tag = avio_rl32(pb);
3357         avio_skip(pb, 4); // flags
3358
3359         if (len < 12 || len - 12 > end - avio_tell(pb))
3360             break;
3361         len -= 12;
3362
3363         if (tag == MKTAG('m', 'e', 'a', 'n'))
3364             p = &mean;
3365         else if (tag == MKTAG('n', 'a', 'm', 'e'))
3366             p = &key;
3367         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3368             avio_skip(pb, 4);
3369             len -= 4;
3370             p = &val;
3371         } else
3372             break;
3373
3374         *p = av_malloc(len + 1);
3375         if (!*p)
3376             break;
3377         ret = ffio_read_size(pb, *p, len);
3378         if (ret < 0) {
3379             av_freep(p);
3380             break;
3381         }
3382         (*p)[len] = 0;
3383     }
3384
3385     if (mean && key && val) {
3386         if (strcmp(key, "iTunSMPB") == 0) {
3387             int priming, remainder, samples;
3388             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3389                 if(priming>0 && priming<16384)
3390                     sc->start_pad = priming;
3391             }
3392         }
3393         if (strcmp(key, "cdec") != 0) {
3394             av_dict_set(&c->fc->metadata, key, val,
3395                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3396             key = val = NULL;
3397         }
3398     } else {
3399         av_log(c->fc, AV_LOG_VERBOSE,
3400                "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3401     }
3402
3403     avio_seek(pb, end, SEEK_SET);
3404     av_freep(&key);
3405     av_freep(&val);
3406     av_freep(&mean);
3407     return ret;
3408 }
3409
3410 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3411 {
3412     while (atom.size > 8) {
3413         uint32_t tag = avio_rl32(pb);
3414         atom.size -= 4;
3415         if (tag == MKTAG('h','d','l','r')) {
3416             avio_seek(pb, -8, SEEK_CUR);
3417             atom.size += 8;
3418             return mov_read_default(c, pb, atom);
3419         }
3420     }
3421     return 0;
3422 }
3423
3424 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3425 {
3426     int i;
3427     int width;
3428     int height;
3429     int display_matrix[3][3];
3430     AVStream *st;
3431     MOVStreamContext *sc;
3432     int version;
3433     int flags;
3434
3435     if (c->fc->nb_streams < 1)
3436         return 0;
3437     st = c->fc->streams[c->fc->nb_streams-1];
3438     sc = st->priv_data;
3439
3440     version = avio_r8(pb);
3441     flags = avio_rb24(pb);
3442     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3443
3444     if (version == 1) {
3445         avio_rb64(pb);
3446         avio_rb64(pb);
3447     } else {
3448         avio_rb32(pb); /* creation time */
3449         avio_rb32(pb); /* modification time */
3450     }
3451     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3452     avio_rb32(pb); /* reserved */
3453
3454     /* highlevel (considering edits) duration in movie timebase */
3455     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3456     avio_rb32(pb); /* reserved */
3457     avio_rb32(pb); /* reserved */
3458
3459     avio_rb16(pb); /* layer */
3460     avio_rb16(pb); /* alternate group */
3461     avio_rb16(pb); /* volume */
3462     avio_rb16(pb); /* reserved */
3463
3464     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3465     // they're kept in fixed point format through all calculations
3466     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3467     // side data, but the scale factor is not needed to calculate aspect ratio
3468     for (i = 0; i < 3; i++) {
3469         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
3470         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
3471         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
3472     }
3473
3474     width = avio_rb32(pb);       // 16.16 fixed point track width
3475     height = avio_rb32(pb);      // 16.16 fixed point track height
3476     sc->width = width >> 16;
3477     sc->height = height >> 16;
3478
3479     // save the matrix and add rotate metadata when it is not the default
3480     // identity
3481     if (display_matrix[0][0] != (1 << 16) ||
3482         display_matrix[1][1] != (1 << 16) ||
3483         display_matrix[2][2] != (1 << 30) ||
3484         display_matrix[0][1] || display_matrix[0][2] ||
3485         display_matrix[1][0] || display_matrix[1][2] ||
3486         display_matrix[2][0] || display_matrix[2][1]) {
3487         int i, j;
3488         double rotate;
3489
3490         av_freep(&sc->display_matrix);
3491         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3492         if (!sc->display_matrix)
3493             return AVERROR(ENOMEM);
3494
3495         for (i = 0; i < 3; i++)
3496             for (j = 0; j < 3; j++)
3497                 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3498
3499         rotate = av_display_rotation_get(sc->display_matrix);
3500         if (!isnan(rotate)) {
3501             char rotate_buf[64];
3502             rotate = -rotate;
3503             if (rotate < 0) // for backward compatibility
3504                 rotate += 360;
3505             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3506             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3507         }
3508     }
3509
3510     // transform the display width/height according to the matrix
3511     // to keep the same scale, use [width height 1<<16]
3512     if (width && height && sc->display_matrix) {
3513         double disp_transform[2];
3514
3515         for (i = 0; i < 2; i++)
3516             disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3517
3518         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
3519             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3520             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3521             st->sample_aspect_ratio = av_d2q(
3522                 disp_transform[0] / disp_transform[1],
3523                 INT_MAX);
3524     }
3525     return 0;
3526 }
3527
3528 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3529 {
3530     MOVFragment *frag = &c->fragment;
3531     MOVTrackExt *trex = NULL;
3532     MOVFragmentIndex* index = NULL;
3533     int flags, track_id, i, found = 0;
3534
3535     avio_r8(pb); /* version */
3536     flags = avio_rb24(pb);
3537
3538     track_id = avio_rb32(pb);
3539     if (!track_id)
3540         return AVERROR_INVALIDDATA;
3541     frag->track_id = track_id;
3542     for (i = 0; i < c->trex_count; i++)
3543         if (c->trex_data[i].track_id == frag->track_id) {
3544             trex = &c->trex_data[i];
3545             break;
3546         }
3547     if (!trex) {
3548         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3549         return AVERROR_INVALIDDATA;
3550     }
3551
3552     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3553                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3554                              frag->moof_offset : frag->implicit_offset;
3555     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3556
3557     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3558                      avio_rb32(pb) : trex->duration;
3559     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
3560                      avio_rb32(pb) : trex->size;
3561     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
3562                      avio_rb32(pb) : trex->flags;
3563     frag->time     = AV_NOPTS_VALUE;
3564     for (i = 0; i < c->fragment_index_count; i++) {
3565         int j;
3566         MOVFragmentIndex* candidate = c->fragment_index_data[i];
3567         if (candidate->track_id == frag->track_id) {
3568             av_log(c->fc, AV_LOG_DEBUG,
3569                    "found fragment index for track %u\n", frag->track_id);
3570             index = candidate;
3571             for (j = index->current_item; j < index->item_count; j++) {
3572                 if (frag->implicit_offset == index->items[j].moof_offset) {
3573                     av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3574                             "for track %u and moof_offset %"PRId64"\n",
3575                             frag->track_id, index->items[j].moof_offset);
3576                     frag->time = index->items[j].time;
3577                     index->current_item = j + 1;
3578                     found = 1;
3579                     break;
3580                 }
3581             }
3582             if (found)
3583                 break;
3584         }
3585     }
3586     if (index && !found) {
3587         av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3588                "it doesn't have an (in-order) entry for moof_offset "
3589                "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3590     }
3591     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3592     return 0;
3593 }
3594
3595 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3596 {
3597     c->chapter_track = avio_rb32(pb);
3598     return 0;
3599 }
3600
3601 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3602 {
3603     MOVTrackExt *trex;
3604     int err;
3605
3606     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3607         return AVERROR_INVALIDDATA;
3608     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3609                                  sizeof(*c->trex_data))) < 0) {
3610         c->trex_count = 0;
3611         return err;
3612     }
3613
3614     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3615
3616     trex = &c->trex_data[c->trex_count++];
3617     avio_r8(pb); /* version */
3618     avio_rb24(pb); /* flags */
3619     trex->track_id = avio_rb32(pb);
3620     trex->stsd_id  = avio_rb32(pb);
3621     trex->duration = avio_rb32(pb);
3622     trex->size     = avio_rb32(pb);
3623     trex->flags    = avio_rb32(pb);
3624     return 0;
3625 }
3626
3627 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3628 {
3629     MOVFragment *frag = &c->fragment;
3630     AVStream *st = NULL;
3631     MOVStreamContext *sc;
3632     int version, i;
3633
3634     for (i = 0; i < c->fc->nb_streams; i++) {
3635         if (c->fc->streams[i]->id == frag->track_id) {
3636             st = c->fc->streams[i];
3637             break;
3638         }
3639     }
3640     if (!st) {
3641         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3642         return AVERROR_INVALIDDATA;
3643     }
3644     sc = st->priv_data;
3645     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3646         return 0;
3647     version = avio_r8(pb);
3648     avio_rb24(pb); /* flags */
3649     if (version) {
3650         sc->track_end = avio_rb64(pb);
3651     } else {
3652         sc->track_end = avio_rb32(pb);
3653     }
3654     return 0;
3655 }
3656
3657 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3658 {
3659     MOVFragment *frag = &c->fragment;
3660     AVStream *st = NULL;
3661     MOVStreamContext *sc;
3662     MOVStts *ctts_data;
3663     uint64_t offset;
3664     int64_t dts;
3665     int data_offset = 0;
3666     unsigned entries, first_sample_flags = frag->flags;
3667     int flags, distance, i, err;
3668
3669     for (i = 0; i < c->fc->nb_streams; i++) {
3670         if (c->fc->streams[i]->id == frag->track_id) {
3671             st = c->fc->streams[i];
3672             break;
3673         }
3674     }
3675     if (!st) {
3676         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3677         return AVERROR_INVALIDDATA;
3678     }
3679     sc = st->priv_data;
3680     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3681         return 0;
3682     avio_r8(pb); /* version */
3683     flags = avio_rb24(pb);
3684     entries = avio_rb32(pb);
3685     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3686
3687     /* Always assume the presence of composition time offsets.
3688      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3689      *  1) in the initial movie, there are no samples.
3690      *  2) in the first movie fragment, there is only one sample without composition time offset.
3691      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
3692     if (!sc->ctts_count && sc->sample_count)
3693     {
3694         /* Complement ctts table if moov atom doesn't have ctts atom. */
3695         ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3696         if (!ctts_data)
3697             return AVERROR(ENOMEM);
3698         sc->ctts_data = ctts_data;
3699         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3700         sc->ctts_data[sc->ctts_count].duration = 0;
3701         sc->ctts_count++;
3702     }
3703     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3704         return AVERROR_INVALIDDATA;
3705     if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3706                                  sizeof(*sc->ctts_data))) < 0) {
3707         sc->ctts_count = 0;
3708         return err;
3709     }
3710     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
3711     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3712     dts    = sc->track_end - sc->time_offset;
3713     offset = frag->base_data_offset + data_offset;
3714     distance = 0;
3715     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3716     for (i = 0; i < entries && !pb->eof_reached; i++) {
3717         unsigned sample_size = frag->size;
3718         int sample_flags = i ? frag->flags : first_sample_flags;
3719         unsigned sample_duration = frag->duration;
3720         int keyframe = 0;
3721
3722         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3723         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
3724         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
3725         sc->ctts_data[sc->ctts_count].count = 1;
3726         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3727                                                   avio_rb32(pb) : 0;
3728         mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3729         if (frag->time != AV_NOPTS_VALUE) {
3730             if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3731                 int64_t pts = frag->time;
3732                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3733                         " sc->dts_shift %d ctts.duration %d"
3734                         " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3735                         sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3736                         sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3737                 dts = pts - sc->dts_shift;
3738                 if (flags & MOV_TRUN_SAMPLE_CTS) {
3739                     dts -= sc->ctts_data[sc->ctts_count].duration;
3740                 } else {
3741                     dts -= sc->time_offset;
3742                 }
3743                 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3744             } else {
3745                 dts = frag->time - sc->time_offset;
3746                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3747                         ", using it for dts\n", dts);
3748             }
3749             frag->time = AV_NOPTS_VALUE;
3750         }
3751         sc->ctts_count++;
3752         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
3753             keyframe = 1;
3754         else
3755             keyframe =
3756                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3757                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3758         if (keyframe)
3759             distance = 0;
3760         err = av_add_index_entry(st, offset, dts, sample_size, distance,
3761                                  keyframe ? AVINDEX_KEYFRAME : 0);
3762         if (err < 0) {
3763             av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3764         }
3765         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3766                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3767                 offset, dts, sample_size, distance, keyframe);
3768         distance++;
3769         dts += sample_duration;
3770         offset += sample_size;
3771         sc->data_size += sample_size;
3772         sc->duration_for_fps += sample_duration;
3773         sc->nb_frames_for_fps ++;
3774     }
3775
3776     if (pb->eof_reached)
3777         return AVERROR_EOF;
3778
3779     frag->implicit_offset = offset;
3780
3781     sc->track_end = dts + sc->time_offset;
3782     if (st->duration < sc->track_end)
3783         st->duration = sc->track_end;
3784
3785     return 0;
3786 }
3787
3788 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3789 {
3790     int64_t offset = avio_tell(pb) + atom.size, pts;
3791     uint8_t version;
3792     unsigned i, track_id;
3793     AVStream *st = NULL;
3794     MOVStreamContext *sc;
3795     MOVFragmentIndex *index = NULL;
3796     MOVFragmentIndex **tmp;
3797     AVRational timescale;
3798
3799     version = avio_r8(pb);
3800     if (version > 1) {
3801         avpriv_request_sample(c->fc, "sidx version %u", version);
3802         return 0;
3803     }
3804
3805     avio_rb24(pb); // flags
3806
3807     track_id = avio_rb32(pb); // Reference ID
3808     for (i = 0; i < c->fc->nb_streams; i++) {
3809         if (c->fc->streams[i]->id == track_id) {
3810             st = c->fc->streams[i];
3811             break;
3812         }
3813     }
3814     if (!st) {
3815         av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
3816         return 0;
3817     }
3818
3819     sc = st->priv_data;
3820
3821     timescale = av_make_q(1, avio_rb32(pb));
3822
3823     if (version == 0) {
3824         pts = avio_rb32(pb);
3825         offset += avio_rb32(pb);
3826     } else {
3827         pts = avio_rb64(pb);
3828         offset += avio_rb64(pb);
3829     }
3830
3831     avio_rb16(pb); // reserved
3832
3833     index = av_mallocz(sizeof(MOVFragmentIndex));
3834     if (!index)
3835         return AVERROR(ENOMEM);
3836
3837     index->track_id = track_id;
3838
3839     index->item_count = avio_rb16(pb);
3840     index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3841
3842     if (!index->items) {
3843         av_freep(&index);
3844         return AVERROR(ENOMEM);
3845     }
3846
3847     for (i = 0; i < index->item_count; i++) {
3848         uint32_t size = avio_rb32(pb);
3849         uint32_t duration = avio_rb32(pb);
3850         if (size & 0x80000000) {
3851             avpriv_request_sample(c->fc, "sidx reference_type 1");
3852             av_freep(&index->items);
3853             av_freep(&index);
3854             return AVERROR_PATCHWELCOME;
3855         }
3856         avio_rb32(pb); // sap_flags
3857         index->items[i].moof_offset = offset;
3858         index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3859         offset += size;
3860         pts += duration;
3861     }
3862
3863     st->duration = sc->track_end = pts;
3864
3865     tmp = av_realloc_array(c->fragment_index_data,
3866                            c->fragment_index_count + 1,
3867                            sizeof(MOVFragmentIndex*));
3868     if (!tmp) {
3869         av_freep(&index->items);
3870         av_freep(&index);
3871         return AVERROR(ENOMEM);
3872     }
3873
3874     c->fragment_index_data = tmp;
3875     c->fragment_index_data[c->fragment_index_count++] = index;
3876
3877     if (offset == avio_size(pb))
3878         c->fragment_index_complete = 1;
3879
3880     return 0;
3881 }
3882
3883 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3884 /* like the files created with Adobe Premiere 5.0, for samples see */
3885 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3886 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3887 {
3888     int err;
3889
3890     if (atom.size < 8)
3891         return 0; /* continue */
3892     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3893         avio_skip(pb, atom.size - 4);
3894         return 0;
3895     }
3896     atom.type = avio_rl32(pb);
3897     atom.size -= 8;
3898     if (atom.type != MKTAG('m','d','a','t')) {
3899         avio_skip(pb, atom.size);
3900         return 0;
3901     }
3902     err = mov_read_mdat(c, pb, atom);
3903     return err;
3904 }
3905
3906 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3907 {
3908 #if CONFIG_ZLIB
3909     AVIOContext ctx;
3910     uint8_t *cmov_data;
3911     uint8_t *moov_data; /* uncompressed data */
3912     long cmov_len, moov_len;
3913     int ret = -1;
3914
3915     avio_rb32(pb); /* dcom atom */
3916     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3917         return AVERROR_INVALIDDATA;
3918     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3919         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3920         return AVERROR_INVALIDDATA;
3921     }
3922     avio_rb32(pb); /* cmvd atom */
3923     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3924         return AVERROR_INVALIDDATA;
3925     moov_len = avio_rb32(pb); /* uncompressed size */
3926     cmov_len = atom.size - 6 * 4;
3927
3928     cmov_data = av_malloc(cmov_len);
3929     if (!cmov_data)
3930         return AVERROR(ENOMEM);
3931     moov_data = av_malloc(moov_len);
3932     if (!moov_data) {
3933         av_free(cmov_data);
3934         return AVERROR(ENOMEM);
3935     }
3936     ret = ffio_read_size(pb, cmov_data, cmov_len);
3937     if (ret < 0)
3938         goto free_and_return;
3939
3940     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3941         goto free_and_return;
3942     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3943         goto free_and_return;
3944     ctx.seekable = AVIO_SEEKABLE_NORMAL;
3945     atom.type = MKTAG('m','o','o','v');
3946     atom.size = moov_len;
3947     ret = mov_read_default(c, &ctx, atom);
3948 free_and_return:
3949     av_free(moov_data);
3950     av_free(cmov_data);
3951     return ret;
3952 #else
3953     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3954     return AVERROR(ENOSYS);
3955 #endif
3956 }
3957
3958 /* edit list atom */
3959 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3960 {
3961     MOVStreamContext *sc;
3962     int i, edit_count, version;
3963
3964     if (c->fc->nb_streams < 1 || c->ignore_editlist)
3965         return 0;
3966     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3967
3968     version = avio_r8(pb); /* version */
3969     avio_rb24(pb); /* flags */
3970     edit_count = avio_rb32(pb); /* entries */
3971
3972     if (!edit_count)
3973         return 0;
3974     if (sc->elst_data)
3975         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3976     av_free(sc->elst_data);
3977     sc->elst_count = 0;
3978     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3979     if (!sc->elst_data)
3980         return AVERROR(ENOMEM);
3981
3982     av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3983     for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3984         MOVElst *e = &sc->elst_data[i];
3985
3986         if (version == 1) {
3987             e->duration = avio_rb64(pb);
3988             e->time     = avio_rb64(pb);
3989         } else {
3990             e->duration = avio_rb32(pb); /* segment duration */
3991             e->time     = (int32_t)avio_rb32(pb); /* media time */
3992         }
3993         e->rate = avio_rb32(pb) / 65536.0;
3994         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3995                 e->duration, e->time, e->rate);
3996     }
3997     sc->elst_count = i;
3998
3999     return 0;
4000 }
4001
4002 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4003 {
4004     MOVStreamContext *sc;
4005
4006     if (c->fc->nb_streams < 1)
4007         return AVERROR_INVALIDDATA;
4008     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
4009     sc->timecode_track = avio_rb32(pb);
4010     return 0;
4011 }
4012
4013 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4014 {
4015     int ret;
4016     uint8_t uuid[16];
4017     static const uint8_t uuid_isml_manifest[] = {
4018         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
4019         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
4020     };
4021     static const uint8_t uuid_xmp[] = {
4022         0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
4023         0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
4024     };
4025
4026     if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
4027         return AVERROR_INVALIDDATA;
4028
4029     ret = avio_read(pb, uuid, sizeof(uuid));
4030     if (ret < 0) {
4031         return ret;
4032     } else if (ret != sizeof(uuid)) {
4033         return AVERROR_INVALIDDATA;
4034     }
4035     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
4036         uint8_t *buffer, *ptr;
4037         char *endptr;
4038         size_t len = atom.size - sizeof(uuid);
4039
4040         if (len < 4) {
4041             return AVERROR_INVALIDDATA;
4042         }
4043         ret = avio_skip(pb, 4); // zeroes
4044         len -= 4;
4045
4046         buffer = av_mallocz(len + 1);
4047         if (!buffer) {
4048             return AVERROR(ENOMEM);
4049         }
4050         ret = avio_read(pb, buffer, len);
4051         if (ret < 0) {
4052             av_free(buffer);
4053             return ret;
4054         } else if (ret != len) {
4055             av_free(buffer);
4056             return AVERROR_INVALIDDATA;
4057         }
4058
4059         ptr = buffer;
4060         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
4061             ptr += sizeof("systemBitrate=\"") - 1;
4062             c->bitrates_count++;
4063             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
4064             if (!c->bitrates) {
4065                 c->bitrates_count = 0;
4066                 av_free(buffer);
4067                 return AVERROR(ENOMEM);
4068             }
4069             errno = 0;
4070             ret = strtol(ptr, &endptr, 10);
4071             if (ret < 0 || errno || *endptr != '"') {
4072                 c->bitrates[c->bitrates_count - 1] = 0;
4073             } else {
4074                 c->bitrates[c->bitrates_count - 1] = ret;
4075             }
4076         }
4077
4078         av_free(buffer);
4079     } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
4080         uint8_t *buffer;
4081         size_t len = atom.size - sizeof(uuid);
4082
4083         buffer = av_mallocz(len + 1);
4084         if (!buffer) {
4085             return AVERROR(ENOMEM);
4086         }
4087         ret = avio_read(pb, buffer, len);
4088         if (ret < 0) {
4089             av_free(buffer);
4090             return ret;
4091         } else if (ret != len) {
4092             av_free(buffer);
4093             return AVERROR_INVALIDDATA;
4094         }
4095         if (c->export_xmp) {
4096             buffer[len] = '\0';
4097             av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
4098         }
4099         av_free(buffer);
4100     }
4101     return 0;
4102 }
4103
4104 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4105 {
4106     int ret;
4107     uint8_t content[16];
4108
4109     if (atom.size < 8)
4110         return 0;
4111
4112     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
4113     if (ret < 0)
4114         return ret;
4115
4116     if (   !c->found_moov
4117         && !c->found_mdat
4118         && !memcmp(content, "Anevia\x1A\x1A", 8)
4119         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
4120         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
4121     }
4122
4123     return 0;
4124 }
4125
4126 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4127 {
4128     uint32_t format = avio_rl32(pb);
4129     MOVStreamContext *sc;
4130     enum AVCodecID id;
4131     AVStream *st;
4132
4133     if (c->fc->nb_streams < 1)
4134         return 0;
4135     st = c->fc->streams[c->fc->nb_streams - 1];
4136     sc = st->priv_data;
4137
4138     switch (sc->format)
4139     {
4140     case MKTAG('e','n','c','v'):        // encrypted video
4141     case MKTAG('e','n','c','a'):        // encrypted audio
4142         id = mov_codec_id(st, format);
4143         if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
4144             st->codecpar->codec_id != id) {
4145             av_log(c->fc, AV_LOG_WARNING,
4146                    "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
4147                    (char*)&format, st->codecpar->codec_id);
4148             break;
4149         }
4150
4151         st->codecpar->codec_id = id;
4152         sc->format = format;
4153         break;
4154
4155     default:
4156         if (format != sc->format) {
4157             av_log(c->fc, AV_LOG_WARNING,
4158                    "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
4159                    (char*)&format, (char*)&sc->format);
4160         }
4161         break;
4162     }
4163
4164     return 0;
4165 }
4166
4167 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4168 {
4169     AVStream *st;
4170     MOVStreamContext *sc;
4171     size_t auxiliary_info_size;
4172
4173     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4174         return 0;
4175
4176     st = c->fc->streams[c->fc->nb_streams - 1];
4177     sc = st->priv_data;
4178
4179     if (sc->cenc.aes_ctr) {
4180         av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
4181         return AVERROR_INVALIDDATA;
4182     }
4183
4184     avio_r8(pb); /* version */
4185     sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
4186
4187     avio_rb32(pb);        /* entries */
4188
4189     if (atom.size < 8) {
4190         av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
4191         return AVERROR_INVALIDDATA;
4192     }
4193
4194     /* save the auxiliary info as is */
4195     auxiliary_info_size = atom.size - 8;
4196
4197     sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
4198     if (!sc->cenc.auxiliary_info) {
4199         return AVERROR(ENOMEM);
4200     }
4201
4202     sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
4203
4204     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
4205
4206     if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
4207         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
4208         return AVERROR_INVALIDDATA;
4209     }
4210
4211     /* initialize the cipher */
4212     sc->cenc.aes_ctr = av_aes_ctr_alloc();
4213     if (!sc->cenc.aes_ctr) {
4214         return AVERROR(ENOMEM);
4215     }
4216
4217     return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
4218 }
4219
4220 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4221 {
4222     AVStream *st;
4223     MOVStreamContext *sc;
4224     size_t data_size;
4225     int atom_header_size;
4226     int flags;
4227
4228     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4229         return 0;
4230
4231     st = c->fc->streams[c->fc->nb_streams - 1];
4232     sc = st->priv_data;
4233
4234     if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
4235         av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
4236         return AVERROR_INVALIDDATA;
4237     }
4238
4239     atom_header_size = 9;
4240
4241     avio_r8(pb); /* version */
4242     flags = avio_rb24(pb);
4243
4244     if ((flags & 0x01) != 0) {
4245         atom_header_size += 8;
4246
4247         avio_rb32(pb);    /* info type */
4248         avio_rb32(pb);    /* info type param */
4249     }
4250
4251     sc->cenc.auxiliary_info_default_size = avio_r8(pb);
4252     avio_rb32(pb);    /* entries */
4253
4254     if (atom.size <= atom_header_size) {
4255         return 0;
4256     }
4257
4258     /* save the auxiliary info sizes as is */
4259     data_size = atom.size - atom_header_size;
4260
4261     sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
4262     if (!sc->cenc.auxiliary_info_sizes) {
4263         return AVERROR(ENOMEM);
4264     }
4265
4266     sc->cenc.auxiliary_info_sizes_count = data_size;
4267
4268     if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
4269         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
4270         return AVERROR_INVALIDDATA;
4271     }
4272
4273     return 0;
4274 }
4275
4276 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
4277 {
4278     uint32_t encrypted_bytes;
4279     uint16_t subsample_count;
4280     uint16_t clear_bytes;
4281     uint8_t* input_end = input + size;
4282
4283     /* read the iv */
4284     if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4285         av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
4286         return AVERROR_INVALIDDATA;
4287     }
4288
4289     av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
4290     sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
4291
4292     if (!sc->cenc.use_subsamples)
4293     {
4294         /* decrypt the whole packet */
4295         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
4296         return 0;
4297     }
4298
4299     /* read the subsample count */
4300     if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4301         av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
4302         return AVERROR_INVALIDDATA;
4303     }
4304
4305     subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
4306     sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4307
4308     for (; subsample_count > 0; subsample_count--)
4309     {
4310         if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4311             av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
4312             return AVERROR_INVALIDDATA;
4313         }
4314
4315         /* read the number of clear / encrypted bytes */
4316         clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
4317         sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4318         encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
4319         sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
4320
4321         if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
4322             av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
4323             return AVERROR_INVALIDDATA;
4324         }
4325
4326         /* skip the clear bytes */
4327         input += clear_bytes;
4328
4329         /* decrypt the encrypted bytes */
4330         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
4331         input += encrypted_bytes;
4332     }
4333
4334     if (input < input_end) {
4335         av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
4336         return AVERROR_INVALIDDATA;
4337     }
4338
4339     return 0;
4340 }
4341
4342 static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
4343 {
4344     size_t auxiliary_info_seek_offset = 0;
4345     int i;
4346
4347     if (sc->cenc.auxiliary_info_default_size) {
4348         auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * sc->current_sample;
4349     } else if (sc->cenc.auxiliary_info_sizes) {
4350         if (sc->current_sample > sc->cenc.auxiliary_info_sizes_count) {
4351             av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
4352                 sc->current_sample, sc->cenc.auxiliary_info_sizes_count);
4353             return AVERROR_INVALIDDATA;
4354         }
4355
4356         for (i = 0; i < sc->current_sample; i++) {
4357             auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
4358         }
4359     }
4360
4361     if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
4362         av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
4363             auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
4364         return AVERROR_INVALIDDATA;
4365     }
4366
4367     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
4368
4369     return 0;
4370 }
4371
4372 static const MOVParseTableEntry mov_default_parse_table[] = {
4373 { MKTAG('A','C','L','R'), mov_read_aclr },
4374 { MKTAG('A','P','R','G'), mov_read_avid },
4375 { MKTAG('A','A','L','P'), mov_read_avid },
4376 { MKTAG('A','R','E','S'), mov_read_ares },
4377 { MKTAG('a','v','s','s'), mov_read_avss },
4378 { MKTAG('c','h','p','l'), mov_read_chpl },
4379 { MKTAG('c','o','6','4'), mov_read_stco },
4380 { MKTAG('c','o','l','r'), mov_read_colr },
4381 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4382 { MKTAG('d','i','n','f'), mov_read_default },
4383 { MKTAG('D','p','x','E'), mov_read_dpxe },
4384 { MKTAG('d','r','e','f'), mov_read_dref },
4385 { MKTAG('e','d','t','s'), mov_read_default },
4386 { MKTAG('e','l','s','t'), mov_read_elst },
4387 { MKTAG('e','n','d','a'), mov_read_enda },
4388 { MKTAG('f','i','e','l'), mov_read_fiel },
4389 { MKTAG('a','d','r','m'), mov_read_adrm },
4390 { MKTAG('f','t','y','p'), mov_read_ftyp },
4391 { MKTAG('g','l','b','l'), mov_read_glbl },
4392 { MKTAG('h','d','l','r'), mov_read_hdlr },
4393 { MKTAG('i','l','s','t'), mov_read_ilst },
4394 { MKTAG('j','p','2','h'), mov_read_jp2h },
4395 { MKTAG('m','d','a','t'), mov_read_mdat },
4396 { MKTAG('m','d','h','d'), mov_read_mdhd },
4397 { MKTAG('m','d','i','a'), mov_read_default },
4398 { MKTAG('m','e','t','a'), mov_read_meta },
4399 { MKTAG('m','i','n','f'), mov_read_default },
4400 { MKTAG('m','o','o','f'), mov_read_moof },
4401 { MKTAG('m','o','o','v'), mov_read_moov },
4402 { MKTAG('m','v','e','x'), mov_read_default },
4403 { MKTAG('m','v','h','d'), mov_read_mvhd },
4404 { MKTAG('S','M','I',' '), mov_read_svq3 },
4405 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4406 { MKTAG('a','v','c','C'), mov_read_glbl },
4407 { MKTAG('p','a','s','p'), mov_read_pasp },
4408 { MKTAG('s','i','d','x'), mov_read_sidx },
4409 { MKTAG('s','t','b','l'), mov_read_default },
4410 { MKTAG('s','t','c','o'), mov_read_stco },
4411 { MKTAG('s','t','p','s'), mov_read_stps },
4412 { MKTAG('s','t','r','f'), mov_read_strf },
4413 { MKTAG('s','t','s','c'), mov_read_stsc },
4414 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4415 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4416 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4417 { MKTAG('s','t','t','s'), mov_read_stts },
4418 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4419 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4420 { MKTAG('t','f','d','t'), mov_read_tfdt },
4421 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4422 { MKTAG('t','r','a','k'), mov_read_trak },
4423 { MKTAG('t','r','a','f'), mov_read_default },
4424 { MKTAG('t','r','e','f'), mov_read_default },
4425 { MKTAG('t','m','c','d'), mov_read_tmcd },
4426 { MKTAG('c','h','a','p'), mov_read_chap },
4427 { MKTAG('t','r','e','x'), mov_read_trex },
4428 { MKTAG('t','r','u','n'), mov_read_trun },
4429 { MKTAG('u','d','t','a'), mov_read_default },
4430 { MKTAG('w','a','v','e'), mov_read_wave },
4431 { MKTAG('e','s','d','s'), mov_read_esds },
4432 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4433 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4434 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4435 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4436 { MKTAG('w','f','e','x'), mov_read_wfex },
4437 { MKTAG('c','m','o','v'), mov_read_cmov },
4438 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4439 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4440 { MKTAG('s','b','g','p'), mov_read_sbgp },
4441 { MKTAG('h','v','c','C'), mov_read_glbl },
4442 { MKTAG('u','u','i','d'), mov_read_uuid },
4443 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4444 { MKTAG('f','r','e','e'), mov_read_free },
4445 { MKTAG('-','-','-','-'), mov_read_custom },
4446 { MKTAG('s','i','n','f'), mov_read_default },
4447 { MKTAG('f','r','m','a'), mov_read_frma },
4448 { MKTAG('s','e','n','c'), mov_read_senc },
4449 { MKTAG('s','a','i','z'), mov_read_saiz },
4450 { 0, NULL }
4451 };
4452
4453 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4454 {
4455     int64_t total_size = 0;
4456     MOVAtom a;
4457     int i;
4458
4459     if (c->atom_depth > 10) {
4460         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4461         return AVERROR_INVALIDDATA;
4462     }
4463     c->atom_depth ++;
4464
4465     if (atom.size < 0)
4466         atom.size = INT64_MAX;
4467     while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4468         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4469         a.size = atom.size;
4470         a.type=0;
4471         if (atom.size >= 8) {
4472             a.size = avio_rb32(pb);
4473             a.type = avio_rl32(pb);
4474             if (a.type == MKTAG('f','r','e','e') &&
4475                 a.size >= 8 &&
4476                 c->moov_retry) {
4477                 uint8_t buf[8];
4478                 uint32_t *type = (uint32_t *)buf + 1;
4479                 if (avio_read(pb, buf, 8) != 8)
4480                     return AVERROR_INVALIDDATA;
4481                 avio_seek(pb, -8, SEEK_CUR);
4482                 if (*type == MKTAG('m','v','h','d') ||
4483                     *type == MKTAG('c','m','o','v')) {
4484                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4485                     a.type = MKTAG('m','o','o','v');
4486                 }
4487             }
4488             if (atom.type != MKTAG('r','o','o','t') &&
4489                 atom.type != MKTAG('m','o','o','v'))
4490             {
4491                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4492                 {
4493                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4494                     avio_skip(pb, -8);
4495                     c->atom_depth --;
4496                     return 0;
4497                 }
4498             }
4499             total_size += 8;
4500             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4501                 a.size = avio_rb64(pb) - 8;
4502                 total_size += 8;
4503             }
4504         }
4505         av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4506                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4507         if (a.size == 0) {
4508             a.size = atom.size - total_size + 8;
4509         }
4510         a.size -= 8;
4511         if (a.size < 0)
4512             break;
4513         a.size = FFMIN(a.size, atom.size - total_size);
4514
4515         for (i = 0; mov_default_parse_table[i].type; i++)
4516             if (mov_default_parse_table[i].type == a.type) {
4517                 parse = mov_default_parse_table[i].parse;
4518                 break;
4519             }
4520
4521         // container is user data
4522         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4523                        atom.type == MKTAG('i','l','s','t')))
4524             parse = mov_read_udta_string;
4525
4526         // Supports parsing the QuickTime Metadata Keys.
4527         // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4528         if (!parse && c->found_hdlr_mdta &&
4529             atom.type == MKTAG('m','e','t','a') &&
4530             a.type == MKTAG('k','e','y','s')) {
4531             parse = mov_read_keys;
4532         }
4533
4534         if (!parse) { /* skip leaf atoms data */
4535             avio_skip(pb, a.size);
4536         } else {
4537             int64_t start_pos = avio_tell(pb);
4538             int64_t left;
4539             int err = parse(c, pb, a);
4540             if (err < 0) {
4541                 c->atom_depth --;
4542                 return err;
4543             }
4544             if (c->found_moov && c->found_mdat &&
4545                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4546                  start_pos + a.size == avio_size(pb))) {
4547                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4548                     c->next_root_atom = start_pos + a.size;
4549                 c->atom_depth --;
4550                 return 0;
4551             }
4552             left = a.size - avio_tell(pb) + start_pos;
4553             if (left > 0) /* skip garbage at atom end */
4554                 avio_skip(pb, left);
4555             else if (left < 0) {
4556                 av_log(c->fc, AV_LOG_WARNING,
4557                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
4558                        (char*)&a.type, -left);
4559                 avio_seek(pb, left, SEEK_CUR);
4560             }
4561         }
4562
4563         total_size += a.size;
4564     }
4565
4566     if (total_size < atom.size && atom.size < 0x7ffff)
4567         avio_skip(pb, atom.size - total_size);
4568
4569     c->atom_depth --;
4570     return 0;
4571 }
4572
4573 static int mov_probe(AVProbeData *p)
4574 {
4575     int64_t offset;
4576     uint32_t tag;
4577     int score = 0;
4578     int moov_offset = -1;
4579
4580     /* check file header */
4581     offset = 0;
4582     for (;;) {
4583         /* ignore invalid offset */
4584         if ((offset + 8) > (unsigned int)p->buf_size)
4585             break;
4586         tag = AV_RL32(p->buf + offset + 4);
4587         switch(tag) {
4588         /* check for obvious tags */
4589         case MKTAG('m','o','o','v'):
4590             moov_offset = offset + 4;
4591         case MKTAG('m','d','a','t'):
4592         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4593         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4594         case MKTAG('f','t','y','p'):
4595             if (AV_RB32(p->buf+offset) < 8 &&
4596                 (AV_RB32(p->buf+offset) != 1 ||
4597                  offset + 12 > (unsigned int)p->buf_size ||
4598                  AV_RB64(p->buf+offset + 8) == 0)) {
4599                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4600             } else if (tag == MKTAG('f','t','y','p') &&
4601                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4602                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4603                     )) {
4604                 score = FFMAX(score, 5);
4605             } else {
4606                 score = AVPROBE_SCORE_MAX;
4607             }
4608             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4609             break;
4610         /* those are more common words, so rate then a bit less */
4611         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4612         case MKTAG('w','i','d','e'):
4613         case MKTAG('f','r','e','e'):
4614         case MKTAG('j','u','n','k'):
4615         case MKTAG('p','i','c','t'):
4616             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4617             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4618             break;
4619         case MKTAG(0x82,0x82,0x7f,0x7d):
4620         case MKTAG('s','k','i','p'):
4621         case MKTAG('u','u','i','d'):
4622         case MKTAG('p','r','f','l'):
4623             /* if we only find those cause probedata is too small at least rate them */
4624             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4625             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4626             break;
4627         default:
4628             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4629         }
4630     }
4631     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4632         /* moov atom in the header - we should make sure that this is not a
4633          * MOV-packed MPEG-PS */
4634         offset = moov_offset;
4635
4636         while(offset < (p->buf_size - 16)){ /* Sufficient space */
4637                /* We found an actual hdlr atom */
4638             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
4639                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
4640                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4641                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4642                 /* We found a media handler reference atom describing an
4643                  * MPEG-PS-in-MOV, return a
4644                  * low score to force expanding the probe window until
4645                  * mpegps_probe finds what it needs */
4646                 return 5;
4647             }else
4648                 /* Keep looking */
4649                 offset+=2;
4650         }
4651     }
4652
4653     return score;
4654 }
4655
4656 // must be done after parsing all trak because there's no order requirement
4657 static void mov_read_chapters(AVFormatContext *s)
4658 {
4659     MOVContext *mov = s->priv_data;
4660     AVStream *st = NULL;
4661     MOVStreamContext *sc;
4662     int64_t cur_pos;
4663     int i;
4664
4665     for (i = 0; i < s->nb_streams; i++)
4666         if (s->streams[i]->id == mov->chapter_track) {
4667             st = s->streams[i];
4668             break;
4669         }
4670     if (!st) {
4671         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4672         return;
4673     }
4674
4675     st->discard = AVDISCARD_ALL;
4676     sc = st->priv_data;
4677     cur_pos = avio_tell(sc->pb);
4678
4679     for (i = 0; i < st->nb_index_entries; i++) {
4680         AVIndexEntry *sample = &st->index_entries[i];
4681         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4682         uint8_t *title;
4683         uint16_t ch;
4684         int len, title_len;
4685
4686         if (end < sample->timestamp) {
4687             av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4688             end = AV_NOPTS_VALUE;
4689         }
4690
4691         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4692             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4693             goto finish;
4694         }
4695
4696         // the first two bytes are the length of the title
4697         len = avio_rb16(sc->pb);
4698         if (len > sample->size-2)
4699             continue;
4700         title_len = 2*len + 1;
4701         if (!(title = av_mallocz(title_len)))
4702             goto finish;
4703
4704         // The samples could theoretically be in any encoding if there's an encd
4705         // atom following, but in practice are only utf-8 or utf-16, distinguished
4706         // instead by the presence of a BOM
4707         if (!len) {
4708             title[0] = 0;
4709         } else {
4710             ch = avio_rb16(sc->pb);
4711             if (ch == 0xfeff)
4712                 avio_get_str16be(sc->pb, len, title, title_len);
4713             else if (ch == 0xfffe)
4714                 avio_get_str16le(sc->pb, len, title, title_len);
4715             else {
4716                 AV_WB16(title, ch);
4717                 if (len == 1 || len == 2)
4718                     title[len] = 0;
4719                 else
4720                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4721             }
4722         }
4723
4724         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4725         av_freep(&title);
4726     }
4727 finish:
4728     avio_seek(sc->pb, cur_pos, SEEK_SET);
4729 }
4730
4731 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4732                                              uint32_t value, int flags)
4733 {
4734     AVTimecode tc;
4735     char buf[AV_TIMECODE_STR_SIZE];
4736     AVRational rate = st->avg_frame_rate;
4737     int ret = av_timecode_init(&tc, rate, flags, 0, s);
4738     if (ret < 0)
4739         return ret;
4740     av_dict_set(&st->metadata, "timecode",
4741                 av_timecode_make_string(&tc, buf, value), 0);
4742     return 0;
4743 }
4744
4745 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
4746 {
4747     MOVStreamContext *sc = st->priv_data;
4748     char buf[AV_TIMECODE_STR_SIZE];
4749     int64_t cur_pos = avio_tell(sc->pb);
4750     int hh, mm, ss, ff, drop;
4751
4752     if (!st->nb_index_entries)
4753         return -1;
4754
4755     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4756     avio_skip(s->pb, 13);
4757     hh = avio_r8(s->pb);
4758     mm = avio_r8(s->pb);
4759     ss = avio_r8(s->pb);
4760     drop = avio_r8(s->pb);
4761     ff = avio_r8(s->pb);
4762     snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
4763              hh, mm, ss, drop ? ';' : ':', ff);
4764     av_dict_set(&st->metadata, "timecode", buf, 0);
4765
4766     avio_seek(sc->pb, cur_pos, SEEK_SET);
4767     return 0;
4768 }
4769
4770 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4771 {
4772     MOVStreamContext *sc = st->priv_data;
4773     int flags = 0;
4774     int64_t cur_pos = avio_tell(sc->pb);
4775     uint32_t value;
4776
4777     if (!st->nb_index_entries)
4778         return -1;
4779
4780     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4781     value = avio_rb32(s->pb);
4782
4783     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4784     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4785     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4786
4787     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4788      * not the case) and thus assume "frame number format" instead of QT one.
4789      * No sample with tmcd track can be found with a QT timecode at the moment,
4790      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4791      * format). */
4792     parse_timecode_in_framenum_format(s, st, value, flags);
4793
4794     avio_seek(sc->pb, cur_pos, SEEK_SET);
4795     return 0;
4796 }
4797
4798 static int mov_read_close(AVFormatContext *s)
4799 {
4800     MOVContext *mov = s->priv_data;
4801     int i, j;
4802
4803     for (i = 0; i < s->nb_streams; i++) {
4804         AVStream *st = s->streams[i];
4805         MOVStreamContext *sc = st->priv_data;
4806
4807         if (!sc)
4808             continue;
4809
4810         av_freep(&sc->ctts_data);
4811         for (j = 0; j < sc->drefs_count; j++) {
4812             av_freep(&sc->drefs[j].path);
4813             av_freep(&sc->drefs[j].dir);
4814         }
4815         av_freep(&sc->drefs);
4816
4817         sc->drefs_count = 0;
4818
4819         if (!sc->pb_is_copied)
4820             ff_format_io_close(s, &sc->pb);
4821
4822         sc->pb = NULL;
4823         av_freep(&sc->chunk_offsets);
4824         av_freep(&sc->stsc_data);
4825         av_freep(&sc->sample_sizes);
4826         av_freep(&sc->keyframes);
4827         av_freep(&sc->stts_data);
4828         av_freep(&sc->stps_data);
4829         av_freep(&sc->elst_data);
4830         av_freep(&sc->rap_group);
4831         av_freep(&sc->display_matrix);
4832
4833         if (sc->extradata)
4834             for (j = 0; j < sc->stsd_count; j++)
4835                 av_free(sc->extradata[j]);
4836         av_freep(&sc->extradata);
4837         av_freep(&sc->extradata_size);
4838
4839         av_freep(&sc->cenc.auxiliary_info);
4840         av_freep(&sc->cenc.auxiliary_info_sizes);
4841         av_aes_ctr_free(sc->cenc.aes_ctr);
4842     }
4843
4844     if (mov->dv_demux) {
4845         avformat_free_context(mov->dv_fctx);
4846         mov->dv_fctx = NULL;
4847     }
4848
4849     if (mov->meta_keys) {
4850         for (i = 1; i < mov->meta_keys_count; i++) {
4851             av_freep(&mov->meta_keys[i]);
4852         }
4853         av_freep(&mov->meta_keys);
4854     }
4855
4856     av_freep(&mov->trex_data);
4857     av_freep(&mov->bitrates);
4858
4859     for (i = 0; i < mov->fragment_index_count; i++) {
4860         MOVFragmentIndex* index = mov->fragment_index_data[i];
4861         av_freep(&index->items);
4862         av_freep(&mov->fragment_index_data[i]);
4863     }
4864     av_freep(&mov->fragment_index_data);
4865
4866     av_freep(&mov->aes_decrypt);
4867
4868     return 0;
4869 }
4870
4871 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4872 {
4873     int i;
4874
4875     for (i = 0; i < s->nb_streams; i++) {
4876         AVStream *st = s->streams[i];
4877         MOVStreamContext *sc = st->priv_data;
4878
4879         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
4880             sc->timecode_track == tmcd_id)
4881             return 1;
4882     }
4883     return 0;
4884 }
4885
4886 /* look for a tmcd track not referenced by any video track, and export it globally */
4887 static void export_orphan_timecode(AVFormatContext *s)
4888 {
4889     int i;
4890
4891     for (i = 0; i < s->nb_streams; i++) {
4892         AVStream *st = s->streams[i];
4893
4894         if (st->codecpar->codec_tag  == MKTAG('t','m','c','d') &&
4895             !tmcd_is_referenced(s, i + 1)) {
4896             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4897             if (tcr) {
4898                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4899                 break;
4900             }
4901         }
4902     }
4903 }
4904
4905 static int read_tfra(MOVContext *mov, AVIOContext *f)
4906 {
4907     MOVFragmentIndex* index = NULL;
4908     int version, fieldlength, i, j;
4909     int64_t pos = avio_tell(f);
4910     uint32_t size = avio_rb32(f);
4911     void *tmp;
4912
4913     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4914         return 1;
4915     }
4916     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4917     index = av_mallocz(sizeof(MOVFragmentIndex));
4918     if (!index) {
4919         return AVERROR(ENOMEM);
4920     }
4921
4922     tmp = av_realloc_array(mov->fragment_index_data,
4923                            mov->fragment_index_count + 1,
4924                            sizeof(MOVFragmentIndex*));
4925     if (!tmp) {
4926         av_freep(&index);
4927         return AVERROR(ENOMEM);
4928     }
4929     mov->fragment_index_data = tmp;
4930     mov->fragment_index_data[mov->fragment_index_count++] = index;
4931
4932     version = avio_r8(f);
4933     avio_rb24(f);
4934     index->track_id = avio_rb32(f);
4935     fieldlength = avio_rb32(f);
4936     index->item_count = avio_rb32(f);
4937     index->items = av_mallocz_array(
4938             index->item_count, sizeof(MOVFragmentIndexItem));
4939     if (!index->items) {
4940         index->item_count = 0;
4941         return AVERROR(ENOMEM);
4942     }
4943     for (i = 0; i < index->item_count; i++) {
4944         int64_t time, offset;
4945         if (version == 1) {
4946             time   = avio_rb64(f);
4947             offset = avio_rb64(f);
4948         } else {
4949             time   = avio_rb32(f);
4950             offset = avio_rb32(f);
4951         }
4952         index->items[i].time = time;
4953         index->items[i].moof_offset = offset;
4954         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4955             avio_r8(f);
4956         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4957             avio_r8(f);
4958         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4959             avio_r8(f);
4960     }
4961
4962     avio_seek(f, pos + size, SEEK_SET);
4963     return 0;
4964 }
4965
4966 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4967 {
4968     int64_t stream_size = avio_size(f);
4969     int64_t original_pos = avio_tell(f);
4970     int64_t seek_ret;
4971     int32_t mfra_size;
4972     int ret = -1;
4973     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4974         ret = seek_ret;
4975         goto fail;
4976     }
4977     mfra_size = avio_rb32(f);
4978     if (mfra_size < 0 || mfra_size > stream_size) {
4979         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4980         goto fail;
4981     }
4982     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4983         ret = seek_ret;
4984         goto fail;
4985     }
4986     if (avio_rb32(f) != mfra_size) {
4987         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4988         goto fail;
4989     }
4990     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4991         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4992         goto fail;
4993     }
4994     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4995     do {
4996         ret = read_tfra(c, f);
4997         if (ret < 0)
4998             goto fail;
4999     } while (!ret);
5000     ret = 0;
5001 fail:
5002     seek_ret = avio_seek(f, original_pos, SEEK_SET);
5003     if (seek_ret < 0) {
5004         av_log(c->fc, AV_LOG_ERROR,
5005                "failed to seek back after looking for mfra\n");
5006         ret = seek_ret;
5007     }
5008     return ret;
5009 }
5010
5011 static int mov_read_header(AVFormatContext *s)
5012 {
5013     MOVContext *mov = s->priv_data;
5014     AVIOContext *pb = s->pb;
5015     int j, err;
5016     MOVAtom atom = { AV_RL32("root") };
5017     int i;
5018
5019     if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
5020         av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
5021             mov->decryption_key_len, AES_CTR_KEY_SIZE);
5022         return AVERROR(EINVAL);
5023     }
5024
5025     mov->fc = s;
5026     mov->trak_index = -1;
5027     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
5028     if (pb->seekable)
5029         atom.size = avio_size(pb);
5030     else
5031         atom.size = INT64_MAX;
5032
5033     /* check MOV header */
5034     do {
5035     if (mov->moov_retry)
5036         avio_seek(pb, 0, SEEK_SET);
5037     if ((err = mov_read_default(mov, pb, atom)) < 0) {
5038         av_log(s, AV_LOG_ERROR, "error reading header\n");
5039         mov_read_close(s);
5040         return err;
5041     }
5042     } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
5043     if (!mov->found_moov) {
5044         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
5045         mov_read_close(s);
5046         return AVERROR_INVALIDDATA;
5047     }
5048     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
5049
5050     if (pb->seekable) {
5051         if (mov->chapter_track > 0 && !mov->ignore_chapters)
5052             mov_read_chapters(s);
5053         for (i = 0; i < s->nb_streams; i++)
5054             if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
5055                 mov_read_timecode_track(s, s->streams[i]);
5056             } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
5057                 mov_read_rtmd_track(s, s->streams[i]);
5058             }
5059     }
5060
5061     /* copy timecode metadata from tmcd tracks to the related video streams */
5062     for (i = 0; i < s->nb_streams; i++) {
5063         AVStream *st = s->streams[i];
5064         MOVStreamContext *sc = st->priv_data;
5065         if (sc->timecode_track > 0) {
5066             AVDictionaryEntry *tcr;
5067             int tmcd_st_id = -1;
5068
5069             for (j = 0; j < s->nb_streams; j++)
5070                 if (s->streams[j]->id == sc->timecode_track)
5071                     tmcd_st_id = j;
5072
5073             if (tmcd_st_id < 0 || tmcd_st_id == i)
5074                 continue;
5075             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
5076             if (tcr)
5077                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
5078         }
5079     }
5080     export_orphan_timecode(s);
5081
5082     for (i = 0; i < s->nb_streams; i++) {
5083         AVStream *st = s->streams[i];
5084         MOVStreamContext *sc = st->priv_data;
5085         fix_timescale(mov, sc);
5086         if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
5087             st->skip_samples = sc->start_pad;
5088         }
5089         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
5090             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
5091                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
5092         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5093             if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
5094                 st->codecpar->width  = sc->width;
5095                 st->codecpar->height = sc->height;
5096             }
5097             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
5098                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
5099                     return err;
5100             }
5101         }
5102         if (mov->handbrake_version &&
5103             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
5104             st->codecpar->codec_id == AV_CODEC_ID_MP3
5105         ) {
5106             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
5107             st->need_parsing = AVSTREAM_PARSE_FULL;
5108         }
5109     }
5110
5111     if (mov->trex_data) {
5112         for (i = 0; i < s->nb_streams; i++) {
5113             AVStream *st = s->streams[i];
5114             MOVStreamContext *sc = st->priv_data;
5115             if (st->duration > 0)
5116                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
5117         }
5118     }
5119
5120     if (mov->use_mfra_for > 0) {
5121         for (i = 0; i < s->nb_streams; i++) {
5122             AVStream *st = s->streams[i];
5123             MOVStreamContext *sc = st->priv_data;
5124             if (sc->duration_for_fps > 0) {
5125                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
5126                     sc->duration_for_fps;
5127             }
5128         }
5129     }
5130
5131     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
5132         if (mov->bitrates[i]) {
5133             s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
5134         }
5135     }
5136
5137     ff_rfps_calculate(s);
5138
5139     for (i = 0; i < s->nb_streams; i++) {
5140         AVStream *st = s->streams[i];
5141         MOVStreamContext *sc = st->priv_data;
5142
5143         switch (st->codecpar->codec_type) {
5144         case AVMEDIA_TYPE_AUDIO:
5145             err = ff_replaygain_export(st, s->metadata);
5146             if (err < 0) {
5147                 mov_read_close(s);
5148                 return err;
5149             }
5150             break;
5151         case AVMEDIA_TYPE_VIDEO:
5152             if (sc->display_matrix) {
5153                 AVPacketSideData *sd, *tmp;
5154
5155                 tmp = av_realloc_array(st->side_data,
5156                                        st->nb_side_data + 1, sizeof(*tmp));
5157                 if (!tmp)
5158                     return AVERROR(ENOMEM);
5159
5160                 st->side_data = tmp;
5161                 st->nb_side_data++;
5162
5163                 sd = &st->side_data[st->nb_side_data - 1];
5164                 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
5165                 sd->size = sizeof(int32_t) * 9;
5166                 sd->data = (uint8_t*)sc->display_matrix;
5167                 sc->display_matrix = NULL;
5168             }
5169             break;
5170         }
5171     }
5172     ff_configure_buffers_for_index(s, AV_TIME_BASE);
5173
5174     return 0;
5175 }
5176
5177 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
5178 {
5179     AVIndexEntry *sample = NULL;
5180     int64_t best_dts = INT64_MAX;
5181     int i;
5182     for (i = 0; i < s->nb_streams; i++) {
5183         AVStream *avst = s->streams[i];
5184         MOVStreamContext *msc = avst->priv_data;
5185         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
5186             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
5187             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
5188             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
5189             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
5190                 (s->pb->seekable &&
5191                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
5192                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
5193                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
5194                 sample = current_sample;
5195                 best_dts = dts;
5196                 *st = avst;
5197             }
5198         }
5199     }
5200     return sample;
5201 }
5202
5203 static int should_retry(AVIOContext *pb, int error_code) {
5204     if (error_code == AVERROR_EOF || avio_feof(pb))
5205         return 0;
5206
5207     return 1;
5208 }
5209
5210 static int mov_switch_root(AVFormatContext *s, int64_t target)
5211 {
5212     MOVContext *mov = s->priv_data;
5213     int i, j;
5214     int already_read = 0;
5215
5216     if (avio_seek(s->pb, target, SEEK_SET) != target) {
5217         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
5218         return AVERROR_INVALIDDATA;
5219     }
5220
5221     mov->next_root_atom = 0;
5222
5223     for (i = 0; i < mov->fragment_index_count; i++) {
5224         MOVFragmentIndex *index = mov->fragment_index_data[i];
5225         int found = 0;
5226         for (j = 0; j < index->item_count; j++) {
5227             MOVFragmentIndexItem *item = &index->items[j];
5228             if (found) {
5229                 mov->next_root_atom = item->moof_offset;
5230                 break; // Advance to next index in outer loop
5231             } else if (item->moof_offset == target) {
5232                 index->current_item = FFMIN(j, index->current_item);
5233                 if (item->headers_read)
5234                     already_read = 1;
5235                 item->headers_read = 1;
5236                 found = 1;
5237             }
5238         }
5239         if (!found)
5240             index->current_item = 0;
5241     }
5242
5243     if (already_read)
5244         return 0;
5245
5246     mov->found_mdat = 0;
5247
5248     if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
5249         avio_feof(s->pb))
5250         return AVERROR_EOF;
5251     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
5252
5253     return 1;
5254 }
5255
5256 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
5257 {
5258     uint8_t *side, *extradata;
5259     int extradata_size;
5260
5261     /* Save the current index. */
5262     sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
5263
5264     /* Notify the decoder that extradata changed. */
5265     extradata_size = sc->extradata_size[sc->last_stsd_index];
5266     extradata = sc->extradata[sc->last_stsd_index];
5267     if (extradata_size > 0 && extradata) {
5268         side = av_packet_new_side_data(pkt,
5269                                        AV_PKT_DATA_NEW_EXTRADATA,
5270                                        extradata_size);
5271         if (!side)
5272             return AVERROR(ENOMEM);
5273         memcpy(side, extradata, extradata_size);
5274     }
5275
5276     return 0;
5277 }
5278
5279 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
5280 {
5281     MOVContext *mov = s->priv_data;
5282     MOVStreamContext *sc;
5283     AVIndexEntry *sample;
5284     AVStream *st = NULL;
5285     int ret;
5286     mov->fc = s;
5287  retry:
5288     sample = mov_find_next_sample(s, &st);
5289     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
5290         if (!mov->next_root_atom)
5291             return AVERROR_EOF;
5292         if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
5293             return ret;
5294         goto retry;
5295     }
5296     sc = st->priv_data;
5297     /* must be done just before reading, to avoid infinite loop on sample */
5298     sc->current_sample++;
5299
5300     if (mov->next_root_atom) {
5301         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
5302         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
5303     }
5304
5305     if (st->discard != AVDISCARD_ALL) {
5306         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
5307         if (ret64 != sample->pos) {
5308             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
5309                    sc->ffindex, sample->pos);
5310             sc->current_sample -= should_retry(sc->pb, ret64);
5311             return AVERROR_INVALIDDATA;
5312         }
5313
5314         if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
5315             av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
5316             goto retry;
5317         }
5318
5319         ret = av_get_packet(sc->pb, pkt, sample->size);
5320         if (ret < 0) {
5321             sc->current_sample -= should_retry(sc->pb, ret);
5322             return ret;
5323         }
5324         if (sc->has_palette) {
5325             uint8_t *pal;
5326
5327             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
5328             if (!pal) {
5329                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
5330             } else {
5331                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
5332                 sc->has_palette = 0;
5333             }
5334         }
5335 #if CONFIG_DV_DEMUXER
5336         if (mov->dv_demux && sc->dv_audio_container) {
5337             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
5338             av_freep(&pkt->data);
5339             pkt->size = 0;
5340             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
5341             if (ret < 0)
5342                 return ret;
5343         }
5344 #endif
5345         if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
5346             if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
5347                 st->need_parsing = AVSTREAM_PARSE_FULL;
5348         }
5349     }
5350
5351     pkt->stream_index = sc->ffindex;
5352     pkt->dts = sample->timestamp;
5353     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
5354         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
5355         /* update ctts context */
5356         sc->ctts_sample++;
5357         if (sc->ctts_index < sc->ctts_count &&
5358             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
5359             sc->ctts_index++;
5360             sc->ctts_sample = 0;
5361         }
5362         if (sc->wrong_dts)
5363             pkt->dts = AV_NOPTS_VALUE;
5364     } else {
5365         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
5366             st->index_entries[sc->current_sample].timestamp : st->duration;
5367         pkt->duration = next_dts - pkt->dts;
5368         pkt->pts = pkt->dts;
5369     }
5370     if (st->discard == AVDISCARD_ALL)
5371         goto retry;
5372     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
5373     pkt->pos = sample->pos;
5374
5375     /* Multiple stsd handling. */
5376     if (sc->stsc_data) {
5377         /* Keep track of the stsc index for the given sample, then check
5378         * if the stsd index is different from the last used one. */
5379         sc->stsc_sample++;
5380         if (sc->stsc_index < sc->stsc_count - 1 &&
5381             mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
5382             sc->stsc_index++;
5383             sc->stsc_sample = 0;
5384         /* Do not check indexes after a switch. */
5385         } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
5386                    sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
5387                    sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
5388             ret = mov_change_extradata(sc, pkt);
5389             if (ret < 0)
5390                 return ret;
5391         }
5392     }
5393
5394     if (mov->aax_mode)
5395         aax_filter(pkt->data, pkt->size, mov);
5396
5397     if (sc->cenc.aes_ctr) {
5398         ret = cenc_filter(mov, sc, pkt->data, pkt->size);
5399         if (ret) {
5400             return ret;
5401         }
5402     }
5403
5404     return 0;
5405 }
5406
5407 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
5408 {
5409     MOVContext *mov = s->priv_data;
5410     int i, j;
5411
5412     if (!mov->fragment_index_complete)
5413         return 0;
5414
5415     for (i = 0; i < mov->fragment_index_count; i++) {
5416         if (mov->fragment_index_data[i]->track_id == st->id) {
5417             MOVFragmentIndex *index = mov->fragment_index_data[i];
5418             for (j = index->item_count - 1; j >= 0; j--) {
5419                 if (index->items[j].time <= timestamp) {
5420                     if (index->items[j].headers_read)
5421                         return 0;
5422
5423                     return mov_switch_root(s, index->items[j].moof_offset);
5424                 }
5425             }
5426         }
5427     }
5428
5429     return 0;
5430 }
5431
5432 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
5433 {
5434     MOVStreamContext *sc = st->priv_data;
5435     int sample, time_sample;
5436     int i;
5437
5438     int ret = mov_seek_fragment(s, st, timestamp);
5439     if (ret < 0)
5440         return ret;
5441
5442     sample = av_index_search_timestamp(st, timestamp, flags);
5443     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
5444     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
5445         sample = 0;
5446     if (sample < 0) /* not sure what to do */
5447         return AVERROR_INVALIDDATA;
5448     sc->current_sample = sample;
5449     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
5450     /* adjust ctts index */
5451     if (sc->ctts_data) {
5452         time_sample = 0;
5453         for (i = 0; i < sc->ctts_count; i++) {
5454             int next = time_sample + sc->ctts_data[i].count;
5455             if (next > sc->current_sample) {
5456                 sc->ctts_index = i;
5457                 sc->ctts_sample = sc->current_sample - time_sample;
5458                 break;
5459             }
5460             time_sample = next;
5461         }
5462     }
5463
5464     /* adjust stsd index */
5465     time_sample = 0;
5466     for (i = 0; i < sc->stsc_count; i++) {
5467         int next = time_sample + mov_get_stsc_samples(sc, i);
5468         if (next > sc->current_sample) {
5469             sc->stsc_index = i;
5470             sc->stsc_sample = sc->current_sample - time_sample;
5471             break;
5472         }
5473         time_sample = next;
5474     }
5475
5476     ret = mov_seek_auxiliary_info(s, sc);
5477     if (ret < 0) {
5478         return ret;
5479     }
5480
5481     return sample;
5482 }
5483
5484 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
5485 {
5486     MOVContext *mc = s->priv_data;
5487     AVStream *st;
5488     int sample;
5489     int i;
5490
5491     if (stream_index >= s->nb_streams)
5492         return AVERROR_INVALIDDATA;
5493
5494     st = s->streams[stream_index];
5495     sample = mov_seek_stream(s, st, sample_time, flags);
5496     if (sample < 0)
5497         return sample;
5498
5499     if (mc->seek_individually) {
5500         /* adjust seek timestamp to found sample timestamp */
5501         int64_t seek_timestamp = st->index_entries[sample].timestamp;
5502
5503         for (i = 0; i < s->nb_streams; i++) {
5504             int64_t timestamp;
5505             MOVStreamContext *sc = s->streams[i]->priv_data;
5506             st = s->streams[i];
5507             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5508
5509             if (stream_index == i)
5510                 continue;
5511
5512             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5513             mov_seek_stream(s, st, timestamp, flags);
5514         }
5515     } else {
5516         for (i = 0; i < s->nb_streams; i++) {
5517             MOVStreamContext *sc;
5518             st = s->streams[i];
5519             sc = st->priv_data;
5520             sc->current_sample = 0;
5521         }
5522         while (1) {
5523             MOVStreamContext *sc;
5524             AVIndexEntry *entry = mov_find_next_sample(s, &st);
5525             if (!entry)
5526                 return AVERROR_INVALIDDATA;
5527             sc = st->priv_data;
5528             if (sc->ffindex == stream_index && sc->current_sample == sample)
5529                 break;
5530             sc->current_sample++;
5531         }
5532     }
5533     return 0;
5534 }
5535
5536 #define OFFSET(x) offsetof(MOVContext, x)
5537 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5538 static const AVOption mov_options[] = {
5539     {"use_absolute_path",
5540         "allow using absolute path when opening alias, this is a possible security issue",
5541         OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
5542         0, 1, FLAGS},
5543     {"seek_streams_individually",
5544         "Seek each stream individually to the to the closest point",
5545         OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
5546         0, 1, FLAGS},
5547     {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
5548         0, 1, FLAGS},
5549     {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5550         0, 1, FLAGS},
5551     {"use_mfra_for",
5552         "use mfra for fragment timestamps",
5553         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5554         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5555         "use_mfra_for"},
5556     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5557         FLAGS, "use_mfra_for" },
5558     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5559         FLAGS, "use_mfra_for" },
5560     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5561         FLAGS, "use_mfra_for" },
5562     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5563         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5564     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5565         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5566     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5567         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5568     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5569         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5570         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5571         .flags = AV_OPT_FLAG_DECODING_PARAM },
5572     { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5573     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
5574         {.i64 = 0}, 0, 1, FLAGS },
5575
5576     { NULL },
5577 };
5578
5579 static const AVClass mov_class = {
5580     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5581     .item_name  = av_default_item_name,
5582     .option     = mov_options,
5583     .version    = LIBAVUTIL_VERSION_INT,
5584 };
5585
5586 AVInputFormat ff_mov_demuxer = {
5587     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
5588     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5589     .priv_class     = &mov_class,
5590     .priv_data_size = sizeof(MOVContext),
5591     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
5592     .read_probe     = mov_probe,
5593     .read_header    = mov_read_header,
5594     .read_packet    = mov_read_packet,
5595     .read_close     = mov_read_close,
5596     .read_seek      = mov_read_seek,
5597     .flags          = AVFMT_NO_BYTE_SEEK,
5598 };