]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
Merge commit '9c37d765ef28b027414f86b0088b0c282a3c46d8'
[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/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/aes.h"
43 #include "libavutil/aes_ctr.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/sha.h"
46 #include "libavutil/spherical.h"
47 #include "libavutil/stereo3d.h"
48 #include "libavutil/timecode.h"
49 #include "libavcodec/ac3tab.h"
50 #include "libavcodec/flac.h"
51 #include "libavcodec/mpegaudiodecheader.h"
52 #include "avformat.h"
53 #include "internal.h"
54 #include "avio_internal.h"
55 #include "riff.h"
56 #include "isom.h"
57 #include "libavcodec/get_bits.h"
58 #include "id3v1.h"
59 #include "mov_chan.h"
60 #include "replaygain.h"
61
62 #if CONFIG_ZLIB
63 #include <zlib.h>
64 #endif
65
66 #include "qtpalette.h"
67
68 /* those functions parse an atom */
69 /* links atom IDs to parse functions */
70 typedef struct MOVParseTableEntry {
71     uint32_t type;
72     int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
73 } MOVParseTableEntry;
74
75 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
76 static int mov_read_mfra(MOVContext *c, AVIOContext *f);
77 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
78                               int count, int duration);
79
80 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
81                                              unsigned len, const char *key)
82 {
83     char buf[16];
84
85     short current, total = 0;
86     avio_rb16(pb); // unknown
87     current = avio_rb16(pb);
88     if (len >= 6)
89         total = avio_rb16(pb);
90     if (!total)
91         snprintf(buf, sizeof(buf), "%d", current);
92     else
93         snprintf(buf, sizeof(buf), "%d/%d", current, total);
94     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
95     av_dict_set(&c->fc->metadata, key, buf, 0);
96
97     return 0;
98 }
99
100 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
101                                             unsigned len, const char *key)
102 {
103     /* bypass padding bytes */
104     avio_r8(pb);
105     avio_r8(pb);
106     avio_r8(pb);
107
108     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
109     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
110
111     return 0;
112 }
113
114 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
115                                         unsigned len, const char *key)
116 {
117     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
118     av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
119
120     return 0;
121 }
122
123 static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
124                              unsigned len, const char *key)
125 {
126     short genre;
127
128     avio_r8(pb); // unknown
129
130     genre = avio_r8(pb);
131     if (genre < 1 || genre > ID3v1_GENRE_MAX)
132         return 0;
133     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
134     av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
135
136     return 0;
137 }
138
139 static const uint32_t mac_to_unicode[128] = {
140     0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
141     0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
142     0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
143     0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
144     0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
145     0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
146     0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
147     0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
148     0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
149     0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
150     0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
151     0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
152     0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
153     0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
154     0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
155     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
156 };
157
158 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
159                                char *dst, int dstlen)
160 {
161     char *p = dst;
162     char *end = dst+dstlen-1;
163     int i;
164
165     for (i = 0; i < len; i++) {
166         uint8_t t, c = avio_r8(pb);
167
168         if (p >= end)
169             continue;
170
171         if (c < 0x80)
172             *p++ = c;
173         else if (p < end)
174             PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
175     }
176     *p = 0;
177     return p - dst;
178 }
179
180 static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
181 {
182     AVPacket pkt;
183     AVStream *st;
184     MOVStreamContext *sc;
185     enum AVCodecID id;
186     int ret;
187
188     switch (type) {
189     case 0xd:  id = AV_CODEC_ID_MJPEG; break;
190     case 0xe:  id = AV_CODEC_ID_PNG;   break;
191     case 0x1b: id = AV_CODEC_ID_BMP;   break;
192     default:
193         av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
194         avio_skip(pb, len);
195         return 0;
196     }
197
198     st = avformat_new_stream(c->fc, NULL);
199     if (!st)
200         return AVERROR(ENOMEM);
201     sc = av_mallocz(sizeof(*sc));
202     if (!sc)
203         return AVERROR(ENOMEM);
204     st->priv_data = sc;
205
206     ret = av_get_packet(pb, &pkt, len);
207     if (ret < 0)
208         return ret;
209
210     if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
211         if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
212             id = AV_CODEC_ID_PNG;
213         } else {
214             id = AV_CODEC_ID_MJPEG;
215         }
216     }
217
218     st->disposition              |= AV_DISPOSITION_ATTACHED_PIC;
219
220     st->attached_pic              = pkt;
221     st->attached_pic.stream_index = st->index;
222     st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
223
224     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
225     st->codecpar->codec_id   = id;
226
227     return 0;
228 }
229
230 // 3GPP TS 26.244
231 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
232 {
233     char language[4] = { 0 };
234     char buf[200], place[100];
235     uint16_t langcode = 0;
236     double longitude, latitude, altitude;
237     const char *key = "location";
238
239     if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
240         av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
241         return AVERROR_INVALIDDATA;
242     }
243
244     avio_skip(pb, 4); // version+flags
245     langcode = avio_rb16(pb);
246     ff_mov_lang_to_iso639(langcode, language);
247     len -= 6;
248
249     len -= avio_get_str(pb, len, place, sizeof(place));
250     if (len < 1) {
251         av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
252         return AVERROR_INVALIDDATA;
253     }
254     avio_skip(pb, 1); // role
255     len -= 1;
256
257     if (len < 12) {
258         av_log(c->fc, AV_LOG_ERROR,
259                "loci too short (%u bytes left, need at least %d)\n", len, 12);
260         return AVERROR_INVALIDDATA;
261     }
262     longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
263     latitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
264     altitude  = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
265
266     // Try to output in the same format as the ?xyz field
267     snprintf(buf, sizeof(buf), "%+08.4f%+09.4f",  latitude, longitude);
268     if (altitude)
269         av_strlcatf(buf, sizeof(buf), "%+f", altitude);
270     av_strlcatf(buf, sizeof(buf), "/%s", place);
271
272     if (*language && strcmp(language, "und")) {
273         char key2[16];
274         snprintf(key2, sizeof(key2), "%s-%s", key, language);
275         av_dict_set(&c->fc->metadata, key2, buf, 0);
276     }
277     c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
278     return av_dict_set(&c->fc->metadata, key, buf, 0);
279 }
280
281 static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
282 {
283     int i, n_hmmt;
284
285     if (len < 2)
286         return 0;
287     if (c->ignore_chapters)
288         return 0;
289
290     n_hmmt = avio_rb32(pb);
291     for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
292         int moment_time = avio_rb32(pb);
293         avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
294     }
295     return 0;
296 }
297
298 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
299 {
300     char tmp_key[5];
301     char key2[32], language[4] = {0};
302     char *str = NULL;
303     const char *key = NULL;
304     uint16_t langcode = 0;
305     uint32_t data_type = 0, str_size, str_size_alloc;
306     int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
307     int raw = 0;
308     int num = 0;
309
310     switch (atom.type) {
311     case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
312     case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
313     case MKTAG( 'X','M','P','_'):
314         if (c->export_xmp) { key = "xmp"; raw = 1; } break;
315     case MKTAG( 'a','A','R','T'): key = "album_artist";    break;
316     case MKTAG( 'a','k','I','D'): key = "account_type";
317         parse = mov_metadata_int8_no_padding; break;
318     case MKTAG( 'a','p','I','D'): key = "account_id"; break;
319     case MKTAG( 'c','a','t','g'): key = "category"; break;
320     case MKTAG( 'c','p','i','l'): key = "compilation";
321         parse = mov_metadata_int8_no_padding; break;
322     case MKTAG( 'c','p','r','t'): key = "copyright"; break;
323     case MKTAG( 'd','e','s','c'): key = "description"; break;
324     case MKTAG( 'd','i','s','k'): key = "disc";
325         parse = mov_metadata_track_or_disc_number; break;
326     case MKTAG( 'e','g','i','d'): key = "episode_uid";
327         parse = mov_metadata_int8_no_padding; break;
328     case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
329     case MKTAG( 'g','n','r','e'): key = "genre";
330         parse = mov_metadata_gnre; break;
331     case MKTAG( 'h','d','v','d'): key = "hd_video";
332         parse = mov_metadata_int8_no_padding; break;
333     case MKTAG( 'H','M','M','T'):
334         return mov_metadata_hmmt(c, pb, atom.size);
335     case MKTAG( 'k','e','y','w'): key = "keywords";  break;
336     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
337     case MKTAG( 'l','o','c','i'):
338         return mov_metadata_loci(c, pb, atom.size);
339     case MKTAG( 'm','a','n','u'): key = "make"; break;
340     case MKTAG( 'm','o','d','l'): key = "model"; break;
341     case MKTAG( 'p','c','s','t'): key = "podcast";
342         parse = mov_metadata_int8_no_padding; break;
343     case MKTAG( 'p','g','a','p'): key = "gapless_playback";
344         parse = mov_metadata_int8_no_padding; break;
345     case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
346     case MKTAG( 'r','t','n','g'): key = "rating";
347         parse = mov_metadata_int8_no_padding; break;
348     case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
349     case MKTAG( 's','o','a','l'): key = "sort_album";   break;
350     case MKTAG( 's','o','a','r'): key = "sort_artist";  break;
351     case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
352     case MKTAG( 's','o','n','m'): key = "sort_name";    break;
353     case MKTAG( 's','o','s','n'): key = "sort_show";    break;
354     case MKTAG( 's','t','i','k'): key = "media_type";
355         parse = mov_metadata_int8_no_padding; break;
356     case MKTAG( 't','r','k','n'): key = "track";
357         parse = mov_metadata_track_or_disc_number; break;
358     case MKTAG( 't','v','e','n'): key = "episode_id"; break;
359     case MKTAG( 't','v','e','s'): key = "episode_sort";
360         parse = mov_metadata_int8_bypass_padding; break;
361     case MKTAG( 't','v','n','n'): key = "network";   break;
362     case MKTAG( 't','v','s','h'): key = "show";      break;
363     case MKTAG( 't','v','s','n'): key = "season_number";
364         parse = mov_metadata_int8_bypass_padding; break;
365     case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
366     case MKTAG(0xa9,'P','R','D'): key = "producer";  break;
367     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
368     case MKTAG(0xa9,'a','u','t'): key = "artist";    break;
369     case MKTAG(0xa9,'c','h','p'): key = "chapter";   break;
370     case MKTAG(0xa9,'c','m','t'): key = "comment";   break;
371     case MKTAG(0xa9,'c','o','m'): key = "composer";  break;
372     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
373     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
374     case MKTAG(0xa9,'d','i','r'): key = "director";  break;
375     case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
376     case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
377     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
378     case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
379     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
380     case MKTAG(0xa9,'g','r','p'): key = "grouping";  break;
381     case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
382     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
383     case MKTAG(0xa9,'l','y','r'): key = "lyrics";    break;
384     case MKTAG(0xa9,'m','a','k'): key = "make";      break;
385     case MKTAG(0xa9,'m','o','d'): key = "model";     break;
386     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
387     case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
388     case MKTAG(0xa9,'p','r','d'): key = "producer";  break;
389     case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
390     case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
391     case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
392     case MKTAG(0xa9,'s','t','3'): key = "subtitle";  break;
393     case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
394     case MKTAG(0xa9,'t','o','o'): key = "encoder";   break;
395     case MKTAG(0xa9,'t','r','k'): key = "track";     break;
396     case MKTAG(0xa9,'u','r','l'): key = "URL";       break;
397     case MKTAG(0xa9,'w','r','n'): key = "warning";   break;
398     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
399     case MKTAG(0xa9,'x','y','z'): key = "location";  break;
400     }
401 retry:
402     if (c->itunes_metadata && atom.size > 8) {
403         int data_size = avio_rb32(pb);
404         int tag = avio_rl32(pb);
405         if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
406             data_type = avio_rb32(pb); // type
407             avio_rb32(pb); // unknown
408             str_size = data_size - 16;
409             atom.size -= 16;
410
411             if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
412                 int ret = mov_read_covr(c, pb, data_type, str_size);
413                 if (ret < 0) {
414                     av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
415                 }
416                 return ret;
417             } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
418                 uint32_t index = AV_RB32(&atom.type);
419                 if (index < c->meta_keys_count && index > 0) {
420                     key = c->meta_keys[index];
421                 } else {
422                     av_log(c->fc, AV_LOG_WARNING,
423                            "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n",
424                            index, c->meta_keys_count);
425                 }
426             }
427         } else return 0;
428     } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
429         str_size = avio_rb16(pb); // string length
430         if (str_size > atom.size) {
431             raw = 1;
432             avio_seek(pb, -2, SEEK_CUR);
433             av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
434             goto retry;
435         }
436         langcode = avio_rb16(pb);
437         ff_mov_lang_to_iso639(langcode, language);
438         atom.size -= 4;
439     } else
440         str_size = atom.size;
441
442     if (c->export_all && !key) {
443         snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
444         key = tmp_key;
445     }
446
447     if (!key)
448         return 0;
449     if (atom.size < 0 || str_size >= INT_MAX/2)
450         return AVERROR_INVALIDDATA;
451
452     // Allocates enough space if data_type is a int32 or float32 number, otherwise
453     // worst-case requirement for output string in case of utf8 coded input
454     num = (data_type >= 21 && data_type <= 23);
455     str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
456     str = av_mallocz(str_size_alloc);
457     if (!str)
458         return AVERROR(ENOMEM);
459
460     if (parse)
461         parse(c, pb, str_size, key);
462     else {
463         if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
464             mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
465         } else if (data_type == 21) { // BE signed integer, variable size
466             int val = 0;
467             if (str_size == 1)
468                 val = (int8_t)avio_r8(pb);
469             else if (str_size == 2)
470                 val = (int16_t)avio_rb16(pb);
471             else if (str_size == 3)
472                 val = ((int32_t)(avio_rb24(pb)<<8))>>8;
473             else if (str_size == 4)
474                 val = (int32_t)avio_rb32(pb);
475             if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
476                 av_log(c->fc, AV_LOG_ERROR,
477                        "Failed to store the number (%d) in string.\n", val);
478                 av_free(str);
479                 return AVERROR_INVALIDDATA;
480             }
481         } else if (data_type == 22) { // BE unsigned integer, variable size
482             unsigned int val = 0;
483             if (str_size == 1)
484                 val = avio_r8(pb);
485             else if (str_size == 2)
486                 val = avio_rb16(pb);
487             else if (str_size == 3)
488                 val = avio_rb24(pb);
489             else if (str_size == 4)
490                 val = avio_rb32(pb);
491             if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
492                 av_log(c->fc, AV_LOG_ERROR,
493                        "Failed to store the number (%u) in string.\n", val);
494                 av_free(str);
495                 return AVERROR_INVALIDDATA;
496             }
497         } else if (data_type == 23 && str_size >= 4) {  // BE float32
498             float val = av_int2float(avio_rb32(pb));
499             if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
500                 av_log(c->fc, AV_LOG_ERROR,
501                        "Failed to store the float32 number (%f) in string.\n", val);
502                 av_free(str);
503                 return AVERROR_INVALIDDATA;
504             }
505         } else {
506             int ret = ffio_read_size(pb, str, str_size);
507             if (ret < 0) {
508                 av_free(str);
509                 return ret;
510             }
511             str[str_size] = 0;
512         }
513         c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
514         av_dict_set(&c->fc->metadata, key, str, 0);
515         if (*language && strcmp(language, "und")) {
516             snprintf(key2, sizeof(key2), "%s-%s", key, language);
517             av_dict_set(&c->fc->metadata, key2, str, 0);
518         }
519         if (!strcmp(key, "encoder")) {
520             int major, minor, micro;
521             if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
522                 c->handbrake_version = 1000000*major + 1000*minor + micro;
523             }
524         }
525     }
526
527     av_freep(&str);
528     return 0;
529 }
530
531 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
532 {
533     int64_t start;
534     int i, nb_chapters, str_len, version;
535     char str[256+1];
536     int ret;
537
538     if (c->ignore_chapters)
539         return 0;
540
541     if ((atom.size -= 5) < 0)
542         return 0;
543
544     version = avio_r8(pb);
545     avio_rb24(pb);
546     if (version)
547         avio_rb32(pb); // ???
548     nb_chapters = avio_r8(pb);
549
550     for (i = 0; i < nb_chapters; i++) {
551         if (atom.size < 9)
552             return 0;
553
554         start = avio_rb64(pb);
555         str_len = avio_r8(pb);
556
557         if ((atom.size -= 9+str_len) < 0)
558             return 0;
559
560         ret = ffio_read_size(pb, str, str_len);
561         if (ret < 0)
562             return ret;
563         str[str_len] = 0;
564         avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
565     }
566     return 0;
567 }
568
569 #define MIN_DATA_ENTRY_BOX_SIZE 12
570 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 {
572     AVStream *st;
573     MOVStreamContext *sc;
574     int entries, i, j;
575
576     if (c->fc->nb_streams < 1)
577         return 0;
578     st = c->fc->streams[c->fc->nb_streams-1];
579     sc = st->priv_data;
580
581     avio_rb32(pb); // version + flags
582     entries = avio_rb32(pb);
583     if (!entries ||
584         entries >  (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
585         entries >= UINT_MAX / sizeof(*sc->drefs))
586         return AVERROR_INVALIDDATA;
587     sc->drefs_count = 0;
588     av_free(sc->drefs);
589     sc->drefs_count = 0;
590     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
591     if (!sc->drefs)
592         return AVERROR(ENOMEM);
593     sc->drefs_count = entries;
594
595     for (i = 0; i < entries; i++) {
596         MOVDref *dref = &sc->drefs[i];
597         uint32_t size = avio_rb32(pb);
598         int64_t next = avio_tell(pb) + size - 4;
599
600         if (size < 12)
601             return AVERROR_INVALIDDATA;
602
603         dref->type = avio_rl32(pb);
604         avio_rb32(pb); // version + flags
605
606         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
607             /* macintosh alias record */
608             uint16_t volume_len, len;
609             int16_t type;
610             int ret;
611
612             avio_skip(pb, 10);
613
614             volume_len = avio_r8(pb);
615             volume_len = FFMIN(volume_len, 27);
616             ret = ffio_read_size(pb, dref->volume, 27);
617             if (ret < 0)
618                 return ret;
619             dref->volume[volume_len] = 0;
620             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
621
622             avio_skip(pb, 12);
623
624             len = avio_r8(pb);
625             len = FFMIN(len, 63);
626             ret = ffio_read_size(pb, dref->filename, 63);
627             if (ret < 0)
628                 return ret;
629             dref->filename[len] = 0;
630             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
631
632             avio_skip(pb, 16);
633
634             /* read next level up_from_alias/down_to_target */
635             dref->nlvl_from = avio_rb16(pb);
636             dref->nlvl_to   = avio_rb16(pb);
637             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
638                    dref->nlvl_from, dref->nlvl_to);
639
640             avio_skip(pb, 16);
641
642             for (type = 0; type != -1 && avio_tell(pb) < next; ) {
643                 if(avio_feof(pb))
644                     return AVERROR_EOF;
645                 type = avio_rb16(pb);
646                 len = avio_rb16(pb);
647                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
648                 if (len&1)
649                     len += 1;
650                 if (type == 2) { // absolute path
651                     av_free(dref->path);
652                     dref->path = av_mallocz(len+1);
653                     if (!dref->path)
654                         return AVERROR(ENOMEM);
655
656                     ret = ffio_read_size(pb, dref->path, len);
657                     if (ret < 0) {
658                         av_freep(&dref->path);
659                         return ret;
660                     }
661                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
662                         len -= volume_len;
663                         memmove(dref->path, dref->path+volume_len, len);
664                         dref->path[len] = 0;
665                     }
666                     // trim string of any ending zeros
667                     for (j = len - 1; j >= 0; j--) {
668                         if (dref->path[j] == 0)
669                             len--;
670                         else
671                             break;
672                     }
673                     for (j = 0; j < len; j++)
674                         if (dref->path[j] == ':' || dref->path[j] == 0)
675                             dref->path[j] = '/';
676                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
677                 } else if (type == 0) { // directory name
678                     av_free(dref->dir);
679                     dref->dir = av_malloc(len+1);
680                     if (!dref->dir)
681                         return AVERROR(ENOMEM);
682
683                     ret = ffio_read_size(pb, dref->dir, len);
684                     if (ret < 0) {
685                         av_freep(&dref->dir);
686                         return ret;
687                     }
688                     dref->dir[len] = 0;
689                     for (j = 0; j < len; j++)
690                         if (dref->dir[j] == ':')
691                             dref->dir[j] = '/';
692                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
693                 } else
694                     avio_skip(pb, len);
695             }
696         } else {
697             av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n",
698                    dref->type, size);
699             entries--;
700             i--;
701         }
702         avio_seek(pb, next, SEEK_SET);
703     }
704     return 0;
705 }
706
707 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
708 {
709     AVStream *st;
710     uint32_t type;
711     uint32_t ctype;
712     int64_t title_size;
713     char *title_str;
714     int ret;
715
716     avio_r8(pb); /* version */
717     avio_rb24(pb); /* flags */
718
719     /* component type */
720     ctype = avio_rl32(pb);
721     type = avio_rl32(pb); /* component subtype */
722
723     av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype));
724     av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type));
725
726     if (c->trak_index < 0) {  // meta not inside a trak
727         if (type == MKTAG('m','d','t','a')) {
728             c->found_hdlr_mdta = 1;
729         }
730         return 0;
731     }
732
733     st = c->fc->streams[c->fc->nb_streams-1];
734
735     if     (type == MKTAG('v','i','d','e'))
736         st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
737     else if (type == MKTAG('s','o','u','n'))
738         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
739     else if (type == MKTAG('m','1','a',' '))
740         st->codecpar->codec_id = AV_CODEC_ID_MP2;
741     else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
742         st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
743
744     avio_rb32(pb); /* component  manufacture */
745     avio_rb32(pb); /* component flags */
746     avio_rb32(pb); /* component flags mask */
747
748     title_size = atom.size - 24;
749     if (title_size > 0) {
750         if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
751             return AVERROR_INVALIDDATA;
752         title_str = av_malloc(title_size + 1); /* Add null terminator */
753         if (!title_str)
754             return AVERROR(ENOMEM);
755
756         ret = ffio_read_size(pb, title_str, title_size);
757         if (ret < 0) {
758             av_freep(&title_str);
759             return ret;
760         }
761         title_str[title_size] = 0;
762         if (title_str[0]) {
763             int off = (!c->isom && title_str[0] == title_size - 1);
764             av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
765         }
766         av_freep(&title_str);
767     }
768
769     return 0;
770 }
771
772 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
773 {
774     return ff_mov_read_esds(c->fc, pb);
775 }
776
777 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
778 {
779     AVStream *st;
780     enum AVAudioServiceType *ast;
781     int ac3info, acmod, lfeon, bsmod;
782
783     if (c->fc->nb_streams < 1)
784         return 0;
785     st = c->fc->streams[c->fc->nb_streams-1];
786
787     ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
788                                                             sizeof(*ast));
789     if (!ast)
790         return AVERROR(ENOMEM);
791
792     ac3info = avio_rb24(pb);
793     bsmod = (ac3info >> 14) & 0x7;
794     acmod = (ac3info >> 11) & 0x7;
795     lfeon = (ac3info >> 10) & 0x1;
796     st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
797     st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
798     if (lfeon)
799         st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
800     *ast = bsmod;
801     if (st->codecpar->channels > 1 && bsmod == 0x7)
802         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
803
804 #if FF_API_LAVF_AVCTX
805     FF_DISABLE_DEPRECATION_WARNINGS
806     st->codec->audio_service_type = *ast;
807     FF_ENABLE_DEPRECATION_WARNINGS
808 #endif
809
810     return 0;
811 }
812
813 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
814 {
815     AVStream *st;
816     enum AVAudioServiceType *ast;
817     int eac3info, acmod, lfeon, bsmod;
818
819     if (c->fc->nb_streams < 1)
820         return 0;
821     st = c->fc->streams[c->fc->nb_streams-1];
822
823     ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
824                                                             sizeof(*ast));
825     if (!ast)
826         return AVERROR(ENOMEM);
827
828     /* No need to parse fields for additional independent substreams and its
829      * associated dependent substreams since libavcodec's E-AC-3 decoder
830      * does not support them yet. */
831     avio_rb16(pb); /* data_rate and num_ind_sub */
832     eac3info = avio_rb24(pb);
833     bsmod = (eac3info >> 12) & 0x1f;
834     acmod = (eac3info >>  9) & 0x7;
835     lfeon = (eac3info >>  8) & 0x1;
836     st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
837     if (lfeon)
838         st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
839     st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
840     *ast = bsmod;
841     if (st->codecpar->channels > 1 && bsmod == 0x7)
842         *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
843
844 #if FF_API_LAVF_AVCTX
845     FF_DISABLE_DEPRECATION_WARNINGS
846     st->codec->audio_service_type = *ast;
847     FF_ENABLE_DEPRECATION_WARNINGS
848 #endif
849
850     return 0;
851 }
852
853 static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
854 {
855     const uint32_t ddts_size = 20;
856     AVStream *st = NULL;
857     uint8_t *buf = NULL;
858     uint32_t frame_duration_code = 0;
859     uint32_t channel_layout_code = 0;
860     GetBitContext gb;
861
862     buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE);
863     if (!buf) {
864         return AVERROR(ENOMEM);
865     }
866     if (avio_read(pb, buf, ddts_size) < ddts_size) {
867         av_free(buf);
868         return AVERROR_INVALIDDATA;
869     }
870
871     init_get_bits(&gb, buf, 8*ddts_size);
872
873     if (c->fc->nb_streams < 1) {
874         av_free(buf);
875         return 0;
876     }
877     st = c->fc->streams[c->fc->nb_streams-1];
878
879     st->codecpar->sample_rate = get_bits_long(&gb, 32);
880     if (st->codecpar->sample_rate <= 0) {
881         av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
882         av_free(buf);
883         return AVERROR_INVALIDDATA;
884     }
885     skip_bits_long(&gb, 32); /* max bitrate */
886     st->codecpar->bit_rate = get_bits_long(&gb, 32);
887     st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
888     frame_duration_code = get_bits(&gb, 2);
889     skip_bits(&gb, 30); /* various fields */
890     channel_layout_code = get_bits(&gb, 16);
891
892     st->codecpar->frame_size =
893             (frame_duration_code == 0) ? 512 :
894             (frame_duration_code == 1) ? 1024 :
895             (frame_duration_code == 2) ? 2048 :
896             (frame_duration_code == 3) ? 4096 : 0;
897
898     if (channel_layout_code > 0xff) {
899         av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
900     }
901     st->codecpar->channel_layout =
902             ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
903             ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
904             ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
905             ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
906             ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
907             ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
908
909     st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
910     av_free(buf);
911
912     return 0;
913 }
914
915 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
916 {
917     AVStream *st;
918
919     if (c->fc->nb_streams < 1)
920         return 0;
921     st = c->fc->streams[c->fc->nb_streams-1];
922
923     if (atom.size < 16)
924         return 0;
925
926     /* skip version and flags */
927     avio_skip(pb, 4);
928
929     ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
930
931     return 0;
932 }
933
934 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
935 {
936     AVStream *st;
937     int ret;
938
939     if (c->fc->nb_streams < 1)
940         return 0;
941     st = c->fc->streams[c->fc->nb_streams-1];
942
943     if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
944         av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
945
946     return ret;
947 }
948
949 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
950 {
951     const int num = avio_rb32(pb);
952     const int den = avio_rb32(pb);
953     AVStream *st;
954
955     if (c->fc->nb_streams < 1)
956         return 0;
957     st = c->fc->streams[c->fc->nb_streams-1];
958
959     if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
960         (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
961         av_log(c->fc, AV_LOG_WARNING,
962                "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
963                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
964                num, den);
965     } else if (den != 0) {
966         av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
967                   num, den, 32767);
968     }
969     return 0;
970 }
971
972 /* this atom contains actual media data */
973 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
974 {
975     if (atom.size == 0) /* wrong one (MP4) */
976         return 0;
977     c->found_mdat=1;
978     return 0; /* now go for moov */
979 }
980
981 #define DRM_BLOB_SIZE 56
982
983 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
984 {
985     uint8_t intermediate_key[20];
986     uint8_t intermediate_iv[20];
987     uint8_t input[64];
988     uint8_t output[64];
989     uint8_t file_checksum[20];
990     uint8_t calculated_checksum[20];
991     struct AVSHA *sha;
992     int i;
993     int ret = 0;
994     uint8_t *activation_bytes = c->activation_bytes;
995     uint8_t *fixed_key = c->audible_fixed_key;
996
997     c->aax_mode = 1;
998
999     sha = av_sha_alloc();
1000     if (!sha)
1001         return AVERROR(ENOMEM);
1002     c->aes_decrypt = av_aes_alloc();
1003     if (!c->aes_decrypt) {
1004         ret = AVERROR(ENOMEM);
1005         goto fail;
1006     }
1007
1008     /* drm blob processing */
1009     avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
1010     avio_read(pb, input, DRM_BLOB_SIZE);
1011     avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
1012     avio_read(pb, file_checksum, 20);
1013
1014     av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
1015     for (i = 0; i < 20; i++)
1016         av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
1017     av_log(c->fc, AV_LOG_INFO, "\n");
1018
1019     /* verify activation data */
1020     if (!activation_bytes) {
1021         av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
1022         ret = 0;  /* allow ffprobe to continue working on .aax files */
1023         goto fail;
1024     }
1025     if (c->activation_bytes_size != 4) {
1026         av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
1027         ret = AVERROR(EINVAL);
1028         goto fail;
1029     }
1030
1031     /* verify fixed key */
1032     if (c->audible_fixed_key_size != 16) {
1033         av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
1034         ret = AVERROR(EINVAL);
1035         goto fail;
1036     }
1037
1038     /* AAX (and AAX+) key derivation */
1039     av_sha_init(sha, 160);
1040     av_sha_update(sha, fixed_key, 16);
1041     av_sha_update(sha, activation_bytes, 4);
1042     av_sha_final(sha, intermediate_key);
1043     av_sha_init(sha, 160);
1044     av_sha_update(sha, fixed_key, 16);
1045     av_sha_update(sha, intermediate_key, 20);
1046     av_sha_update(sha, activation_bytes, 4);
1047     av_sha_final(sha, intermediate_iv);
1048     av_sha_init(sha, 160);
1049     av_sha_update(sha, intermediate_key, 16);
1050     av_sha_update(sha, intermediate_iv, 16);
1051     av_sha_final(sha, calculated_checksum);
1052     if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
1053         av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
1054         ret = AVERROR_INVALIDDATA;
1055         goto fail;
1056     }
1057     av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
1058     av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
1059     for (i = 0; i < 4; i++) {
1060         // file data (in output) is stored in big-endian mode
1061         if (activation_bytes[i] != output[3 - i]) { // critical error
1062             av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
1063             ret = AVERROR_INVALIDDATA;
1064             goto fail;
1065         }
1066     }
1067     memcpy(c->file_key, output + 8, 16);
1068     memcpy(input, output + 26, 16);
1069     av_sha_init(sha, 160);
1070     av_sha_update(sha, input, 16);
1071     av_sha_update(sha, c->file_key, 16);
1072     av_sha_update(sha, fixed_key, 16);
1073     av_sha_final(sha, c->file_iv);
1074
1075 fail:
1076     av_free(sha);
1077
1078     return ret;
1079 }
1080
1081 // Audible AAX (and AAX+) bytestream decryption
1082 static int aax_filter(uint8_t *input, int size, MOVContext *c)
1083 {
1084     int blocks = 0;
1085     unsigned char iv[16];
1086
1087     memcpy(iv, c->file_iv, 16); // iv is overwritten
1088     blocks = size >> 4; // trailing bytes are not encrypted!
1089     av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
1090     av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
1091
1092     return 0;
1093 }
1094
1095 /* read major brand, minor version and compatible brands and store them as metadata */
1096 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1097 {
1098     uint32_t minor_ver;
1099     int comp_brand_size;
1100     char* comp_brands_str;
1101     uint8_t type[5] = {0};
1102     int ret = ffio_read_size(pb, type, 4);
1103     if (ret < 0)
1104         return ret;
1105
1106     if (strcmp(type, "qt  "))
1107         c->isom = 1;
1108     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
1109     av_dict_set(&c->fc->metadata, "major_brand", type, 0);
1110     minor_ver = avio_rb32(pb); /* minor version */
1111     av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
1112
1113     comp_brand_size = atom.size - 8;
1114     if (comp_brand_size < 0)
1115         return AVERROR_INVALIDDATA;
1116     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
1117     if (!comp_brands_str)
1118         return AVERROR(ENOMEM);
1119
1120     ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
1121     if (ret < 0) {
1122         av_freep(&comp_brands_str);
1123         return ret;
1124     }
1125     comp_brands_str[comp_brand_size] = 0;
1126     av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
1127     av_freep(&comp_brands_str);
1128
1129     return 0;
1130 }
1131
1132 /* this atom should contain all header atoms */
1133 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1134 {
1135     int ret;
1136
1137     if (c->found_moov) {
1138         av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
1139         avio_skip(pb, atom.size);
1140         return 0;
1141     }
1142
1143     if ((ret = mov_read_default(c, pb, atom)) < 0)
1144         return ret;
1145     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
1146     /* so we don't parse the whole file if over a network */
1147     c->found_moov=1;
1148     return 0; /* now go for mdat */
1149 }
1150
1151 static MOVFragmentStreamInfo * get_frag_stream_info(
1152     MOVFragmentIndex *frag_index,
1153     int index,
1154     int id)
1155 {
1156     int i;
1157     MOVFragmentIndexItem * item;
1158
1159     if (index < 0 || index >= frag_index->nb_items)
1160         return NULL;
1161     item = &frag_index->item[index];
1162     for (i = 0; i < item->nb_stream_info; i++)
1163         if (item->stream_info[i].id == id)
1164             return &item->stream_info[i];
1165
1166     // This shouldn't happen
1167     return NULL;
1168 }
1169
1170 static void set_frag_stream(MOVFragmentIndex *frag_index, int id)
1171 {
1172     int i;
1173     MOVFragmentIndexItem * item;
1174
1175     if (frag_index->current < 0 ||
1176         frag_index->current >= frag_index->nb_items)
1177         return;
1178
1179     item = &frag_index->item[frag_index->current];
1180     for (i = 0; i < item->nb_stream_info; i++)
1181         if (item->stream_info[i].id == id) {
1182             item->current = i;
1183             return;
1184         }
1185
1186     // id not found.  This shouldn't happen.
1187     item->current = -1;
1188 }
1189
1190 static MOVFragmentStreamInfo * get_current_frag_stream_info(
1191     MOVFragmentIndex *frag_index)
1192 {
1193     MOVFragmentIndexItem *item;
1194     if (frag_index->current < 0 ||
1195         frag_index->current >= frag_index->nb_items)
1196         return NULL;
1197
1198     item = &frag_index->item[frag_index->current];
1199     if (item->current >= 0 && item->current < item->nb_stream_info)
1200         return &item->stream_info[item->current];
1201
1202     // This shouldn't happen
1203     return NULL;
1204 }
1205
1206 static int search_frag_moof_offset(MOVFragmentIndex *frag_index, int64_t offset)
1207 {
1208     int a, b, m;
1209     int64_t moof_offset;
1210
1211     // Optimize for appending new entries
1212     if (!frag_index->nb_items ||
1213         frag_index->item[frag_index->nb_items - 1].moof_offset < offset)
1214         return frag_index->nb_items;
1215
1216     a = -1;
1217     b = frag_index->nb_items;
1218
1219     while (b - a > 1) {
1220         m = (a + b) >> 1;
1221         moof_offset = frag_index->item[m].moof_offset;
1222         if (moof_offset >= offset)
1223             b = m;
1224         if (moof_offset <= offset)
1225             a = m;
1226     }
1227     return b;
1228 }
1229
1230 static int64_t get_stream_info_time(MOVFragmentStreamInfo * frag_stream_info)
1231 {
1232
1233     if (frag_stream_info) {
1234         if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE)
1235             return frag_stream_info->sidx_pts;
1236         if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE)
1237             return frag_stream_info->first_tfra_pts;
1238         if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE)
1239             return frag_stream_info->tfdt_dts;
1240     }
1241     return AV_NOPTS_VALUE;
1242 }
1243
1244 static int64_t get_frag_time(MOVFragmentIndex *frag_index,
1245                              int index, int track_id)
1246 {
1247     MOVFragmentStreamInfo * frag_stream_info;
1248     int64_t timestamp;
1249     int i;
1250
1251     if (track_id >= 0) {
1252         frag_stream_info = get_frag_stream_info(frag_index, index, track_id);
1253         return frag_stream_info->sidx_pts;
1254     }
1255
1256     for (i = 0; i < frag_index->item[index].nb_stream_info; i++) {
1257         frag_stream_info = &frag_index->item[index].stream_info[i];
1258         timestamp = get_stream_info_time(frag_stream_info);
1259         if (timestamp != AV_NOPTS_VALUE)
1260             return timestamp;
1261     }
1262     return AV_NOPTS_VALUE;
1263 }
1264
1265 static int search_frag_timestamp(MOVFragmentIndex *frag_index,
1266                                  AVStream *st, int64_t timestamp)
1267 {
1268     int a, b, m;
1269     int64_t frag_time;
1270     int id = -1;
1271
1272     if (st) {
1273         // If the stream is referenced by any sidx, limit the search
1274         // to fragments that referenced this stream in the sidx
1275         MOVStreamContext *sc = st->priv_data;
1276         if (sc->has_sidx)
1277             id = st->id;
1278     }
1279
1280     a = -1;
1281     b = frag_index->nb_items;
1282
1283     while (b - a > 1) {
1284         m = (a + b) >> 1;
1285         frag_time = get_frag_time(frag_index, m, id);
1286         if (frag_time != AV_NOPTS_VALUE) {
1287             if (frag_time >= timestamp)
1288                 b = m;
1289             if (frag_time <= timestamp)
1290                 a = m;
1291         }
1292     }
1293     return a;
1294 }
1295
1296 static int update_frag_index(MOVContext *c, int64_t offset)
1297 {
1298     int index, i;
1299     MOVFragmentIndexItem * item;
1300     MOVFragmentStreamInfo * frag_stream_info;
1301
1302     // If moof_offset already exists in frag_index, return index to it
1303     index = search_frag_moof_offset(&c->frag_index, offset);
1304     if (index < c->frag_index.nb_items &&
1305         c->frag_index.item[index].moof_offset == offset)
1306         return index;
1307
1308     // offset is not yet in frag index.
1309     // Insert new item at index (sorted by moof offset)
1310     item = av_fast_realloc(c->frag_index.item,
1311                            &c->frag_index.allocated_size,
1312                            (c->frag_index.nb_items + 1) *
1313                            sizeof(*c->frag_index.item));
1314     if(!item)
1315         return -1;
1316     c->frag_index.item = item;
1317
1318     frag_stream_info = av_realloc_array(NULL, c->fc->nb_streams,
1319                                         sizeof(*item->stream_info));
1320     if (!frag_stream_info)
1321         return -1;
1322
1323     for (i = 0; i < c->fc->nb_streams; i++) {
1324         frag_stream_info[i].id = c->fc->streams[i]->id;
1325         frag_stream_info[i].sidx_pts = AV_NOPTS_VALUE;
1326         frag_stream_info[i].tfdt_dts = AV_NOPTS_VALUE;
1327         frag_stream_info[i].first_tfra_pts = AV_NOPTS_VALUE;
1328         frag_stream_info[i].index_entry = -1;
1329     }
1330
1331     if (index < c->frag_index.nb_items)
1332         memmove(c->frag_index.item + index + 1, c->frag_index.item + index,
1333                 (c->frag_index.nb_items - index) * sizeof(*c->frag_index.item));
1334
1335     item = &c->frag_index.item[index];
1336     item->headers_read = 0;
1337     item->current = 0;
1338     item->nb_stream_info = c->fc->nb_streams;
1339     item->moof_offset = offset;
1340     item->stream_info = frag_stream_info;
1341     c->frag_index.nb_items++;
1342
1343     return index;
1344 }
1345
1346 static void fix_frag_index_entries(MOVFragmentIndex *frag_index, int index,
1347                                    int id, int entries)
1348 {
1349     int i;
1350     MOVFragmentStreamInfo * frag_stream_info;
1351
1352     if (index < 0)
1353         return;
1354     for (i = index; i < frag_index->nb_items; i++) {
1355         frag_stream_info = get_frag_stream_info(frag_index, i, id);
1356         if (frag_stream_info && frag_stream_info->index_entry >= 0)
1357             frag_stream_info->index_entry += entries;
1358     }
1359 }
1360
1361 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1362 {
1363     if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
1364         c->has_looked_for_mfra = 1;
1365         if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
1366             int ret;
1367             av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
1368                     "for a mfra\n");
1369             if ((ret = mov_read_mfra(c, pb)) < 0) {
1370                 av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
1371                         "read the mfra (may be a live ismv)\n");
1372             }
1373         } else {
1374             av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
1375                     "seekable, can not look for mfra\n");
1376         }
1377     }
1378     c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
1379     av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
1380     c->frag_index.current = update_frag_index(c, c->fragment.moof_offset);
1381     return mov_read_default(c, pb, atom);
1382 }
1383
1384 static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
1385 {
1386     if (time) {
1387         if(time >= 2082844800)
1388             time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
1389
1390         if ((int64_t)(time * 1000000ULL) / 1000000 != time) {
1391             av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n");
1392             return;
1393         }
1394
1395         avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
1396     }
1397 }
1398
1399 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1400 {
1401     AVStream *st;
1402     MOVStreamContext *sc;
1403     int version;
1404     char language[4] = {0};
1405     unsigned lang;
1406     int64_t creation_time;
1407
1408     if (c->fc->nb_streams < 1)
1409         return 0;
1410     st = c->fc->streams[c->fc->nb_streams-1];
1411     sc = st->priv_data;
1412
1413     if (sc->time_scale) {
1414         av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
1415         return AVERROR_INVALIDDATA;
1416     }
1417
1418     version = avio_r8(pb);
1419     if (version > 1) {
1420         avpriv_request_sample(c->fc, "Version %d", version);
1421         return AVERROR_PATCHWELCOME;
1422     }
1423     avio_rb24(pb); /* flags */
1424     if (version == 1) {
1425         creation_time = avio_rb64(pb);
1426         avio_rb64(pb);
1427     } else {
1428         creation_time = avio_rb32(pb);
1429         avio_rb32(pb); /* modification time */
1430     }
1431     mov_metadata_creation_time(&st->metadata, creation_time);
1432
1433     sc->time_scale = avio_rb32(pb);
1434     if (sc->time_scale <= 0) {
1435         av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale);
1436         sc->time_scale = 1;
1437     }
1438     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1439
1440     lang = avio_rb16(pb); /* language */
1441     if (ff_mov_lang_to_iso639(lang, language))
1442         av_dict_set(&st->metadata, "language", language, 0);
1443     avio_rb16(pb); /* quality */
1444
1445     return 0;
1446 }
1447
1448 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1449 {
1450     int i;
1451     int64_t creation_time;
1452     int version = avio_r8(pb); /* version */
1453     avio_rb24(pb); /* flags */
1454
1455     if (version == 1) {
1456         creation_time = avio_rb64(pb);
1457         avio_rb64(pb);
1458     } else {
1459         creation_time = avio_rb32(pb);
1460         avio_rb32(pb); /* modification time */
1461     }
1462     mov_metadata_creation_time(&c->fc->metadata, creation_time);
1463     c->time_scale = avio_rb32(pb); /* time scale */
1464     if (c->time_scale <= 0) {
1465         av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale);
1466         c->time_scale = 1;
1467     }
1468     av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
1469
1470     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
1471     // set the AVCodecContext duration because the duration of individual tracks
1472     // may be inaccurate
1473     if (c->time_scale > 0 && !c->trex_data)
1474         c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
1475     avio_rb32(pb); /* preferred scale */
1476
1477     avio_rb16(pb); /* preferred volume */
1478
1479     avio_skip(pb, 10); /* reserved */
1480
1481     /* movie display matrix, store it in main context and use it later on */
1482     for (i = 0; i < 3; i++) {
1483         c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
1484         c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
1485         c->movie_display_matrix[i][2] = avio_rb32(pb); //  2.30 fixed point
1486     }
1487
1488     avio_rb32(pb); /* preview time */
1489     avio_rb32(pb); /* preview duration */
1490     avio_rb32(pb); /* poster time */
1491     avio_rb32(pb); /* selection time */
1492     avio_rb32(pb); /* selection duration */
1493     avio_rb32(pb); /* current time */
1494     avio_rb32(pb); /* next track ID */
1495
1496     return 0;
1497 }
1498
1499 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1500 {
1501     AVStream *st;
1502     int little_endian;
1503
1504     if (c->fc->nb_streams < 1)
1505         return 0;
1506     st = c->fc->streams[c->fc->nb_streams-1];
1507
1508     little_endian = avio_rb16(pb) & 0xFF;
1509     av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
1510     if (little_endian == 1) {
1511         switch (st->codecpar->codec_id) {
1512         case AV_CODEC_ID_PCM_S24BE:
1513             st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
1514             break;
1515         case AV_CODEC_ID_PCM_S32BE:
1516             st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
1517             break;
1518         case AV_CODEC_ID_PCM_F32BE:
1519             st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
1520             break;
1521         case AV_CODEC_ID_PCM_F64BE:
1522             st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
1523             break;
1524         default:
1525             break;
1526         }
1527     }
1528     return 0;
1529 }
1530
1531 static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1532 {
1533     AVStream *st;
1534     char color_parameter_type[5] = { 0 };
1535     uint16_t color_primaries, color_trc, color_matrix;
1536     int ret;
1537
1538     if (c->fc->nb_streams < 1)
1539         return 0;
1540     st = c->fc->streams[c->fc->nb_streams - 1];
1541
1542     ret = ffio_read_size(pb, color_parameter_type, 4);
1543     if (ret < 0)
1544         return ret;
1545     if (strncmp(color_parameter_type, "nclx", 4) &&
1546         strncmp(color_parameter_type, "nclc", 4)) {
1547         av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
1548                color_parameter_type);
1549         return 0;
1550     }
1551
1552     color_primaries = avio_rb16(pb);
1553     color_trc = avio_rb16(pb);
1554     color_matrix = avio_rb16(pb);
1555
1556     av_log(c->fc, AV_LOG_TRACE,
1557            "%s: pri %d trc %d matrix %d",
1558            color_parameter_type, color_primaries, color_trc, color_matrix);
1559
1560     if (!strncmp(color_parameter_type, "nclx", 4)) {
1561         uint8_t color_range = avio_r8(pb) >> 7;
1562         av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
1563         if (color_range)
1564             st->codecpar->color_range = AVCOL_RANGE_JPEG;
1565         else
1566             st->codecpar->color_range = AVCOL_RANGE_MPEG;
1567     }
1568
1569     if (!av_color_primaries_name(color_primaries))
1570         color_primaries = AVCOL_PRI_UNSPECIFIED;
1571     if (!av_color_transfer_name(color_trc))
1572         color_trc = AVCOL_TRC_UNSPECIFIED;
1573     if (!av_color_space_name(color_matrix))
1574         color_matrix = AVCOL_SPC_UNSPECIFIED;
1575
1576     st->codecpar->color_primaries = color_primaries;
1577     st->codecpar->color_trc       = color_trc;
1578     st->codecpar->color_space     = color_matrix;
1579     av_log(c->fc, AV_LOG_TRACE, "\n");
1580
1581     return 0;
1582 }
1583
1584 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1585 {
1586     AVStream *st;
1587     unsigned mov_field_order;
1588     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
1589
1590     if (c->fc->nb_streams < 1) // will happen with jp2 files
1591         return 0;
1592     st = c->fc->streams[c->fc->nb_streams-1];
1593     if (atom.size < 2)
1594         return AVERROR_INVALIDDATA;
1595     mov_field_order = avio_rb16(pb);
1596     if ((mov_field_order & 0xFF00) == 0x0100)
1597         decoded_field_order = AV_FIELD_PROGRESSIVE;
1598     else if ((mov_field_order & 0xFF00) == 0x0200) {
1599         switch (mov_field_order & 0xFF) {
1600         case 0x01: decoded_field_order = AV_FIELD_TT;
1601                    break;
1602         case 0x06: decoded_field_order = AV_FIELD_BB;
1603                    break;
1604         case 0x09: decoded_field_order = AV_FIELD_TB;
1605                    break;
1606         case 0x0E: decoded_field_order = AV_FIELD_BT;
1607                    break;
1608         }
1609     }
1610     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
1611         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
1612     }
1613     st->codecpar->field_order = decoded_field_order;
1614
1615     return 0;
1616 }
1617
1618 static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
1619 {
1620     int err = 0;
1621     uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
1622     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
1623         return AVERROR_INVALIDDATA;
1624     if ((err = av_reallocp(&par->extradata, size)) < 0) {
1625         par->extradata_size = 0;
1626         return err;
1627     }
1628     par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
1629     return 0;
1630 }
1631
1632 /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
1633 static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1634                                         AVCodecParameters *par, uint8_t *buf)
1635 {
1636     int64_t result = atom.size;
1637     int err;
1638
1639     AV_WB32(buf    , atom.size + 8);
1640     AV_WL32(buf + 4, atom.type);
1641     err = ffio_read_size(pb, buf + 8, atom.size);
1642     if (err < 0) {
1643         par->extradata_size -= atom.size;
1644         return err;
1645     } else if (err < atom.size) {
1646         av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
1647         par->extradata_size -= atom.size - err;
1648         result = err;
1649     }
1650     memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1651     return result;
1652 }
1653
1654 /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
1655 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
1656                               enum AVCodecID codec_id)
1657 {
1658     AVStream *st;
1659     uint64_t original_size;
1660     int err;
1661
1662     if (c->fc->nb_streams < 1) // will happen with jp2 files
1663         return 0;
1664     st = c->fc->streams[c->fc->nb_streams-1];
1665
1666     if (st->codecpar->codec_id != codec_id)
1667         return 0; /* unexpected codec_id - don't mess with extradata */
1668
1669     original_size = st->codecpar->extradata_size;
1670     err = mov_realloc_extradata(st->codecpar, atom);
1671     if (err)
1672         return err;
1673
1674     err =  mov_read_atom_into_extradata(c, pb, atom, st->codecpar,  st->codecpar->extradata + original_size);
1675     if (err < 0)
1676         return err;
1677     return 0; // Note: this is the original behavior to ignore truncation.
1678 }
1679
1680 /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
1681 static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1682 {
1683     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
1684 }
1685
1686 static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1687 {
1688     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
1689 }
1690
1691 static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1692 {
1693     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
1694 }
1695
1696 static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1697 {
1698     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
1699 }
1700
1701 static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1702 {
1703     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
1704     if(ret == 0)
1705         ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
1706     return ret;
1707 }
1708
1709 static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1710 {
1711     int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
1712
1713     if (!ret && c->fc->nb_streams >= 1) {
1714         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1715         if (par->extradata_size >= 40) {
1716             par->height = AV_RB16(&par->extradata[36]);
1717             par->width  = AV_RB16(&par->extradata[38]);
1718         }
1719     }
1720     return ret;
1721 }
1722
1723 static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1724 {
1725     if (c->fc->nb_streams >= 1) {
1726         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1727         if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
1728             par->codec_id == AV_CODEC_ID_H264 &&
1729             atom.size > 11) {
1730             int cid;
1731             avio_skip(pb, 10);
1732             cid = avio_rb16(pb);
1733             /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
1734             if (cid == 0xd4d || cid == 0xd4e)
1735                 par->width = 1440;
1736             return 0;
1737         } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
1738                     par->codec_tag == MKTAG('A', 'V', 'j', '2') ||
1739                     par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
1740                    atom.size >= 24) {
1741             int num, den;
1742             avio_skip(pb, 12);
1743             num = avio_rb32(pb);
1744             den = avio_rb32(pb);
1745             if (num <= 0 || den <= 0)
1746                 return 0;
1747             switch (avio_rb32(pb)) {
1748             case 2:
1749                 if (den >= INT_MAX / 2)
1750                     return 0;
1751                 den *= 2;
1752             case 1:
1753                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1754                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1755             default:
1756                 return 0;
1757             }
1758         }
1759     }
1760
1761     return mov_read_avid(c, pb, atom);
1762 }
1763
1764 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1765 {
1766     int ret = 0;
1767     int length = 0;
1768     uint64_t original_size;
1769     if (c->fc->nb_streams >= 1) {
1770         AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
1771         if (par->codec_id == AV_CODEC_ID_H264)
1772             return 0;
1773         if (atom.size == 16) {
1774             original_size = par->extradata_size;
1775             ret = mov_realloc_extradata(par, atom);
1776             if (!ret) {
1777                 length =  mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
1778                 if (length == atom.size) {
1779                     const uint8_t range_value = par->extradata[original_size + 19];
1780                     switch (range_value) {
1781                     case 1:
1782                         par->color_range = AVCOL_RANGE_MPEG;
1783                         break;
1784                     case 2:
1785                         par->color_range = AVCOL_RANGE_JPEG;
1786                         break;
1787                     default:
1788                         av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1789                         break;
1790                     }
1791                     ff_dlog(c, "color_range: %d\n", par->color_range);
1792                 } else {
1793                   /* For some reason the whole atom was not added to the extradata */
1794                   av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1795                 }
1796             } else {
1797                 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1798             }
1799         } else {
1800             av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1801         }
1802     }
1803
1804     return ret;
1805 }
1806
1807 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1808 {
1809     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1810 }
1811
1812 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1813 {
1814     AVStream *st;
1815     int ret;
1816
1817     if (c->fc->nb_streams < 1)
1818         return 0;
1819     st = c->fc->streams[c->fc->nb_streams-1];
1820
1821     if ((uint64_t)atom.size > (1<<30))
1822         return AVERROR_INVALIDDATA;
1823
1824     if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
1825         st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
1826         st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
1827         // pass all frma atom to codec, needed at least for QDMC and QDM2
1828         av_freep(&st->codecpar->extradata);
1829         ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1830         if (ret < 0)
1831             return ret;
1832     } else if (atom.size > 8) { /* to read frma, esds atoms */
1833         if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1834             uint64_t buffer;
1835             ret = ffio_ensure_seekback(pb, 8);
1836             if (ret < 0)
1837                 return ret;
1838             buffer = avio_rb64(pb);
1839             atom.size -= 8;
1840             if (  (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1841                 && buffer >> 32 <= atom.size
1842                 && buffer >> 32 >= 8) {
1843                 avio_skip(pb, -8);
1844                 atom.size += 8;
1845             } else if (!st->codecpar->extradata_size) {
1846 #define ALAC_EXTRADATA_SIZE 36
1847                 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1848                 if (!st->codecpar->extradata)
1849                     return AVERROR(ENOMEM);
1850                 st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
1851                 AV_WB32(st->codecpar->extradata    , ALAC_EXTRADATA_SIZE);
1852                 AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
1853                 AV_WB64(st->codecpar->extradata + 12, buffer);
1854                 avio_read(pb, st->codecpar->extradata + 20, 16);
1855                 avio_skip(pb, atom.size - 24);
1856                 return 0;
1857             }
1858         }
1859         if ((ret = mov_read_default(c, pb, atom)) < 0)
1860             return ret;
1861     } else
1862         avio_skip(pb, atom.size);
1863     return 0;
1864 }
1865
1866 /**
1867  * This function reads atom content and puts data in extradata without tag
1868  * nor size unlike mov_read_extradata.
1869  */
1870 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1871 {
1872     AVStream *st;
1873     int ret;
1874
1875     if (c->fc->nb_streams < 1)
1876         return 0;
1877     st = c->fc->streams[c->fc->nb_streams-1];
1878
1879     if ((uint64_t)atom.size > (1<<30))
1880         return AVERROR_INVALIDDATA;
1881
1882     if (atom.size >= 10) {
1883         // Broken files created by legacy versions of libavformat will
1884         // wrap a whole fiel atom inside of a glbl atom.
1885         unsigned size = avio_rb32(pb);
1886         unsigned type = avio_rl32(pb);
1887         avio_seek(pb, -8, SEEK_CUR);
1888         if (type == MKTAG('f','i','e','l') && size == atom.size)
1889             return mov_read_default(c, pb, atom);
1890     }
1891     if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
1892         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1893         return 0;
1894     }
1895     av_freep(&st->codecpar->extradata);
1896     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
1897     if (ret < 0)
1898         return ret;
1899
1900     return 0;
1901 }
1902
1903 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1904 {
1905     AVStream *st;
1906     uint8_t profile_level;
1907     int ret;
1908
1909     if (c->fc->nb_streams < 1)
1910         return 0;
1911     st = c->fc->streams[c->fc->nb_streams-1];
1912
1913     if (atom.size >= (1<<28) || atom.size < 7)
1914         return AVERROR_INVALIDDATA;
1915
1916     profile_level = avio_r8(pb);
1917     if ((profile_level & 0xf0) != 0xc0)
1918         return 0;
1919
1920     avio_seek(pb, 6, SEEK_CUR);
1921     av_freep(&st->codecpar->extradata);
1922     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
1923     if (ret < 0)
1924         return ret;
1925
1926     return 0;
1927 }
1928
1929 /**
1930  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1931  * but can have extradata appended at the end after the 40 bytes belonging
1932  * to the struct.
1933  */
1934 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1935 {
1936     AVStream *st;
1937     int ret;
1938
1939     if (c->fc->nb_streams < 1)
1940         return 0;
1941     if (atom.size <= 40)
1942         return 0;
1943     st = c->fc->streams[c->fc->nb_streams-1];
1944
1945     if ((uint64_t)atom.size > (1<<30))
1946         return AVERROR_INVALIDDATA;
1947
1948     avio_skip(pb, 40);
1949     av_freep(&st->codecpar->extradata);
1950     ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
1951     if (ret < 0)
1952         return ret;
1953
1954     return 0;
1955 }
1956
1957 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1958 {
1959     AVStream *st;
1960     MOVStreamContext *sc;
1961     unsigned int i, entries;
1962
1963     if (c->fc->nb_streams < 1)
1964         return 0;
1965     st = c->fc->streams[c->fc->nb_streams-1];
1966     sc = st->priv_data;
1967
1968     avio_r8(pb); /* version */
1969     avio_rb24(pb); /* flags */
1970
1971     entries = avio_rb32(pb);
1972
1973     if (!entries)
1974         return 0;
1975
1976     if (sc->chunk_offsets)
1977         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1978     av_free(sc->chunk_offsets);
1979     sc->chunk_count = 0;
1980     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1981     if (!sc->chunk_offsets)
1982         return AVERROR(ENOMEM);
1983     sc->chunk_count = entries;
1984
1985     if      (atom.type == MKTAG('s','t','c','o'))
1986         for (i = 0; i < entries && !pb->eof_reached; i++)
1987             sc->chunk_offsets[i] = avio_rb32(pb);
1988     else if (atom.type == MKTAG('c','o','6','4'))
1989         for (i = 0; i < entries && !pb->eof_reached; i++)
1990             sc->chunk_offsets[i] = avio_rb64(pb);
1991     else
1992         return AVERROR_INVALIDDATA;
1993
1994     sc->chunk_count = i;
1995
1996     if (pb->eof_reached) {
1997         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STCO atom\n");
1998         return AVERROR_EOF;
1999     }
2000
2001     return 0;
2002 }
2003
2004 static int mov_codec_id(AVStream *st, uint32_t format)
2005 {
2006     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
2007
2008     if (id <= 0 &&
2009         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
2010          (format & 0xFFFF) == 'T' + ('S' << 8)))
2011         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
2012
2013     if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
2014         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2015     } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
2016                /* skip old ASF MPEG-4 tag */
2017                format && format != MKTAG('m','p','4','s')) {
2018         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2019         if (id <= 0)
2020             id = ff_codec_get_id(ff_codec_bmp_tags, format);
2021         if (id > 0)
2022             st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
2023         else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
2024                     (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
2025                     st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
2026             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
2027             if (id > 0)
2028                 st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
2029         }
2030     }
2031
2032     st->codecpar->codec_tag = format;
2033
2034     return id;
2035 }
2036
2037 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
2038                                  AVStream *st, MOVStreamContext *sc)
2039 {
2040     uint8_t codec_name[32] = { 0 };
2041     int64_t stsd_start;
2042     unsigned int len;
2043
2044     /* The first 16 bytes of the video sample description are already
2045      * read in ff_mov_read_stsd_entries() */
2046     stsd_start = avio_tell(pb) - 16;
2047
2048     avio_rb16(pb); /* version */
2049     avio_rb16(pb); /* revision level */
2050     avio_rb32(pb); /* vendor */
2051     avio_rb32(pb); /* temporal quality */
2052     avio_rb32(pb); /* spatial quality */
2053
2054     st->codecpar->width  = avio_rb16(pb); /* width */
2055     st->codecpar->height = avio_rb16(pb); /* height */
2056
2057     avio_rb32(pb); /* horiz resolution */
2058     avio_rb32(pb); /* vert resolution */
2059     avio_rb32(pb); /* data size, always 0 */
2060     avio_rb16(pb); /* frames per samples */
2061
2062     len = avio_r8(pb); /* codec name, pascal string */
2063     if (len > 31)
2064         len = 31;
2065     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
2066     if (len < 31)
2067         avio_skip(pb, 31 - len);
2068
2069     if (codec_name[0])
2070         av_dict_set(&st->metadata, "encoder", codec_name, 0);
2071
2072     /* codec_tag YV12 triggers an UV swap in rawdec.c */
2073     if (!strncmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
2074         st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
2075         st->codecpar->width &= ~1;
2076         st->codecpar->height &= ~1;
2077     }
2078     /* Flash Media Server uses tag H.263 with Sorenson Spark */
2079     if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
2080         !strncmp(codec_name, "Sorenson H263", 13))
2081         st->codecpar->codec_id = AV_CODEC_ID_FLV1;
2082
2083     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
2084
2085     avio_seek(pb, stsd_start, SEEK_SET);
2086
2087     if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
2088         st->codecpar->bits_per_coded_sample &= 0x1F;
2089         sc->has_palette = 1;
2090     }
2091 }
2092
2093 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
2094                                  AVStream *st, MOVStreamContext *sc)
2095 {
2096     int bits_per_sample, flags;
2097     uint16_t version = avio_rb16(pb);
2098     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
2099
2100     avio_rb16(pb); /* revision level */
2101     avio_rb32(pb); /* vendor */
2102
2103     st->codecpar->channels              = avio_rb16(pb); /* channel count */
2104     st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
2105     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
2106
2107     sc->audio_cid = avio_rb16(pb);
2108     avio_rb16(pb); /* packet size = 0 */
2109
2110     st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
2111
2112     // Read QT version 1 fields. In version 0 these do not exist.
2113     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
2114     if (!c->isom ||
2115         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
2116
2117         if (version == 1) {
2118             sc->samples_per_frame = avio_rb32(pb);
2119             avio_rb32(pb); /* bytes per packet */
2120             sc->bytes_per_frame = avio_rb32(pb);
2121             avio_rb32(pb); /* bytes per sample */
2122         } else if (version == 2) {
2123             avio_rb32(pb); /* sizeof struct only */
2124             st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
2125             st->codecpar->channels    = avio_rb32(pb);
2126             avio_rb32(pb); /* always 0x7F000000 */
2127             st->codecpar->bits_per_coded_sample = avio_rb32(pb);
2128
2129             flags = avio_rb32(pb); /* lpcm format specific flag */
2130             sc->bytes_per_frame   = avio_rb32(pb);
2131             sc->samples_per_frame = avio_rb32(pb);
2132             if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
2133                 st->codecpar->codec_id =
2134                     ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
2135                                              flags);
2136         }
2137         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
2138             /* can't correctly handle variable sized packet as audio unit */
2139             switch (st->codecpar->codec_id) {
2140             case AV_CODEC_ID_MP2:
2141             case AV_CODEC_ID_MP3:
2142                 st->need_parsing = AVSTREAM_PARSE_FULL;
2143                 break;
2144             }
2145         }
2146     }
2147
2148     if (sc->format == 0) {
2149         if (st->codecpar->bits_per_coded_sample == 8)
2150             st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
2151         else if (st->codecpar->bits_per_coded_sample == 16)
2152             st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
2153     }
2154
2155     switch (st->codecpar->codec_id) {
2156     case AV_CODEC_ID_PCM_S8:
2157     case AV_CODEC_ID_PCM_U8:
2158         if (st->codecpar->bits_per_coded_sample == 16)
2159             st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
2160         break;
2161     case AV_CODEC_ID_PCM_S16LE:
2162     case AV_CODEC_ID_PCM_S16BE:
2163         if (st->codecpar->bits_per_coded_sample == 8)
2164             st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
2165         else if (st->codecpar->bits_per_coded_sample == 24)
2166             st->codecpar->codec_id =
2167                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2168                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
2169         else if (st->codecpar->bits_per_coded_sample == 32)
2170              st->codecpar->codec_id =
2171                 st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
2172                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
2173         break;
2174     /* set values for old format before stsd version 1 appeared */
2175     case AV_CODEC_ID_MACE3:
2176         sc->samples_per_frame = 6;
2177         sc->bytes_per_frame   = 2 * st->codecpar->channels;
2178         break;
2179     case AV_CODEC_ID_MACE6:
2180         sc->samples_per_frame = 6;
2181         sc->bytes_per_frame   = 1 * st->codecpar->channels;
2182         break;
2183     case AV_CODEC_ID_ADPCM_IMA_QT:
2184         sc->samples_per_frame = 64;
2185         sc->bytes_per_frame   = 34 * st->codecpar->channels;
2186         break;
2187     case AV_CODEC_ID_GSM:
2188         sc->samples_per_frame = 160;
2189         sc->bytes_per_frame   = 33;
2190         break;
2191     default:
2192         break;
2193     }
2194
2195     bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
2196     if (bits_per_sample) {
2197         st->codecpar->bits_per_coded_sample = bits_per_sample;
2198         sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
2199     }
2200 }
2201
2202 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
2203                                     AVStream *st, MOVStreamContext *sc,
2204                                     int64_t size)
2205 {
2206     // ttxt stsd contains display flags, justification, background
2207     // color, fonts, and default styles, so fake an atom to read it
2208     MOVAtom fake_atom = { .size = size };
2209     // mp4s contains a regular esds atom
2210     if (st->codecpar->codec_tag != AV_RL32("mp4s"))
2211         mov_read_glbl(c, pb, fake_atom);
2212     st->codecpar->width  = sc->width;
2213     st->codecpar->height = sc->height;
2214 }
2215
2216 static uint32_t yuv_to_rgba(uint32_t ycbcr)
2217 {
2218     uint8_t r, g, b;
2219     int y, cb, cr;
2220
2221     y  = (ycbcr >> 16) & 0xFF;
2222     cr = (ycbcr >> 8)  & 0xFF;
2223     cb =  ycbcr        & 0xFF;
2224
2225     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
2226     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
2227     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
2228
2229     return (r << 16) | (g << 8) | b;
2230 }
2231
2232 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
2233 {
2234     char buf[256] = {0};
2235     uint8_t *src = st->codecpar->extradata;
2236     int i;
2237
2238     if (st->codecpar->extradata_size != 64)
2239         return 0;
2240
2241     if (st->codecpar->width > 0 &&  st->codecpar->height > 0)
2242         snprintf(buf, sizeof(buf), "size: %dx%d\n",
2243                  st->codecpar->width, st->codecpar->height);
2244     av_strlcat(buf, "palette: ", sizeof(buf));
2245
2246     for (i = 0; i < 16; i++) {
2247         uint32_t yuv = AV_RB32(src + i * 4);
2248         uint32_t rgba = yuv_to_rgba(yuv);
2249
2250         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
2251     }
2252
2253     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
2254         return 0;
2255
2256     av_freep(&st->codecpar->extradata);
2257     st->codecpar->extradata_size = 0;
2258     st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
2259     if (!st->codecpar->extradata)
2260         return AVERROR(ENOMEM);
2261     st->codecpar->extradata_size = strlen(buf);
2262     memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
2263
2264     return 0;
2265 }
2266
2267 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2268                                 AVStream *st, MOVStreamContext *sc,
2269                                 int64_t size)
2270 {
2271     int ret;
2272
2273     if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
2274         if ((int)size != size)
2275             return AVERROR(ENOMEM);
2276
2277         ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
2278         if (ret < 0)
2279             return ret;
2280         if (size > 16) {
2281             MOVStreamContext *tmcd_ctx = st->priv_data;
2282             int val;
2283             val = AV_RB32(st->codecpar->extradata + 4);
2284             tmcd_ctx->tmcd_flags = val;
2285             st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
2286             st->avg_frame_rate.den = 1;
2287 #if FF_API_LAVF_AVCTX
2288 FF_DISABLE_DEPRECATION_WARNINGS
2289             st->codec->time_base = av_inv_q(st->avg_frame_rate);
2290 FF_ENABLE_DEPRECATION_WARNINGS
2291 #endif
2292             /* adjust for per frame dur in counter mode */
2293             if (tmcd_ctx->tmcd_flags & 0x0008) {
2294                 int timescale = AV_RB32(st->codecpar->extradata + 8);
2295                 int framedur = AV_RB32(st->codecpar->extradata + 12);
2296                 st->avg_frame_rate.num *= timescale;
2297                 st->avg_frame_rate.den *= framedur;
2298 #if FF_API_LAVF_AVCTX
2299 FF_DISABLE_DEPRECATION_WARNINGS
2300                 st->codec->time_base.den *= timescale;
2301                 st->codec->time_base.num *= framedur;
2302 FF_ENABLE_DEPRECATION_WARNINGS
2303 #endif
2304             }
2305             if (size > 30) {
2306                 uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
2307                 uint32_t format = AV_RB32(st->codecpar->extradata + 22);
2308                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2309                     uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
2310                     if (str_size > 0 && size >= (int)str_size + 26) {
2311                         char *reel_name = av_malloc(str_size + 1);
2312                         if (!reel_name)
2313                             return AVERROR(ENOMEM);
2314                         memcpy(reel_name, st->codecpar->extradata + 30, str_size);
2315                         reel_name[str_size] = 0; /* Add null terminator */
2316                         /* don't add reel_name if emtpy string */
2317                         if (*reel_name == 0) {
2318                             av_free(reel_name);
2319                         } else {
2320                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
2321                         }
2322                     }
2323                 }
2324             }
2325         }
2326     } else {
2327         /* other codec type, just skip (rtp, mp4s ...) */
2328         avio_skip(pb, size);
2329     }
2330     return 0;
2331 }
2332
2333 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2334                                    AVStream *st, MOVStreamContext *sc)
2335 {
2336     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2337         !st->codecpar->sample_rate && sc->time_scale > 1)
2338         st->codecpar->sample_rate = sc->time_scale;
2339
2340     /* special codec parameters handling */
2341     switch (st->codecpar->codec_id) {
2342 #if CONFIG_DV_DEMUXER
2343     case AV_CODEC_ID_DVAUDIO:
2344         c->dv_fctx = avformat_alloc_context();
2345         if (!c->dv_fctx) {
2346             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2347             return AVERROR(ENOMEM);
2348         }
2349         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2350         if (!c->dv_demux) {
2351             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2352             return AVERROR(ENOMEM);
2353         }
2354         sc->dv_audio_container = 1;
2355         st->codecpar->codec_id    = AV_CODEC_ID_PCM_S16LE;
2356         break;
2357 #endif
2358     /* no ifdef since parameters are always those */
2359     case AV_CODEC_ID_QCELP:
2360         st->codecpar->channels = 1;
2361         // force sample rate for qcelp when not stored in mov
2362         if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
2363             st->codecpar->sample_rate = 8000;
2364         // FIXME: Why is the following needed for some files?
2365         sc->samples_per_frame = 160;
2366         if (!sc->bytes_per_frame)
2367             sc->bytes_per_frame = 35;
2368         break;
2369     case AV_CODEC_ID_AMR_NB:
2370         st->codecpar->channels    = 1;
2371         /* force sample rate for amr, stsd in 3gp does not store sample rate */
2372         st->codecpar->sample_rate = 8000;
2373         break;
2374     case AV_CODEC_ID_AMR_WB:
2375         st->codecpar->channels    = 1;
2376         st->codecpar->sample_rate = 16000;
2377         break;
2378     case AV_CODEC_ID_MP2:
2379     case AV_CODEC_ID_MP3:
2380         /* force type after stsd for m1a hdlr */
2381         st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
2382         break;
2383     case AV_CODEC_ID_GSM:
2384     case AV_CODEC_ID_ADPCM_MS:
2385     case AV_CODEC_ID_ADPCM_IMA_WAV:
2386     case AV_CODEC_ID_ILBC:
2387     case AV_CODEC_ID_MACE3:
2388     case AV_CODEC_ID_MACE6:
2389     case AV_CODEC_ID_QDM2:
2390         st->codecpar->block_align = sc->bytes_per_frame;
2391         break;
2392     case AV_CODEC_ID_ALAC:
2393         if (st->codecpar->extradata_size == 36) {
2394             st->codecpar->channels    = AV_RB8 (st->codecpar->extradata + 21);
2395             st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
2396         }
2397         break;
2398     case AV_CODEC_ID_AC3:
2399     case AV_CODEC_ID_EAC3:
2400     case AV_CODEC_ID_MPEG1VIDEO:
2401     case AV_CODEC_ID_VC1:
2402     case AV_CODEC_ID_VP8:
2403     case AV_CODEC_ID_VP9:
2404         st->need_parsing = AVSTREAM_PARSE_FULL;
2405         break;
2406     default:
2407         break;
2408     }
2409     return 0;
2410 }
2411
2412 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2413                                   int codec_tag, int format,
2414                                   int64_t size)
2415 {
2416     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2417
2418     if (codec_tag &&
2419          (codec_tag != format &&
2420           // AVID 1:1 samples with differing data format and codec tag exist
2421           (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
2422           // prores is allowed to have differing data format and codec tag
2423           codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
2424           // so is dv (sigh)
2425           codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
2426           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2427                                  : codec_tag != MKTAG('j','p','e','g')))) {
2428         /* Multiple fourcc, we skip JPEG. This is not correct, we should
2429          * export it as a separate AVStream but this needs a few changes
2430          * in the MOV demuxer, patch welcome. */
2431
2432         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2433         avio_skip(pb, size);
2434         return 1;
2435     }
2436
2437     return 0;
2438 }
2439
2440 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2441 {
2442     AVStream *st;
2443     MOVStreamContext *sc;
2444     int pseudo_stream_id;
2445
2446     av_assert0 (c->fc->nb_streams >= 1);
2447     st = c->fc->streams[c->fc->nb_streams-1];
2448     sc = st->priv_data;
2449
2450     for (pseudo_stream_id = 0;
2451          pseudo_stream_id < entries && !pb->eof_reached;
2452          pseudo_stream_id++) {
2453         //Parsing Sample description table
2454         enum AVCodecID id;
2455         int ret, dref_id = 1;
2456         MOVAtom a = { AV_RL32("stsd") };
2457         int64_t start_pos = avio_tell(pb);
2458         int64_t size    = avio_rb32(pb); /* size */
2459         uint32_t format = avio_rl32(pb); /* data format */
2460
2461         if (size >= 16) {
2462             avio_rb32(pb); /* reserved */
2463             avio_rb16(pb); /* reserved */
2464             dref_id = avio_rb16(pb);
2465         } else if (size <= 7) {
2466             av_log(c->fc, AV_LOG_ERROR,
2467                    "invalid size %"PRId64" in stsd\n", size);
2468             return AVERROR_INVALIDDATA;
2469         }
2470
2471         if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
2472                                    size - (avio_tell(pb) - start_pos))) {
2473             sc->stsd_count++;
2474             continue;
2475         }
2476
2477         sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
2478         sc->dref_id= dref_id;
2479         sc->format = format;
2480
2481         id = mov_codec_id(st, format);
2482
2483         av_log(c->fc, AV_LOG_TRACE,
2484                "size=%"PRId64" 4CC=%s codec_type=%d\n", size,
2485                av_fourcc2str(format), st->codecpar->codec_type);
2486
2487         if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
2488             st->codecpar->codec_id = id;
2489             mov_parse_stsd_video(c, pb, st, sc);
2490         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
2491             st->codecpar->codec_id = id;
2492             mov_parse_stsd_audio(c, pb, st, sc);
2493             if (st->codecpar->sample_rate < 0) {
2494                 av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
2495                 return AVERROR_INVALIDDATA;
2496             }
2497         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
2498             st->codecpar->codec_id = id;
2499             mov_parse_stsd_subtitle(c, pb, st, sc,
2500                                     size - (avio_tell(pb) - start_pos));
2501         } else {
2502             ret = mov_parse_stsd_data(c, pb, st, sc,
2503                                       size - (avio_tell(pb) - start_pos));
2504             if (ret < 0)
2505                 return ret;
2506         }
2507         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2508         a.size = size - (avio_tell(pb) - start_pos);
2509         if (a.size > 8) {
2510             if ((ret = mov_read_default(c, pb, a)) < 0)
2511                 return ret;
2512         } else if (a.size > 0)
2513             avio_skip(pb, a.size);
2514
2515         if (sc->extradata && st->codecpar->extradata) {
2516             int extra_size = st->codecpar->extradata_size;
2517
2518             /* Move the current stream extradata to the stream context one. */
2519             sc->extradata_size[pseudo_stream_id] = extra_size;
2520             sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
2521             if (!sc->extradata[pseudo_stream_id])
2522                 return AVERROR(ENOMEM);
2523             memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
2524             av_freep(&st->codecpar->extradata);
2525             st->codecpar->extradata_size = 0;
2526         }
2527         sc->stsd_count++;
2528     }
2529
2530     if (pb->eof_reached) {
2531         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSD atom\n");
2532         return AVERROR_EOF;
2533     }
2534
2535     return 0;
2536 }
2537
2538 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2539 {
2540     AVStream *st;
2541     MOVStreamContext *sc;
2542     int ret, entries;
2543
2544     if (c->fc->nb_streams < 1)
2545         return 0;
2546     st = c->fc->streams[c->fc->nb_streams - 1];
2547     sc = st->priv_data;
2548
2549     avio_r8(pb); /* version */
2550     avio_rb24(pb); /* flags */
2551     entries = avio_rb32(pb);
2552
2553     if (entries <= 0) {
2554         av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
2555         return AVERROR_INVALIDDATA;
2556     }
2557
2558     if (sc->extradata) {
2559         av_log(c->fc, AV_LOG_ERROR,
2560                "Duplicate stsd found in this track.\n");
2561         return AVERROR_INVALIDDATA;
2562     }
2563
2564     /* Prepare space for hosting multiple extradata. */
2565     sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
2566     if (!sc->extradata)
2567         return AVERROR(ENOMEM);
2568
2569     sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
2570     if (!sc->extradata_size) {
2571         ret = AVERROR(ENOMEM);
2572         goto fail;
2573     }
2574
2575     ret = ff_mov_read_stsd_entries(c, pb, entries);
2576     if (ret < 0)
2577         goto fail;
2578
2579     /* Restore back the primary extradata. */
2580     av_freep(&st->codecpar->extradata);
2581     st->codecpar->extradata_size = sc->extradata_size[0];
2582     if (sc->extradata_size[0]) {
2583         st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
2584         if (!st->codecpar->extradata)
2585             return AVERROR(ENOMEM);
2586         memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
2587     }
2588
2589     return mov_finalize_stsd_codec(c, pb, st, sc);
2590 fail:
2591     av_freep(&sc->extradata);
2592     av_freep(&sc->extradata_size);
2593     return ret;
2594 }
2595
2596 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2597 {
2598     AVStream *st;
2599     MOVStreamContext *sc;
2600     unsigned int i, entries;
2601
2602     if (c->fc->nb_streams < 1)
2603         return 0;
2604     st = c->fc->streams[c->fc->nb_streams-1];
2605     sc = st->priv_data;
2606
2607     avio_r8(pb); /* version */
2608     avio_rb24(pb); /* flags */
2609
2610     entries = avio_rb32(pb);
2611     if ((uint64_t)entries * 12 + 4 > atom.size)
2612         return AVERROR_INVALIDDATA;
2613
2614     av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
2615
2616     if (!entries)
2617         return 0;
2618     if (sc->stsc_data)
2619         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2620     av_free(sc->stsc_data);
2621     sc->stsc_count = 0;
2622     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2623     if (!sc->stsc_data)
2624         return AVERROR(ENOMEM);
2625
2626     for (i = 0; i < entries && !pb->eof_reached; i++) {
2627         sc->stsc_data[i].first = avio_rb32(pb);
2628         sc->stsc_data[i].count = avio_rb32(pb);
2629         sc->stsc_data[i].id = avio_rb32(pb);
2630     }
2631
2632     sc->stsc_count = i;
2633     for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
2634         if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
2635             (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
2636             sc->stsc_data[i].first < 1 ||
2637             sc->stsc_data[i].count < 1 ||
2638             sc->stsc_data[i].id < 1) {
2639             av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
2640             if (i+1 >= sc->stsc_count || sc->stsc_data[i+1].first < 2)
2641                 return AVERROR_INVALIDDATA;
2642             // We replace this entry by the next valid
2643             sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
2644             sc->stsc_data[i].count = sc->stsc_data[i+1].count;
2645             sc->stsc_data[i].id    = sc->stsc_data[i+1].id;
2646         }
2647     }
2648
2649     if (pb->eof_reached) {
2650         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2651         return AVERROR_EOF;
2652     }
2653
2654     return 0;
2655 }
2656
2657 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2658 {
2659     return index < count - 1;
2660 }
2661
2662 /* Compute the samples value for the stsc entry at the given index. */
2663 static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2664 {
2665     int chunk_count;
2666
2667     if (mov_stsc_index_valid(index, sc->stsc_count))
2668         chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2669     else
2670         chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2671
2672     return sc->stsc_data[index].count * (int64_t)chunk_count;
2673 }
2674
2675 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2676 {
2677     AVStream *st;
2678     MOVStreamContext *sc;
2679     unsigned i, entries;
2680
2681     if (c->fc->nb_streams < 1)
2682         return 0;
2683     st = c->fc->streams[c->fc->nb_streams-1];
2684     sc = st->priv_data;
2685
2686     avio_rb32(pb); // version + flags
2687
2688     entries = avio_rb32(pb);
2689     if (sc->stps_data)
2690         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2691     av_free(sc->stps_data);
2692     sc->stps_count = 0;
2693     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2694     if (!sc->stps_data)
2695         return AVERROR(ENOMEM);
2696
2697     for (i = 0; i < entries && !pb->eof_reached; i++) {
2698         sc->stps_data[i] = avio_rb32(pb);
2699     }
2700
2701     sc->stps_count = i;
2702
2703     if (pb->eof_reached) {
2704         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2705         return AVERROR_EOF;
2706     }
2707
2708     return 0;
2709 }
2710
2711 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2712 {
2713     AVStream *st;
2714     MOVStreamContext *sc;
2715     unsigned int i, entries;
2716
2717     if (c->fc->nb_streams < 1)
2718         return 0;
2719     st = c->fc->streams[c->fc->nb_streams-1];
2720     sc = st->priv_data;
2721
2722     avio_r8(pb); /* version */
2723     avio_rb24(pb); /* flags */
2724
2725     entries = avio_rb32(pb);
2726
2727     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2728
2729     if (!entries)
2730     {
2731         sc->keyframe_absent = 1;
2732         if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2733             st->need_parsing = AVSTREAM_PARSE_HEADERS;
2734         return 0;
2735     }
2736     if (sc->keyframes)
2737         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2738     if (entries >= UINT_MAX / sizeof(int))
2739         return AVERROR_INVALIDDATA;
2740     av_freep(&sc->keyframes);
2741     sc->keyframe_count = 0;
2742     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2743     if (!sc->keyframes)
2744         return AVERROR(ENOMEM);
2745
2746     for (i = 0; i < entries && !pb->eof_reached; i++) {
2747         sc->keyframes[i] = avio_rb32(pb);
2748     }
2749
2750     sc->keyframe_count = i;
2751
2752     if (pb->eof_reached) {
2753         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2754         return AVERROR_EOF;
2755     }
2756
2757     return 0;
2758 }
2759
2760 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2761 {
2762     AVStream *st;
2763     MOVStreamContext *sc;
2764     unsigned int i, entries, sample_size, field_size, num_bytes;
2765     GetBitContext gb;
2766     unsigned char* buf;
2767     int ret;
2768
2769     if (c->fc->nb_streams < 1)
2770         return 0;
2771     st = c->fc->streams[c->fc->nb_streams-1];
2772     sc = st->priv_data;
2773
2774     avio_r8(pb); /* version */
2775     avio_rb24(pb); /* flags */
2776
2777     if (atom.type == MKTAG('s','t','s','z')) {
2778         sample_size = avio_rb32(pb);
2779         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2780             sc->sample_size = sample_size;
2781         sc->stsz_sample_size = sample_size;
2782         field_size = 32;
2783     } else {
2784         sample_size = 0;
2785         avio_rb24(pb); /* reserved */
2786         field_size = avio_r8(pb);
2787     }
2788     entries = avio_rb32(pb);
2789
2790     av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2791
2792     sc->sample_count = entries;
2793     if (sample_size)
2794         return 0;
2795
2796     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2797         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2798         return AVERROR_INVALIDDATA;
2799     }
2800
2801     if (!entries)
2802         return 0;
2803     if (entries >= (UINT_MAX - 4) / field_size)
2804         return AVERROR_INVALIDDATA;
2805     if (sc->sample_sizes)
2806         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2807     av_free(sc->sample_sizes);
2808     sc->sample_count = 0;
2809     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2810     if (!sc->sample_sizes)
2811         return AVERROR(ENOMEM);
2812
2813     num_bytes = (entries*field_size+4)>>3;
2814
2815     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2816     if (!buf) {
2817         av_freep(&sc->sample_sizes);
2818         return AVERROR(ENOMEM);
2819     }
2820
2821     ret = ffio_read_size(pb, buf, num_bytes);
2822     if (ret < 0) {
2823         av_freep(&sc->sample_sizes);
2824         av_free(buf);
2825         return ret;
2826     }
2827
2828     init_get_bits(&gb, buf, 8*num_bytes);
2829
2830     for (i = 0; i < entries && !pb->eof_reached; i++) {
2831         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2832         sc->data_size += sc->sample_sizes[i];
2833     }
2834
2835     sc->sample_count = i;
2836
2837     av_free(buf);
2838
2839     if (pb->eof_reached) {
2840         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2841         return AVERROR_EOF;
2842     }
2843
2844     return 0;
2845 }
2846
2847 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2848 {
2849     AVStream *st;
2850     MOVStreamContext *sc;
2851     unsigned int i, entries, alloc_size = 0;
2852     int64_t duration=0;
2853     int64_t total_sample_count=0;
2854
2855     if (c->fc->nb_streams < 1)
2856         return 0;
2857     st = c->fc->streams[c->fc->nb_streams-1];
2858     sc = st->priv_data;
2859
2860     avio_r8(pb); /* version */
2861     avio_rb24(pb); /* flags */
2862     entries = avio_rb32(pb);
2863
2864     av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2865             c->fc->nb_streams-1, entries);
2866
2867     if (sc->stts_data)
2868         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2869     av_freep(&sc->stts_data);
2870     sc->stts_count = 0;
2871     if (entries >= INT_MAX / sizeof(*sc->stts_data))
2872         return AVERROR(ENOMEM);
2873
2874     for (i = 0; i < entries && !pb->eof_reached; i++) {
2875         int sample_duration;
2876         unsigned int sample_count;
2877         unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
2878         MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2879                                              min_entries * sizeof(*sc->stts_data));
2880         if (!stts_data) {
2881             av_freep(&sc->stts_data);
2882             sc->stts_count = 0;
2883             return AVERROR(ENOMEM);
2884         }
2885         sc->stts_count = min_entries;
2886         sc->stts_data = stts_data;
2887
2888         sample_count=avio_rb32(pb);
2889         sample_duration = avio_rb32(pb);
2890
2891         sc->stts_data[i].count= sample_count;
2892         sc->stts_data[i].duration= sample_duration;
2893
2894         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2895                 sample_count, sample_duration);
2896
2897         if (   i+1 == entries
2898             && i
2899             && sample_count == 1
2900             && total_sample_count > 100
2901             && sample_duration/10 > duration / total_sample_count)
2902             sample_duration = duration / total_sample_count;
2903         duration+=(int64_t)sample_duration*(uint64_t)sample_count;
2904         total_sample_count+=sample_count;
2905     }
2906
2907     sc->stts_count = i;
2908
2909     if (duration > 0 &&
2910         duration <= INT64_MAX - sc->duration_for_fps &&
2911         total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
2912     ) {
2913         sc->duration_for_fps  += duration;
2914         sc->nb_frames_for_fps += total_sample_count;
2915     }
2916
2917     if (pb->eof_reached) {
2918         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2919         return AVERROR_EOF;
2920     }
2921
2922     st->nb_frames= total_sample_count;
2923     if (duration)
2924         st->duration= duration;
2925     sc->track_end = duration;
2926     return 0;
2927 }
2928
2929 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2930 {
2931     if (duration < 0) {
2932         if (duration == INT_MIN) {
2933             av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2934             duration++;
2935         }
2936         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2937     }
2938 }
2939
2940 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2941 {
2942     AVStream *st;
2943     MOVStreamContext *sc;
2944     unsigned int i, entries, ctts_count = 0;
2945
2946     if (c->fc->nb_streams < 1)
2947         return 0;
2948     st = c->fc->streams[c->fc->nb_streams-1];
2949     sc = st->priv_data;
2950
2951     avio_r8(pb); /* version */
2952     avio_rb24(pb); /* flags */
2953     entries = avio_rb32(pb);
2954
2955     av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2956
2957     if (!entries)
2958         return 0;
2959     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2960         return AVERROR_INVALIDDATA;
2961     av_freep(&sc->ctts_data);
2962     sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2963     if (!sc->ctts_data)
2964         return AVERROR(ENOMEM);
2965
2966     for (i = 0; i < entries && !pb->eof_reached; i++) {
2967         int count    =avio_rb32(pb);
2968         int duration =avio_rb32(pb);
2969
2970         if (count <= 0) {
2971             av_log(c->fc, AV_LOG_TRACE,
2972                    "ignoring CTTS entry with count=%d duration=%d\n",
2973                    count, duration);
2974             continue;
2975         }
2976
2977         add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
2978                        count, duration);
2979
2980         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2981                 count, duration);
2982
2983         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2984             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2985             av_freep(&sc->ctts_data);
2986             sc->ctts_count = 0;
2987             return 0;
2988         }
2989
2990         if (i+2<entries)
2991             mov_update_dts_shift(sc, duration);
2992     }
2993
2994     sc->ctts_count = ctts_count;
2995
2996     if (pb->eof_reached) {
2997         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
2998         return AVERROR_EOF;
2999     }
3000
3001     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
3002
3003     return 0;
3004 }
3005
3006 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3007 {
3008     AVStream *st;
3009     MOVStreamContext *sc;
3010     unsigned int i, entries;
3011     uint8_t version;
3012     uint32_t grouping_type;
3013
3014     if (c->fc->nb_streams < 1)
3015         return 0;
3016     st = c->fc->streams[c->fc->nb_streams-1];
3017     sc = st->priv_data;
3018
3019     version = avio_r8(pb); /* version */
3020     avio_rb24(pb); /* flags */
3021     grouping_type = avio_rl32(pb);
3022     if (grouping_type != MKTAG( 'r','a','p',' '))
3023         return 0; /* only support 'rap ' grouping */
3024     if (version == 1)
3025         avio_rb32(pb); /* grouping_type_parameter */
3026
3027     entries = avio_rb32(pb);
3028     if (!entries)
3029         return 0;
3030     if (sc->rap_group)
3031         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3032     av_free(sc->rap_group);
3033     sc->rap_group_count = 0;
3034     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3035     if (!sc->rap_group)
3036         return AVERROR(ENOMEM);
3037
3038     for (i = 0; i < entries && !pb->eof_reached; i++) {
3039         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3040         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3041     }
3042
3043     sc->rap_group_count = i;
3044
3045     if (pb->eof_reached) {
3046         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3047         return AVERROR_EOF;
3048     }
3049
3050     return 0;
3051 }
3052
3053 /**
3054  * Get ith edit list entry (media time, duration).
3055  */
3056 static int get_edit_list_entry(MOVContext *mov,
3057                                const MOVStreamContext *msc,
3058                                unsigned int edit_list_index,
3059                                int64_t *edit_list_media_time,
3060                                int64_t *edit_list_duration,
3061                                int64_t global_timescale)
3062 {
3063     if (edit_list_index == msc->elst_count) {
3064         return 0;
3065     }
3066     *edit_list_media_time = msc->elst_data[edit_list_index].time;
3067     *edit_list_duration = msc->elst_data[edit_list_index].duration;
3068
3069     /* duration is in global timescale units;convert to msc timescale */
3070     if (global_timescale == 0) {
3071       avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3072       return 0;
3073     }
3074     *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3075                                      global_timescale);
3076     return 1;
3077 }
3078
3079 /**
3080  * Find the closest previous frame to the timestamp_pts, in e_old index
3081  * entries. Searching for just any frame / just key frames can be controlled by
3082  * last argument 'flag'.
3083  * Note that if ctts_data is not NULL, we will always search for a key frame
3084  * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3085  * return the first frame of the video.
3086  *
3087  * Here the timestamp_pts is considered to be a presentation timestamp and
3088  * the timestamp of index entries are considered to be decoding timestamps.
3089  *
3090  * Returns 0 if successful in finding a frame, else returns -1.
3091  * Places the found index corresponding output arg.
3092  *
3093  * If ctts_old is not NULL, then refines the searched entry by searching
3094  * backwards from the found timestamp, to find the frame with correct PTS.
3095  *
3096  * Places the found ctts_index and ctts_sample in corresponding output args.
3097  */
3098 static int find_prev_closest_index(AVStream *st,
3099                                    AVIndexEntry *e_old,
3100                                    int nb_old,
3101                                    MOVStts* ctts_data,
3102                                    int64_t ctts_count,
3103                                    int64_t timestamp_pts,
3104                                    int flag,
3105                                    int64_t* index,
3106                                    int64_t* ctts_index,
3107                                    int64_t* ctts_sample)
3108 {
3109     MOVStreamContext *msc = st->priv_data;
3110     AVIndexEntry *e_keep = st->index_entries;
3111     int nb_keep = st->nb_index_entries;
3112     int64_t i = 0;
3113     int64_t index_ctts_count;
3114
3115     av_assert0(index);
3116
3117     // If dts_shift > 0, then all the index timestamps will have to be offset by
3118     // at least dts_shift amount to obtain PTS.
3119     // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3120     if (msc->dts_shift > 0) {
3121         timestamp_pts -= msc->dts_shift;
3122     }
3123
3124     st->index_entries = e_old;
3125     st->nb_index_entries = nb_old;
3126     *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3127
3128     // Keep going backwards in the index entries until the timestamp is the same.
3129     if (*index >= 0) {
3130         for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3131              i--) {
3132             if ((flag & AVSEEK_FLAG_ANY) ||
3133                 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3134                 *index = i - 1;
3135             }
3136         }
3137     }
3138
3139     // If we have CTTS then refine the search, by searching backwards over PTS
3140     // computed by adding corresponding CTTS durations to index timestamps.
3141     if (ctts_data && *index >= 0) {
3142         av_assert0(ctts_index);
3143         av_assert0(ctts_sample);
3144         // Find out the ctts_index for the found frame.
3145         *ctts_index = 0;
3146         *ctts_sample = 0;
3147         for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3148             if (*ctts_index < ctts_count) {
3149                 (*ctts_sample)++;
3150                 if (ctts_data[*ctts_index].count == *ctts_sample) {
3151                     (*ctts_index)++;
3152                     *ctts_sample = 0;
3153                 }
3154             }
3155         }
3156
3157         while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
3158             // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3159             // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3160             // compensated by dts_shift above.
3161             if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3162                 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3163                 break;
3164             }
3165
3166             (*index)--;
3167             if (*ctts_sample == 0) {
3168                 (*ctts_index)--;
3169                 if (*ctts_index >= 0)
3170                   *ctts_sample = ctts_data[*ctts_index].count - 1;
3171             } else {
3172                 (*ctts_sample)--;
3173             }
3174         }
3175     }
3176
3177     /* restore AVStream state*/
3178     st->index_entries = e_keep;
3179     st->nb_index_entries = nb_keep;
3180     return *index >= 0 ? 0 : -1;
3181 }
3182
3183 /**
3184  * Add index entry with the given values, to the end of st->index_entries.
3185  * Returns the new size st->index_entries if successful, else returns -1.
3186  *
3187  * This function is similar to ff_add_index_entry in libavformat/utils.c
3188  * except that here we are always unconditionally adding an index entry to
3189  * the end, instead of searching the entries list and skipping the add if
3190  * there is an existing entry with the same timestamp.
3191  * This is needed because the mov_fix_index calls this func with the same
3192  * unincremented timestamp for successive discarded frames.
3193  */
3194 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3195                                int size, int distance, int flags)
3196 {
3197     AVIndexEntry *entries, *ie;
3198     int64_t index = -1;
3199     const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3200
3201     // Double the allocation each time, to lower memory fragmentation.
3202     // Another difference from ff_add_index_entry function.
3203     const size_t requested_size =
3204         min_size_needed > st->index_entries_allocated_size ?
3205         FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3206         min_size_needed;
3207
3208     if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3209         return -1;
3210
3211     entries = av_fast_realloc(st->index_entries,
3212                               &st->index_entries_allocated_size,
3213                               requested_size);
3214     if(!entries)
3215         return -1;
3216
3217     st->index_entries= entries;
3218
3219     index= st->nb_index_entries++;
3220     ie= &entries[index];
3221
3222     ie->pos = pos;
3223     ie->timestamp = timestamp;
3224     ie->min_distance= distance;
3225     ie->size= size;
3226     ie->flags = flags;
3227     return index;
3228 }
3229
3230 /**
3231  * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3232  * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3233  */
3234 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3235                                        int64_t* frame_duration_buffer,
3236                                        int frame_duration_buffer_size) {
3237     int i = 0;
3238     av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3239     for (i = 0; i < frame_duration_buffer_size; i++) {
3240         end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3241         st->index_entries[end_index - 1 - i].timestamp = end_ts;
3242     }
3243 }
3244
3245 /**
3246  * Append a new ctts entry to ctts_data.
3247  * Returns the new ctts_count if successful, else returns -1.
3248  */
3249 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3250                               int count, int duration)
3251 {
3252     MOVStts *ctts_buf_new;
3253     const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3254     const size_t requested_size =
3255         min_size_needed > *allocated_size ?
3256         FFMAX(min_size_needed, 2 * (*allocated_size)) :
3257         min_size_needed;
3258
3259     if((unsigned)(*ctts_count) >= UINT_MAX / sizeof(MOVStts) - 1)
3260         return -1;
3261
3262     ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3263
3264     if(!ctts_buf_new)
3265         return -1;
3266
3267     *ctts_data = ctts_buf_new;
3268
3269     ctts_buf_new[*ctts_count].count = count;
3270     ctts_buf_new[*ctts_count].duration = duration;
3271
3272     *ctts_count = (*ctts_count) + 1;
3273     return *ctts_count;
3274 }
3275
3276 #define MAX_REORDER_DELAY 16
3277 static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
3278     MOVStreamContext *msc = st->priv_data;
3279     int ind;
3280     int ctts_ind = 0;
3281     int ctts_sample = 0;
3282     int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3283     int buf_start = 0;
3284     int buf_size = 0;
3285     int j, r, num_swaps;
3286
3287     if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3288         st->codecpar->codec_id == AV_CODEC_ID_H264) {
3289         st->codecpar->video_delay = 0;
3290         for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3291             if (buf_size == (MAX_REORDER_DELAY + 1)) {
3292                 // If circular buffer is full, then move the first element forward.
3293                 buf_start = (buf_start + 1) % buf_size;
3294             } else {
3295                 ++buf_size;
3296             }
3297
3298             // Point j to the last elem of the buffer and insert the current pts there.
3299             j = (buf_start + buf_size - 1) % buf_size;
3300             pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3301
3302             // The timestamps that are already in the sorted buffer, and are greater than the
3303             // current pts, are exactly the timestamps that need to be buffered to output PTS
3304             // in correct sorted order.
3305             // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3306             // can be computed as the maximum no. of swaps any particular timestamp needs to
3307             // go through, to keep this buffer in sorted order.
3308             num_swaps = 0;
3309             while (j != buf_start) {
3310                 r = (j - 1 + buf_size) % buf_size;
3311                 if (pts_buf[j] < pts_buf[r]) {
3312                     FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3313                     ++num_swaps;
3314                 }
3315                 j = r;
3316             }
3317             st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3318
3319             ctts_sample++;
3320             if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3321                 ctts_ind++;
3322                 ctts_sample = 0;
3323             }
3324         }
3325         av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3326                st->codecpar->video_delay, st->index);
3327     }
3328 }
3329
3330 static void mov_current_sample_inc(MOVStreamContext *sc)
3331 {
3332     sc->current_sample++;
3333     sc->current_index++;
3334     if (sc->index_ranges &&
3335         sc->current_index >= sc->current_index_range->end &&
3336         sc->current_index_range->end) {
3337         sc->current_index_range++;
3338         sc->current_index = sc->current_index_range->start;
3339     }
3340 }
3341
3342 static void mov_current_sample_dec(MOVStreamContext *sc)
3343 {
3344     sc->current_sample--;
3345     sc->current_index--;
3346     if (sc->index_ranges &&
3347         sc->current_index < sc->current_index_range->start &&
3348         sc->current_index_range > sc->index_ranges) {
3349         sc->current_index_range--;
3350         sc->current_index = sc->current_index_range->end - 1;
3351     }
3352 }
3353
3354 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3355 {
3356     int64_t range_size;
3357
3358     sc->current_sample = current_sample;
3359     sc->current_index = current_sample;
3360     if (!sc->index_ranges) {
3361         return;
3362     }
3363
3364     for (sc->current_index_range = sc->index_ranges;
3365         sc->current_index_range->end;
3366         sc->current_index_range++) {
3367         range_size = sc->current_index_range->end - sc->current_index_range->start;
3368         if (range_size > current_sample) {
3369             sc->current_index = sc->current_index_range->start + current_sample;
3370             break;
3371         }
3372         current_sample -= range_size;
3373     }
3374 }
3375
3376 /**
3377  * Fix st->index_entries, so that it contains only the entries (and the entries
3378  * which are needed to decode them) that fall in the edit list time ranges.
3379  * Also fixes the timestamps of the index entries to match the timeline
3380  * specified the edit lists.
3381  */
3382 static void mov_fix_index(MOVContext *mov, AVStream *st)
3383 {
3384     MOVStreamContext *msc = st->priv_data;
3385     AVIndexEntry *e_old = st->index_entries;
3386     int nb_old = st->nb_index_entries;
3387     const AVIndexEntry *e_old_end = e_old + nb_old;
3388     const AVIndexEntry *current = NULL;
3389     MOVStts *ctts_data_old = msc->ctts_data;
3390     int64_t ctts_index_old = 0;
3391     int64_t ctts_sample_old = 0;
3392     int64_t ctts_count_old = msc->ctts_count;
3393     int64_t edit_list_media_time = 0;
3394     int64_t edit_list_duration = 0;
3395     int64_t frame_duration = 0;
3396     int64_t edit_list_dts_counter = 0;
3397     int64_t edit_list_dts_entry_end = 0;
3398     int64_t edit_list_start_ctts_sample = 0;
3399     int64_t curr_cts;
3400     int64_t curr_ctts = 0;
3401     int64_t empty_edits_sum_duration = 0;
3402     int64_t edit_list_index = 0;
3403     int64_t index;
3404     int flags;
3405     int64_t start_dts = 0;
3406     int64_t edit_list_start_encountered = 0;
3407     int64_t search_timestamp = 0;
3408     int64_t* frame_duration_buffer = NULL;
3409     int num_discarded_begin = 0;
3410     int first_non_zero_audio_edit = -1;
3411     int packet_skip_samples = 0;
3412     MOVIndexRange *current_index_range;
3413     int i;
3414     int found_keyframe_after_edit = 0;
3415
3416     if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3417         return;
3418     }
3419
3420     // allocate the index ranges array
3421     msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3422     if (!msc->index_ranges) {
3423         av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3424         return;
3425     }
3426     msc->current_index_range = msc->index_ranges;
3427     current_index_range = msc->index_ranges - 1;
3428
3429     // Clean AVStream from traces of old index
3430     st->index_entries = NULL;
3431     st->index_entries_allocated_size = 0;
3432     st->nb_index_entries = 0;
3433
3434     // Clean ctts fields of MOVStreamContext
3435     msc->ctts_data = NULL;
3436     msc->ctts_count = 0;
3437     msc->ctts_index = 0;
3438     msc->ctts_sample = 0;
3439     msc->ctts_allocated_size = 0;
3440
3441     // Reinitialize min_corrected_pts so that it can be computed again.
3442     msc->min_corrected_pts = -1;
3443
3444     // If the dts_shift is positive (in case of negative ctts values in mov),
3445     // then negate the DTS by dts_shift
3446     if (msc->dts_shift > 0) {
3447         edit_list_dts_entry_end -= msc->dts_shift;
3448         av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3449     }
3450
3451     start_dts = edit_list_dts_entry_end;
3452
3453     while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3454                                &edit_list_duration, mov->time_scale)) {
3455         av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3456                st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3457         edit_list_index++;
3458         edit_list_dts_counter = edit_list_dts_entry_end;
3459         edit_list_dts_entry_end += edit_list_duration;
3460         num_discarded_begin = 0;
3461         if (edit_list_media_time == -1) {
3462             empty_edits_sum_duration += edit_list_duration;
3463             continue;
3464         }
3465
3466         // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3467         // according to the edit list below.
3468         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3469             if (first_non_zero_audio_edit < 0) {
3470                 first_non_zero_audio_edit = 1;
3471             } else {
3472                 first_non_zero_audio_edit = 0;
3473             }
3474
3475             if (first_non_zero_audio_edit > 0)
3476                 st->skip_samples = msc->start_pad = 0;
3477         }
3478
3479         // While reordering frame index according to edit list we must handle properly
3480         // the scenario when edit list entry starts from none key frame.
3481         // We find closest previous key frame and preserve it and consequent frames in index.
3482         // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3483         search_timestamp = edit_list_media_time;
3484         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3485             // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3486             // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3487             // edit_list_media_time to cover the decoder delay.
3488             search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3489         }
3490
3491         if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3492                                     &index, &ctts_index_old, &ctts_sample_old) < 0) {
3493             av_log(mov->fc, AV_LOG_WARNING,
3494                    "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3495                    st->index, edit_list_index, search_timestamp);
3496             if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3497                                         &index, &ctts_index_old, &ctts_sample_old) < 0) {
3498                 av_log(mov->fc, AV_LOG_WARNING,
3499                        "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3500                        st->index, edit_list_index, search_timestamp);
3501                 index = 0;
3502                 ctts_index_old = 0;
3503                 ctts_sample_old = 0;
3504             }
3505         }
3506         current = e_old + index;
3507         edit_list_start_ctts_sample = ctts_sample_old;
3508
3509         // Iterate over index and arrange it according to edit list
3510         edit_list_start_encountered = 0;
3511         found_keyframe_after_edit = 0;
3512         for (; current < e_old_end; current++, index++) {
3513             // check  if frame outside edit list mark it for discard
3514             frame_duration = (current + 1 <  e_old_end) ?
3515                              ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3516
3517             flags = current->flags;
3518
3519             // frames (pts) before or after edit list
3520             curr_cts = current->timestamp + msc->dts_shift;
3521             curr_ctts = 0;
3522
3523             if (ctts_data_old && ctts_index_old < ctts_count_old) {
3524                 curr_ctts = ctts_data_old[ctts_index_old].duration;
3525                 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3526                        curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3527                 curr_cts += curr_ctts;
3528                 ctts_sample_old++;
3529                 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3530                     if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3531                                        &msc->ctts_allocated_size,
3532                                        ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3533                                        ctts_data_old[ctts_index_old].duration) == -1) {
3534                         av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3535                                ctts_index_old,
3536                                ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3537                                ctts_data_old[ctts_index_old].duration);
3538                         break;
3539                     }
3540                     ctts_index_old++;
3541                     ctts_sample_old = 0;
3542                     edit_list_start_ctts_sample = 0;
3543                 }
3544             }
3545
3546             if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3547                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3548                     curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3549                     first_non_zero_audio_edit > 0) {
3550                     packet_skip_samples = edit_list_media_time - curr_cts;
3551                     st->skip_samples += packet_skip_samples;
3552
3553                     // Shift the index entry timestamp by packet_skip_samples to be correct.
3554                     edit_list_dts_counter -= packet_skip_samples;
3555                     if (edit_list_start_encountered == 0)  {
3556                         edit_list_start_encountered = 1;
3557                         // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3558                         // discarded packets.
3559                         if (frame_duration_buffer) {
3560                             fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3561                                                        frame_duration_buffer, num_discarded_begin);
3562                             av_freep(&frame_duration_buffer);
3563                         }
3564                     }
3565
3566                     av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3567                 } else {
3568                     flags |= AVINDEX_DISCARD_FRAME;
3569                     av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3570
3571                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3572                         num_discarded_begin++;
3573                         frame_duration_buffer = av_realloc(frame_duration_buffer,
3574                                                            num_discarded_begin * sizeof(int64_t));
3575                         if (!frame_duration_buffer) {
3576                             av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3577                             break;
3578                         }
3579                         frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3580
3581                         // Increment skip_samples for the first non-zero audio edit list
3582                         if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3583                             st->skip_samples += frame_duration;
3584                         }
3585                     }
3586                 }
3587             } else {
3588                 if (msc->min_corrected_pts < 0) {
3589                     msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3590                 } else {
3591                     msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3592                 }
3593                 if (edit_list_start_encountered == 0) {
3594                     edit_list_start_encountered = 1;
3595                     // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3596                     // discarded packets.
3597                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3598                         fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3599                                                    frame_duration_buffer, num_discarded_begin);
3600                         av_freep(&frame_duration_buffer);
3601                     }
3602                 }
3603             }
3604
3605             if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3606                                 current->min_distance, flags) == -1) {
3607                 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3608                 break;
3609             }
3610
3611             // Update the index ranges array
3612             if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3613                 current_index_range++;
3614                 current_index_range->start = index;
3615             }
3616             current_index_range->end = index + 1;
3617
3618             // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3619             if (edit_list_start_encountered > 0) {
3620                 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3621             }
3622
3623             // Break when found first key frame after edit entry completion
3624             if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3625                 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3626                 if (ctts_data_old) {
3627                     // If we have CTTS and this is the first keyframe after edit elist,
3628                     // wait for one more, because there might be trailing B-frames after this I-frame
3629                     // that do belong to the edit.
3630                     if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3631                         found_keyframe_after_edit = 1;
3632                         continue;
3633                     }
3634                     if (ctts_sample_old != 0) {
3635                         if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3636                                            &msc->ctts_allocated_size,
3637                                            ctts_sample_old - edit_list_start_ctts_sample,
3638                                            ctts_data_old[ctts_index_old].duration) == -1) {
3639                             av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3640                                    ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3641                                    ctts_data_old[ctts_index_old].duration);
3642                             break;
3643                         }
3644                     }
3645                 }
3646                 break;
3647             }
3648         }
3649     }
3650     // If there are empty edits, then msc->min_corrected_pts might be positive
3651     // intentionally. So we subtract the sum duration of emtpy edits here.
3652     msc->min_corrected_pts -= empty_edits_sum_duration;
3653
3654     // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3655     // dts by that amount to make the first pts zero.
3656     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && msc->min_corrected_pts > 0) {
3657         av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
3658         for (i = 0; i < st->nb_index_entries; ++i) {
3659             st->index_entries[i].timestamp -= msc->min_corrected_pts;
3660         }
3661     }
3662
3663     // Update av stream length
3664     st->duration = edit_list_dts_entry_end - start_dts;
3665     msc->start_pad = st->skip_samples;
3666
3667     // Free the old index and the old CTTS structures
3668     av_free(e_old);
3669     av_free(ctts_data_old);
3670     av_freep(&frame_duration_buffer);
3671
3672     // Null terminate the index ranges array
3673     current_index_range++;
3674     current_index_range->start = 0;
3675     current_index_range->end = 0;
3676     msc->current_index = msc->index_ranges[0].start;
3677 }
3678
3679 static void mov_build_index(MOVContext *mov, AVStream *st)
3680 {
3681     MOVStreamContext *sc = st->priv_data;
3682     int64_t current_offset;
3683     int64_t current_dts = 0;
3684     unsigned int stts_index = 0;
3685     unsigned int stsc_index = 0;
3686     unsigned int stss_index = 0;
3687     unsigned int stps_index = 0;
3688     unsigned int i, j;
3689     uint64_t stream_size = 0;
3690     MOVStts *ctts_data_old = sc->ctts_data;
3691     unsigned int ctts_count_old = sc->ctts_count;
3692
3693     if (sc->elst_count) {
3694         int i, edit_start_index = 0, multiple_edits = 0;
3695         int64_t empty_duration = 0; // empty duration of the first edit list entry
3696         int64_t start_time = 0; // start time of the media
3697
3698         for (i = 0; i < sc->elst_count; i++) {
3699             const MOVElst *e = &sc->elst_data[i];
3700             if (i == 0 && e->time == -1) {
3701                 /* if empty, the first entry is the start time of the stream
3702                  * relative to the presentation itself */
3703                 empty_duration = e->duration;
3704                 edit_start_index = 1;
3705             } else if (i == edit_start_index && e->time >= 0) {
3706                 start_time = e->time;
3707             } else {
3708                 multiple_edits = 1;
3709             }
3710         }
3711
3712         if (multiple_edits && !mov->advanced_editlist)
3713             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3714                    "Use -advanced_editlist to correctly decode otherwise "
3715                    "a/v desync might occur\n");
3716
3717         /* adjust first dts according to edit list */
3718         if ((empty_duration || start_time) && mov->time_scale > 0) {
3719             if (empty_duration)
3720                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3721             sc->time_offset = start_time - empty_duration;
3722             sc->min_corrected_pts = start_time;
3723             if (!mov->advanced_editlist)
3724                 current_dts = -sc->time_offset;
3725         }
3726
3727         if (!multiple_edits && !mov->advanced_editlist &&
3728             st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3729             sc->start_pad = start_time;
3730     }
3731
3732     /* only use old uncompressed audio chunk demuxing when stts specifies it */
3733     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3734           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3735         unsigned int current_sample = 0;
3736         unsigned int stts_sample = 0;
3737         unsigned int sample_size;
3738         unsigned int distance = 0;
3739         unsigned int rap_group_index = 0;
3740         unsigned int rap_group_sample = 0;
3741         int64_t last_dts = 0;
3742         int64_t dts_correction = 0;
3743         int rap_group_present = sc->rap_group_count && sc->rap_group;
3744         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3745
3746         current_dts -= sc->dts_shift;
3747         last_dts     = current_dts;
3748
3749         if (!sc->sample_count || st->nb_index_entries)
3750             return;
3751         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3752             return;
3753         if (av_reallocp_array(&st->index_entries,
3754                               st->nb_index_entries + sc->sample_count,
3755                               sizeof(*st->index_entries)) < 0) {
3756             st->nb_index_entries = 0;
3757             return;
3758         }
3759         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3760
3761         if (ctts_data_old) {
3762             // Expand ctts entries such that we have a 1-1 mapping with samples
3763             if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3764                 return;
3765             sc->ctts_count = 0;
3766             sc->ctts_allocated_size = 0;
3767             sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
3768                                     sc->sample_count * sizeof(*sc->ctts_data));
3769             if (!sc->ctts_data) {
3770                 av_free(ctts_data_old);
3771                 return;
3772             }
3773
3774             memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
3775
3776             for (i = 0; i < ctts_count_old &&
3777                         sc->ctts_count < sc->sample_count; i++)
3778                 for (j = 0; j < ctts_data_old[i].count &&
3779                             sc->ctts_count < sc->sample_count; j++)
3780                     add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3781                                    &sc->ctts_allocated_size, 1,
3782                                    ctts_data_old[i].duration);
3783             av_free(ctts_data_old);
3784         }
3785
3786         for (i = 0; i < sc->chunk_count; i++) {
3787             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3788             current_offset = sc->chunk_offsets[i];
3789             while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3790                 i + 1 == sc->stsc_data[stsc_index + 1].first)
3791                 stsc_index++;
3792
3793             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3794                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3795                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3796                 sc->stsz_sample_size = sc->sample_size;
3797             }
3798             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3799                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3800                 sc->stsz_sample_size = sc->sample_size;
3801             }
3802
3803             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3804                 int keyframe = 0;
3805                 if (current_sample >= sc->sample_count) {
3806                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3807                     return;
3808                 }
3809
3810                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3811                     keyframe = 1;
3812                     if (stss_index + 1 < sc->keyframe_count)
3813                         stss_index++;
3814                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3815                     keyframe = 1;
3816                     if (stps_index + 1 < sc->stps_count)
3817                         stps_index++;
3818                 }
3819                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3820                     if (sc->rap_group[rap_group_index].index > 0)
3821                         keyframe = 1;
3822                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3823                         rap_group_sample = 0;
3824                         rap_group_index++;
3825                     }
3826                 }
3827                 if (sc->keyframe_absent
3828                     && !sc->stps_count
3829                     && !rap_group_present
3830                     && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3831                      keyframe = 1;
3832                 if (keyframe)
3833                     distance = 0;
3834                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3835                 if (sc->pseudo_stream_id == -1 ||
3836                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3837                     AVIndexEntry *e;
3838                     if (sample_size > 0x3FFFFFFF) {
3839                         av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3840                         return;
3841                     }
3842                     e = &st->index_entries[st->nb_index_entries++];
3843                     e->pos = current_offset;
3844                     e->timestamp = current_dts;
3845                     e->size = sample_size;
3846                     e->min_distance = distance;
3847                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3848                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3849                             "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3850                             current_offset, current_dts, sample_size, distance, keyframe);
3851                     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3852                         ff_rfps_add_frame(mov->fc, st, current_dts);
3853                 }
3854
3855                 current_offset += sample_size;
3856                 stream_size += sample_size;
3857
3858                 /* A negative sample duration is invalid based on the spec,
3859                  * but some samples need it to correct the DTS. */
3860                 if (sc->stts_data[stts_index].duration < 0) {
3861                     av_log(mov->fc, AV_LOG_WARNING,
3862                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3863                            sc->stts_data[stts_index].duration, stts_index,
3864                            st->index);
3865                     dts_correction += sc->stts_data[stts_index].duration - 1;
3866                     sc->stts_data[stts_index].duration = 1;
3867                 }
3868                 current_dts += sc->stts_data[stts_index].duration;
3869                 if (!dts_correction || current_dts + dts_correction > last_dts) {
3870                     current_dts += dts_correction;
3871                     dts_correction = 0;
3872                 } else {
3873                     /* Avoid creating non-monotonous DTS */
3874                     dts_correction += current_dts - last_dts - 1;
3875                     current_dts = last_dts + 1;
3876                 }
3877                 last_dts = current_dts;
3878                 distance++;
3879                 stts_sample++;
3880                 current_sample++;
3881                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3882                     stts_sample = 0;
3883                     stts_index++;
3884                 }
3885             }
3886         }
3887         if (st->duration > 0)
3888             st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3889     } else {
3890         unsigned chunk_samples, total = 0;
3891
3892         // compute total chunk count
3893         for (i = 0; i < sc->stsc_count; i++) {
3894             unsigned count, chunk_count;
3895
3896             chunk_samples = sc->stsc_data[i].count;
3897             if (i != sc->stsc_count - 1 &&
3898                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3899                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3900                 return;
3901             }
3902
3903             if (sc->samples_per_frame >= 160) { // gsm
3904                 count = chunk_samples / sc->samples_per_frame;
3905             } else if (sc->samples_per_frame > 1) {
3906                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3907                 count = (chunk_samples+samples-1) / samples;
3908             } else {
3909                 count = (chunk_samples+1023) / 1024;
3910             }
3911
3912             if (mov_stsc_index_valid(i, sc->stsc_count))
3913                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3914             else
3915                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3916             total += chunk_count * count;
3917         }
3918
3919         av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3920         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3921             return;
3922         if (av_reallocp_array(&st->index_entries,
3923                               st->nb_index_entries + total,
3924                               sizeof(*st->index_entries)) < 0) {
3925             st->nb_index_entries = 0;
3926             return;
3927         }
3928         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3929
3930         // populate index
3931         for (i = 0; i < sc->chunk_count; i++) {
3932             current_offset = sc->chunk_offsets[i];
3933             if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3934                 i + 1 == sc->stsc_data[stsc_index + 1].first)
3935                 stsc_index++;
3936             chunk_samples = sc->stsc_data[stsc_index].count;
3937
3938             while (chunk_samples > 0) {
3939                 AVIndexEntry *e;
3940                 unsigned size, samples;
3941
3942                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3943                     avpriv_request_sample(mov->fc,
3944                            "Zero bytes per frame, but %d samples per frame",
3945                            sc->samples_per_frame);
3946                     return;
3947                 }
3948
3949                 if (sc->samples_per_frame >= 160) { // gsm
3950                     samples = sc->samples_per_frame;
3951                     size = sc->bytes_per_frame;
3952                 } else {
3953                     if (sc->samples_per_frame > 1) {
3954                         samples = FFMIN((1024 / sc->samples_per_frame)*
3955                                         sc->samples_per_frame, chunk_samples);
3956                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3957                     } else {
3958                         samples = FFMIN(1024, chunk_samples);
3959                         size = samples * sc->sample_size;
3960                     }
3961                 }
3962
3963                 if (st->nb_index_entries >= total) {
3964                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3965                     return;
3966                 }
3967                 if (size > 0x3FFFFFFF) {
3968                     av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3969                     return;
3970                 }
3971                 e = &st->index_entries[st->nb_index_entries++];
3972                 e->pos = current_offset;
3973                 e->timestamp = current_dts;
3974                 e->size = size;
3975                 e->min_distance = 0;
3976                 e->flags = AVINDEX_KEYFRAME;
3977                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3978                        "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3979                        size, samples);
3980
3981                 current_offset += size;
3982                 current_dts += samples;
3983                 chunk_samples -= samples;
3984             }
3985         }
3986     }
3987
3988     if (!mov->ignore_editlist && mov->advanced_editlist) {
3989         // Fix index according to edit lists.
3990         mov_fix_index(mov, st);
3991     }
3992
3993     mov_estimate_video_delay(mov, st);
3994 }
3995
3996 static int test_same_origin(const char *src, const char *ref) {
3997     char src_proto[64];
3998     char ref_proto[64];
3999     char src_auth[256];
4000     char ref_auth[256];
4001     char src_host[256];
4002     char ref_host[256];
4003     int src_port=-1;
4004     int ref_port=-1;
4005
4006     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
4007     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
4008
4009     if (strlen(src) == 0) {
4010         return -1;
4011     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
4012         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
4013         strlen(src_host) + 1 >= sizeof(src_host) ||
4014         strlen(ref_host) + 1 >= sizeof(ref_host)) {
4015         return 0;
4016     } else if (strcmp(src_proto, ref_proto) ||
4017                strcmp(src_auth, ref_auth) ||
4018                strcmp(src_host, ref_host) ||
4019                src_port != ref_port) {
4020         return 0;
4021     } else
4022         return 1;
4023 }
4024
4025 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
4026 {
4027     /* try relative path, we do not try the absolute because it can leak information about our
4028        system to an attacker */
4029     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4030         char filename[1025];
4031         const char *src_path;
4032         int i, l;
4033
4034         /* find a source dir */
4035         src_path = strrchr(src, '/');
4036         if (src_path)
4037             src_path++;
4038         else
4039             src_path = src;
4040
4041         /* find a next level down to target */
4042         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4043             if (ref->path[l] == '/') {
4044                 if (i == ref->nlvl_to - 1)
4045                     break;
4046                 else
4047                     i++;
4048             }
4049
4050         /* compose filename if next level down to target was found */
4051         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
4052             memcpy(filename, src, src_path - src);
4053             filename[src_path - src] = 0;
4054
4055             for (i = 1; i < ref->nlvl_from; i++)
4056                 av_strlcat(filename, "../", sizeof(filename));
4057
4058             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4059             if (!c->use_absolute_path) {
4060                 int same_origin = test_same_origin(src, filename);
4061
4062                 if (!same_origin) {
4063                     av_log(c->fc, AV_LOG_ERROR,
4064                         "Reference with mismatching origin, %s not tried for security reasons, "
4065                         "set demuxer option use_absolute_path to allow it anyway\n",
4066                         ref->path);
4067                     return AVERROR(ENOENT);
4068                 }
4069
4070                 if(strstr(ref->path + l + 1, "..") ||
4071                    strstr(ref->path + l + 1, ":") ||
4072                    (ref->nlvl_from > 1 && same_origin < 0) ||
4073                    (filename[0] == '/' && src_path == src))
4074                     return AVERROR(ENOENT);
4075             }
4076
4077             if (strlen(filename) + 1 == sizeof(filename))
4078                 return AVERROR(ENOENT);
4079             if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4080                 return 0;
4081         }
4082     } else if (c->use_absolute_path) {
4083         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4084                "this is a possible security issue\n");
4085         if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4086             return 0;
4087     } else {
4088         av_log(c->fc, AV_LOG_ERROR,
4089                "Absolute path %s not tried for security reasons, "
4090                "set demuxer option use_absolute_path to allow absolute paths\n",
4091                ref->path);
4092     }
4093
4094     return AVERROR(ENOENT);
4095 }
4096
4097 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
4098 {
4099     if (sc->time_scale <= 0) {
4100         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4101         sc->time_scale = c->time_scale;
4102         if (sc->time_scale <= 0)
4103             sc->time_scale = 1;
4104     }
4105 }
4106
4107 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4108 {
4109     AVStream *st;
4110     MOVStreamContext *sc;
4111     int ret;
4112
4113     st = avformat_new_stream(c->fc, NULL);
4114     if (!st) return AVERROR(ENOMEM);
4115     st->id = c->fc->nb_streams;
4116     sc = av_mallocz(sizeof(MOVStreamContext));
4117     if (!sc) return AVERROR(ENOMEM);
4118
4119     st->priv_data = sc;
4120     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
4121     sc->ffindex = st->index;
4122     c->trak_index = st->index;
4123
4124     if ((ret = mov_read_default(c, pb, atom)) < 0)
4125         return ret;
4126
4127     c->trak_index = -1;
4128
4129     /* sanity checks */
4130     if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4131                             (!sc->sample_size && !sc->sample_count))) ||
4132         (!sc->chunk_count && sc->sample_count)) {
4133         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4134                st->index);
4135         return 0;
4136     }
4137     if (sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
4138         av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
4139                st->index);
4140         return AVERROR_INVALIDDATA;
4141     }
4142
4143     fix_timescale(c, sc);
4144
4145     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4146
4147     mov_build_index(c, st);
4148
4149     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4150         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4151         if (c->enable_drefs) {
4152             if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4153                 av_log(c->fc, AV_LOG_ERROR,
4154                        "stream %d, error opening alias: path='%s', dir='%s', "
4155                        "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4156                        st->index, dref->path, dref->dir, dref->filename,
4157                        dref->volume, dref->nlvl_from, dref->nlvl_to);
4158         } else {
4159             av_log(c->fc, AV_LOG_WARNING,
4160                    "Skipped opening external track: "
4161                    "stream %d, alias: path='%s', dir='%s', "
4162                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4163                    "Set enable_drefs to allow this.\n",
4164                    st->index, dref->path, dref->dir, dref->filename,
4165                    dref->volume, dref->nlvl_from, dref->nlvl_to);
4166         }
4167     } else {
4168         sc->pb = c->fc->pb;
4169         sc->pb_is_copied = 1;
4170     }
4171
4172     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4173         if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4174             sc->height && sc->width &&
4175             (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4176             st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4177                                              ((double)st->codecpar->width * sc->height), INT_MAX);
4178         }
4179
4180 #if FF_API_R_FRAME_RATE
4181         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4182             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4183                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4184 #endif
4185     }
4186
4187     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4188     if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4189         TAG_IS_AVCI(st->codecpar->codec_tag)) {
4190         ret = ff_generate_avci_extradata(st);
4191         if (ret < 0)
4192             return ret;
4193     }
4194
4195     switch (st->codecpar->codec_id) {
4196 #if CONFIG_H261_DECODER
4197     case AV_CODEC_ID_H261:
4198 #endif
4199 #if CONFIG_H263_DECODER
4200     case AV_CODEC_ID_H263:
4201 #endif
4202 #if CONFIG_MPEG4_DECODER
4203     case AV_CODEC_ID_MPEG4:
4204 #endif
4205         st->codecpar->width = 0; /* let decoder init width/height */
4206         st->codecpar->height= 0;
4207         break;
4208     }
4209
4210     // If the duration of the mp3 packets is not constant, then they could need a parser
4211     if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4212         && sc->stts_count > 3
4213         && sc->stts_count*10 > st->nb_frames
4214         && sc->time_scale == st->codecpar->sample_rate) {
4215             st->need_parsing = AVSTREAM_PARSE_FULL;
4216     }
4217     /* Do not need those anymore. */
4218     av_freep(&sc->chunk_offsets);
4219     av_freep(&sc->sample_sizes);
4220     av_freep(&sc->keyframes);
4221     av_freep(&sc->stts_data);
4222     av_freep(&sc->stps_data);
4223     av_freep(&sc->elst_data);
4224     av_freep(&sc->rap_group);
4225
4226     return 0;
4227 }
4228
4229 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4230 {
4231     int ret;
4232     c->itunes_metadata = 1;
4233     ret = mov_read_default(c, pb, atom);
4234     c->itunes_metadata = 0;
4235     return ret;
4236 }
4237
4238 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4239 {
4240     uint32_t count;
4241     uint32_t i;
4242
4243     if (atom.size < 8)
4244         return 0;
4245
4246     avio_skip(pb, 4);
4247     count = avio_rb32(pb);
4248     if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4249         av_log(c->fc, AV_LOG_ERROR,
4250                "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4251         return AVERROR_INVALIDDATA;
4252     }
4253
4254     c->meta_keys_count = count + 1;
4255     c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4256     if (!c->meta_keys)
4257         return AVERROR(ENOMEM);
4258
4259     for (i = 1; i <= count; ++i) {
4260         uint32_t key_size = avio_rb32(pb);
4261         uint32_t type = avio_rl32(pb);
4262         if (key_size < 8) {
4263             av_log(c->fc, AV_LOG_ERROR,
4264                    "The key# %"PRIu32" in meta has invalid size:"
4265                    "%"PRIu32"\n", i, key_size);
4266             return AVERROR_INVALIDDATA;
4267         }
4268         key_size -= 8;
4269         if (type != MKTAG('m','d','t','a')) {
4270             avio_skip(pb, key_size);
4271         }
4272         c->meta_keys[i] = av_mallocz(key_size + 1);
4273         if (!c->meta_keys[i])
4274             return AVERROR(ENOMEM);
4275         avio_read(pb, c->meta_keys[i], key_size);
4276     }
4277
4278     return 0;
4279 }
4280
4281 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4282 {
4283     int64_t end = avio_tell(pb) + atom.size;
4284     uint8_t *key = NULL, *val = NULL, *mean = NULL;
4285     int i;
4286     int ret = 0;
4287     AVStream *st;
4288     MOVStreamContext *sc;
4289
4290     if (c->fc->nb_streams < 1)
4291         return 0;
4292     st = c->fc->streams[c->fc->nb_streams-1];
4293     sc = st->priv_data;
4294
4295     for (i = 0; i < 3; i++) {
4296         uint8_t **p;
4297         uint32_t len, tag;
4298
4299         if (end - avio_tell(pb) <= 12)
4300             break;
4301
4302         len = avio_rb32(pb);
4303         tag = avio_rl32(pb);
4304         avio_skip(pb, 4); // flags
4305
4306         if (len < 12 || len - 12 > end - avio_tell(pb))
4307             break;
4308         len -= 12;
4309
4310         if (tag == MKTAG('m', 'e', 'a', 'n'))
4311             p = &mean;
4312         else if (tag == MKTAG('n', 'a', 'm', 'e'))
4313             p = &key;
4314         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4315             avio_skip(pb, 4);
4316             len -= 4;
4317             p = &val;
4318         } else
4319             break;
4320
4321         *p = av_malloc(len + 1);
4322         if (!*p) {
4323             ret = AVERROR(ENOMEM);
4324             break;
4325         }
4326         ret = ffio_read_size(pb, *p, len);
4327         if (ret < 0) {
4328             av_freep(p);
4329             break;
4330         }
4331         (*p)[len] = 0;
4332     }
4333
4334     if (mean && key && val) {
4335         if (strcmp(key, "iTunSMPB") == 0) {
4336             int priming, remainder, samples;
4337             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4338                 if(priming>0 && priming<16384)
4339                     sc->start_pad = priming;
4340             }
4341         }
4342         if (strcmp(key, "cdec") != 0) {
4343             av_dict_set(&c->fc->metadata, key, val,
4344                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4345             key = val = NULL;
4346         }
4347     } else {
4348         av_log(c->fc, AV_LOG_VERBOSE,
4349                "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4350     }
4351
4352     avio_seek(pb, end, SEEK_SET);
4353     av_freep(&key);
4354     av_freep(&val);
4355     av_freep(&mean);
4356     return ret;
4357 }
4358
4359 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4360 {
4361     while (atom.size > 8) {
4362         uint32_t tag = avio_rl32(pb);
4363         atom.size -= 4;
4364         if (tag == MKTAG('h','d','l','r')) {
4365             avio_seek(pb, -8, SEEK_CUR);
4366             atom.size += 8;
4367             return mov_read_default(c, pb, atom);
4368         }
4369     }
4370     return 0;
4371 }
4372
4373 // return 1 when matrix is identity, 0 otherwise
4374 #define IS_MATRIX_IDENT(matrix)            \
4375     ( (matrix)[0][0] == (1 << 16) &&       \
4376       (matrix)[1][1] == (1 << 16) &&       \
4377       (matrix)[2][2] == (1 << 30) &&       \
4378      !(matrix)[0][1] && !(matrix)[0][2] && \
4379      !(matrix)[1][0] && !(matrix)[1][2] && \
4380      !(matrix)[2][0] && !(matrix)[2][1])
4381
4382 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4383 {
4384     int i, j, e;
4385     int width;
4386     int height;
4387     int display_matrix[3][3];
4388     int res_display_matrix[3][3] = { { 0 } };
4389     AVStream *st;
4390     MOVStreamContext *sc;
4391     int version;
4392     int flags;
4393
4394     if (c->fc->nb_streams < 1)
4395         return 0;
4396     st = c->fc->streams[c->fc->nb_streams-1];
4397     sc = st->priv_data;
4398
4399     version = avio_r8(pb);
4400     flags = avio_rb24(pb);
4401     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4402
4403     if (version == 1) {
4404         avio_rb64(pb);
4405         avio_rb64(pb);
4406     } else {
4407         avio_rb32(pb); /* creation time */
4408         avio_rb32(pb); /* modification time */
4409     }
4410     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4411     avio_rb32(pb); /* reserved */
4412
4413     /* highlevel (considering edits) duration in movie timebase */
4414     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4415     avio_rb32(pb); /* reserved */
4416     avio_rb32(pb); /* reserved */
4417
4418     avio_rb16(pb); /* layer */
4419     avio_rb16(pb); /* alternate group */
4420     avio_rb16(pb); /* volume */
4421     avio_rb16(pb); /* reserved */
4422
4423     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4424     // they're kept in fixed point format through all calculations
4425     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4426     // side data, but the scale factor is not needed to calculate aspect ratio
4427     for (i = 0; i < 3; i++) {
4428         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
4429         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
4430         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
4431     }
4432
4433     width = avio_rb32(pb);       // 16.16 fixed point track width
4434     height = avio_rb32(pb);      // 16.16 fixed point track height
4435     sc->width = width >> 16;
4436     sc->height = height >> 16;
4437
4438     // apply the moov display matrix (after the tkhd one)
4439     for (i = 0; i < 3; i++) {
4440         const int sh[3] = { 16, 16, 30 };
4441         for (j = 0; j < 3; j++) {
4442             for (e = 0; e < 3; e++) {
4443                 res_display_matrix[i][j] +=
4444                     ((int64_t) display_matrix[i][e] *
4445                      c->movie_display_matrix[e][j]) >> sh[e];
4446             }
4447         }
4448     }
4449
4450     // save the matrix when it is not the default identity
4451     if (!IS_MATRIX_IDENT(res_display_matrix)) {
4452         double rotate;
4453
4454         av_freep(&sc->display_matrix);
4455         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4456         if (!sc->display_matrix)
4457             return AVERROR(ENOMEM);
4458
4459         for (i = 0; i < 3; i++)
4460             for (j = 0; j < 3; j++)
4461                 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4462
4463 #if FF_API_OLD_ROTATE_API
4464         rotate = av_display_rotation_get(sc->display_matrix);
4465         if (!isnan(rotate)) {
4466             char rotate_buf[64];
4467             rotate = -rotate;
4468             if (rotate < 0) // for backward compatibility
4469                 rotate += 360;
4470             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4471             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4472         }
4473 #endif
4474     }
4475
4476     // transform the display width/height according to the matrix
4477     // to keep the same scale, use [width height 1<<16]
4478     if (width && height && sc->display_matrix) {
4479         double disp_transform[2];
4480
4481         for (i = 0; i < 2; i++)
4482             disp_transform[i] = hypot(sc->display_matrix[0 + i],
4483                                       sc->display_matrix[3 + i]);
4484
4485         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
4486             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4487             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4488             st->sample_aspect_ratio = av_d2q(
4489                 disp_transform[0] / disp_transform[1],
4490                 INT_MAX);
4491     }
4492     return 0;
4493 }
4494
4495 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4496 {
4497     MOVFragment *frag = &c->fragment;
4498     MOVTrackExt *trex = NULL;
4499     int flags, track_id, i;
4500
4501     avio_r8(pb); /* version */
4502     flags = avio_rb24(pb);
4503
4504     track_id = avio_rb32(pb);
4505     if (!track_id)
4506         return AVERROR_INVALIDDATA;
4507     frag->track_id = track_id;
4508     set_frag_stream(&c->frag_index, track_id);
4509     for (i = 0; i < c->trex_count; i++)
4510         if (c->trex_data[i].track_id == frag->track_id) {
4511             trex = &c->trex_data[i];
4512             break;
4513         }
4514     if (!trex) {
4515         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4516         return AVERROR_INVALIDDATA;
4517     }
4518
4519     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4520                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4521                              frag->moof_offset : frag->implicit_offset;
4522     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4523
4524     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4525                      avio_rb32(pb) : trex->duration;
4526     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
4527                      avio_rb32(pb) : trex->size;
4528     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
4529                      avio_rb32(pb) : trex->flags;
4530     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4531
4532     return 0;
4533 }
4534
4535 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4536 {
4537     unsigned i, num;
4538     void *new_tracks;
4539
4540     num = atom.size / 4;
4541     if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4542         return AVERROR(ENOMEM);
4543
4544     av_free(c->chapter_tracks);
4545     c->chapter_tracks = new_tracks;
4546     c->nb_chapter_tracks = num;
4547
4548     for (i = 0; i < num && !pb->eof_reached; i++)
4549         c->chapter_tracks[i] = avio_rb32(pb);
4550
4551     return 0;
4552 }
4553
4554 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4555 {
4556     MOVTrackExt *trex;
4557     int err;
4558
4559     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4560         return AVERROR_INVALIDDATA;
4561     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4562                                  sizeof(*c->trex_data))) < 0) {
4563         c->trex_count = 0;
4564         return err;
4565     }
4566
4567     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4568
4569     trex = &c->trex_data[c->trex_count++];
4570     avio_r8(pb); /* version */
4571     avio_rb24(pb); /* flags */
4572     trex->track_id = avio_rb32(pb);
4573     trex->stsd_id  = avio_rb32(pb);
4574     trex->duration = avio_rb32(pb);
4575     trex->size     = avio_rb32(pb);
4576     trex->flags    = avio_rb32(pb);
4577     return 0;
4578 }
4579
4580 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4581 {
4582     MOVFragment *frag = &c->fragment;
4583     AVStream *st = NULL;
4584     MOVStreamContext *sc;
4585     int version, i;
4586     MOVFragmentStreamInfo * frag_stream_info;
4587     int64_t base_media_decode_time;
4588
4589     for (i = 0; i < c->fc->nb_streams; i++) {
4590         if (c->fc->streams[i]->id == frag->track_id) {
4591             st = c->fc->streams[i];
4592             break;
4593         }
4594     }
4595     if (!st) {
4596         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4597         return AVERROR_INVALIDDATA;
4598     }
4599     sc = st->priv_data;
4600     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4601         return 0;
4602     version = avio_r8(pb);
4603     avio_rb24(pb); /* flags */
4604     if (version) {
4605         base_media_decode_time = avio_rb64(pb);
4606     } else {
4607         base_media_decode_time = avio_rb32(pb);
4608     }
4609
4610     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4611     if (frag_stream_info)
4612         frag_stream_info->tfdt_dts = base_media_decode_time;
4613     sc->track_end = base_media_decode_time;
4614
4615     return 0;
4616 }
4617
4618 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4619 {
4620     MOVFragment *frag = &c->fragment;
4621     AVStream *st = NULL;
4622     MOVStreamContext *sc;
4623     MOVStts *ctts_data;
4624     uint64_t offset;
4625     int64_t dts, pts = AV_NOPTS_VALUE;
4626     int data_offset = 0;
4627     unsigned entries, first_sample_flags = frag->flags;
4628     int flags, distance, i;
4629     int64_t prev_dts = AV_NOPTS_VALUE;
4630     int next_frag_index = -1, index_entry_pos;
4631     size_t requested_size;
4632     size_t old_ctts_allocated_size;
4633     AVIndexEntry *new_entries;
4634     MOVFragmentStreamInfo * frag_stream_info;
4635
4636     for (i = 0; i < c->fc->nb_streams; i++) {
4637         if (c->fc->streams[i]->id == frag->track_id) {
4638             st = c->fc->streams[i];
4639             break;
4640         }
4641     }
4642     if (!st) {
4643         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4644         return AVERROR_INVALIDDATA;
4645     }
4646     sc = st->priv_data;
4647     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4648         return 0;
4649
4650     // Find the next frag_index index that has a valid index_entry for
4651     // the current track_id.
4652     //
4653     // A valid index_entry means the trun for the fragment was read
4654     // and it's samples are in index_entries at the given position.
4655     // New index entries will be inserted before the index_entry found.
4656     index_entry_pos = st->nb_index_entries;
4657     for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4658         frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4659         if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4660             next_frag_index = i;
4661             index_entry_pos = frag_stream_info->index_entry;
4662             break;
4663         }
4664     }
4665
4666     avio_r8(pb); /* version */
4667     flags = avio_rb24(pb);
4668     entries = avio_rb32(pb);
4669     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4670
4671     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4672         return AVERROR_INVALIDDATA;
4673     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
4674     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4675
4676     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4677     if (frag_stream_info)
4678     {
4679         if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4680             c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4681             pts = frag_stream_info->first_tfra_pts;
4682             av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4683                     ", using it for pts\n", pts);
4684         } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4685             // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4686             // pts = frag_stream_info->sidx_pts;
4687             dts = frag_stream_info->sidx_pts - sc->time_offset;
4688             av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4689                     ", using it for pts\n", pts);
4690         } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4691             dts = frag_stream_info->tfdt_dts - sc->time_offset;
4692             av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4693                     ", using it for dts\n", dts);
4694         } else {
4695             dts = sc->track_end - sc->time_offset;
4696             av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4697                     ", using it for dts\n", dts);
4698         }
4699     } else {
4700         dts = sc->track_end - sc->time_offset;
4701         av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4702                 ", using it for dts\n", dts);
4703     }
4704     offset   = frag->base_data_offset + data_offset;
4705     distance = 0;
4706     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4707
4708     // realloc space for new index entries
4709     if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4710         entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4711         av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4712     }
4713     if (entries <= 0)
4714         return -1;
4715
4716     requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4717     new_entries = av_fast_realloc(st->index_entries,
4718                                   &st->index_entries_allocated_size,
4719                                   requested_size);
4720     if(!new_entries)
4721         return AVERROR(ENOMEM);
4722     st->index_entries= new_entries;
4723
4724     requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4725     old_ctts_allocated_size = sc->ctts_allocated_size;
4726     ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4727                                 requested_size);
4728     if (!ctts_data)
4729         return AVERROR(ENOMEM);
4730     sc->ctts_data = ctts_data;
4731
4732     // In case there were samples without ctts entries, ensure they get
4733     // zero valued entries. This ensures clips which mix boxes with and
4734     // without ctts entries don't pickup uninitialized data.
4735     memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
4736            sc->ctts_allocated_size - old_ctts_allocated_size);
4737
4738     if (index_entry_pos < st->nb_index_entries) {
4739         // Make hole in index_entries and ctts_data for new samples
4740         memmove(st->index_entries + index_entry_pos + entries,
4741                 st->index_entries + index_entry_pos,
4742                 sizeof(*st->index_entries) *
4743                 (st->nb_index_entries - index_entry_pos));
4744         memmove(sc->ctts_data + index_entry_pos + entries,
4745                 sc->ctts_data + index_entry_pos,
4746                 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4747         if (index_entry_pos < sc->current_sample) {
4748             sc->current_sample += entries;
4749         }
4750     }
4751
4752     st->nb_index_entries += entries;
4753     sc->ctts_count = st->nb_index_entries;
4754
4755     // Record the index_entry position in frag_index of this fragment
4756     if (frag_stream_info)
4757         frag_stream_info->index_entry = index_entry_pos;
4758
4759     if (index_entry_pos > 0)
4760         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4761
4762     for (i = 0; i < entries && !pb->eof_reached; i++) {
4763         unsigned sample_size = frag->size;
4764         int sample_flags = i ? frag->flags : first_sample_flags;
4765         unsigned sample_duration = frag->duration;
4766         unsigned ctts_duration = 0;
4767         int keyframe = 0;
4768         int index_entry_flags = 0;
4769
4770         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4771         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
4772         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
4773         if (flags & MOV_TRUN_SAMPLE_CTS)      ctts_duration   = avio_rb32(pb);
4774
4775         mov_update_dts_shift(sc, ctts_duration);
4776         if (pts != AV_NOPTS_VALUE) {
4777             dts = pts - sc->dts_shift;
4778             if (flags & MOV_TRUN_SAMPLE_CTS) {
4779                 dts -= ctts_duration;
4780             } else {
4781                 dts -= sc->time_offset;
4782             }
4783             av_log(c->fc, AV_LOG_DEBUG,
4784                    "pts %"PRId64" calculated dts %"PRId64
4785                    " sc->dts_shift %d ctts.duration %d"
4786                    " sc->time_offset %"PRId64
4787                    " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4788                    pts, dts,
4789                    sc->dts_shift, ctts_duration,
4790                    sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4791             pts = AV_NOPTS_VALUE;
4792         }
4793
4794         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4795             keyframe = 1;
4796         else
4797             keyframe =
4798                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4799                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4800         if (keyframe) {
4801             distance = 0;
4802             index_entry_flags |= AVINDEX_KEYFRAME;
4803         }
4804         // Fragments can overlap in time.  Discard overlapping frames after
4805         // decoding.
4806         if (prev_dts >= dts)
4807             index_entry_flags |= AVINDEX_DISCARD_FRAME;
4808
4809         st->index_entries[index_entry_pos].pos = offset;
4810         st->index_entries[index_entry_pos].timestamp = dts;
4811         st->index_entries[index_entry_pos].size= sample_size;
4812         st->index_entries[index_entry_pos].min_distance= distance;
4813         st->index_entries[index_entry_pos].flags = index_entry_flags;
4814
4815         sc->ctts_data[index_entry_pos].count = 1;
4816         sc->ctts_data[index_entry_pos].duration = ctts_duration;
4817         index_entry_pos++;
4818
4819         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4820                 "size %u, distance %d, keyframe %d\n", st->index,
4821                 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4822         distance++;
4823         dts += sample_duration;
4824         offset += sample_size;
4825         sc->data_size += sample_size;
4826
4827         if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
4828             1 <= INT64_MAX - sc->nb_frames_for_fps
4829         ) {
4830             sc->duration_for_fps += sample_duration;
4831             sc->nb_frames_for_fps ++;
4832         }
4833     }
4834     if (i < entries) {
4835         // EOF found before reading all entries.  Fix the hole this would
4836         // leave in index_entries and ctts_data
4837         int gap = entries - i;
4838         memmove(st->index_entries + index_entry_pos,
4839                 st->index_entries + index_entry_pos + gap,
4840                 sizeof(*st->index_entries) *
4841                 (st->nb_index_entries - (index_entry_pos + gap)));
4842         memmove(sc->ctts_data + index_entry_pos,
4843                 sc->ctts_data + index_entry_pos + gap,
4844                 sizeof(*sc->ctts_data) *
4845                 (sc->ctts_count - (index_entry_pos + gap)));
4846
4847         st->nb_index_entries -= gap;
4848         sc->ctts_count -= gap;
4849         if (index_entry_pos < sc->current_sample) {
4850             sc->current_sample -= gap;
4851         }
4852         entries = i;
4853     }
4854
4855     // The end of this new fragment may overlap in time with the start
4856     // of the next fragment in index_entries. Mark the samples in the next
4857     // fragment that overlap with AVINDEX_DISCARD_FRAME
4858     prev_dts = AV_NOPTS_VALUE;
4859     if (index_entry_pos > 0)
4860         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4861     for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4862         if (prev_dts < st->index_entries[i].timestamp)
4863             break;
4864         st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4865     }
4866
4867     // If a hole was created to insert the new index_entries into,
4868     // the index_entry recorded for all subsequent moof must
4869     // be incremented by the number of entries inserted.
4870     fix_frag_index_entries(&c->frag_index, next_frag_index,
4871                            frag->track_id, entries);
4872
4873     if (pb->eof_reached) {
4874         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4875         return AVERROR_EOF;
4876     }
4877
4878     frag->implicit_offset = offset;
4879
4880     sc->track_end = dts + sc->time_offset;
4881     if (st->duration < sc->track_end)
4882         st->duration = sc->track_end;
4883
4884     return 0;
4885 }
4886
4887 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4888 {
4889     int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4890     uint8_t version;
4891     unsigned i, j, track_id, item_count;
4892     AVStream *st = NULL;
4893     AVStream *ref_st = NULL;
4894     MOVStreamContext *sc, *ref_sc = NULL;
4895     AVRational timescale;
4896
4897     version = avio_r8(pb);
4898     if (version > 1) {
4899         avpriv_request_sample(c->fc, "sidx version %u", version);
4900         return 0;
4901     }
4902
4903     avio_rb24(pb); // flags
4904
4905     track_id = avio_rb32(pb); // Reference ID
4906     for (i = 0; i < c->fc->nb_streams; i++) {
4907         if (c->fc->streams[i]->id == track_id) {
4908             st = c->fc->streams[i];
4909             break;
4910         }
4911     }
4912     if (!st) {
4913         av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4914         return 0;
4915     }
4916
4917     sc = st->priv_data;
4918
4919     timescale = av_make_q(1, avio_rb32(pb));
4920
4921     if (timescale.den <= 0) {
4922         av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4923         return AVERROR_INVALIDDATA;
4924     }
4925
4926     if (version == 0) {
4927         pts = avio_rb32(pb);
4928         offset += avio_rb32(pb);
4929     } else {
4930         pts = avio_rb64(pb);
4931         offset += avio_rb64(pb);
4932     }
4933
4934     avio_rb16(pb); // reserved
4935
4936     item_count = avio_rb16(pb);
4937
4938     for (i = 0; i < item_count; i++) {
4939         int index;
4940         MOVFragmentStreamInfo * frag_stream_info;
4941         uint32_t size = avio_rb32(pb);
4942         uint32_t duration = avio_rb32(pb);
4943         if (size & 0x80000000) {
4944             avpriv_request_sample(c->fc, "sidx reference_type 1");
4945             return AVERROR_PATCHWELCOME;
4946         }
4947         avio_rb32(pb); // sap_flags
4948         timestamp = av_rescale_q(pts, st->time_base, timescale);
4949
4950         index = update_frag_index(c, offset);
4951         frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4952         if (frag_stream_info)
4953             frag_stream_info->sidx_pts = timestamp;
4954
4955         offset += size;
4956         pts += duration;
4957     }
4958
4959     st->duration = sc->track_end = pts;
4960
4961     sc->has_sidx = 1;
4962
4963     if (offset == avio_size(pb)) {
4964         // Find first entry in fragment index that came from an sidx.
4965         // This will pretty much always be the first entry.
4966         for (i = 0; i < c->frag_index.nb_items; i++) {
4967             MOVFragmentIndexItem * item = &c->frag_index.item[i];
4968             for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4969                 MOVFragmentStreamInfo * si;
4970                 si = &item->stream_info[j];
4971                 if (si->sidx_pts != AV_NOPTS_VALUE) {
4972                     ref_st = c->fc->streams[j];
4973                     ref_sc = ref_st->priv_data;
4974                     break;
4975                 }
4976             }
4977         }
4978         for (i = 0; i < c->fc->nb_streams; i++) {
4979             st = c->fc->streams[i];
4980             sc = st->priv_data;
4981             if (!sc->has_sidx) {
4982                 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4983             }
4984         }
4985
4986         c->frag_index.complete = 1;
4987     }
4988
4989     return 0;
4990 }
4991
4992 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4993 /* like the files created with Adobe Premiere 5.0, for samples see */
4994 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4995 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4996 {
4997     int err;
4998
4999     if (atom.size < 8)
5000         return 0; /* continue */
5001     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
5002         avio_skip(pb, atom.size - 4);
5003         return 0;
5004     }
5005     atom.type = avio_rl32(pb);
5006     atom.size -= 8;
5007     if (atom.type != MKTAG('m','d','a','t')) {
5008         avio_skip(pb, atom.size);
5009         return 0;
5010     }
5011     err = mov_read_mdat(c, pb, atom);
5012     return err;
5013 }
5014
5015 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5016 {
5017 #if CONFIG_ZLIB
5018     AVIOContext ctx;
5019     uint8_t *cmov_data;
5020     uint8_t *moov_data; /* uncompressed data */
5021     long cmov_len, moov_len;
5022     int ret = -1;
5023
5024     avio_rb32(pb); /* dcom atom */
5025     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
5026         return AVERROR_INVALIDDATA;
5027     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
5028         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
5029         return AVERROR_INVALIDDATA;
5030     }
5031     avio_rb32(pb); /* cmvd atom */
5032     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
5033         return AVERROR_INVALIDDATA;
5034     moov_len = avio_rb32(pb); /* uncompressed size */
5035     cmov_len = atom.size - 6 * 4;
5036
5037     cmov_data = av_malloc(cmov_len);
5038     if (!cmov_data)
5039         return AVERROR(ENOMEM);
5040     moov_data = av_malloc(moov_len);
5041     if (!moov_data) {
5042         av_free(cmov_data);
5043         return AVERROR(ENOMEM);
5044     }
5045     ret = ffio_read_size(pb, cmov_data, cmov_len);
5046     if (ret < 0)
5047         goto free_and_return;
5048
5049     ret = AVERROR_INVALIDDATA;
5050     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5051         goto free_and_return;
5052     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5053         goto free_and_return;
5054     ctx.seekable = AVIO_SEEKABLE_NORMAL;
5055     atom.type = MKTAG('m','o','o','v');
5056     atom.size = moov_len;
5057     ret = mov_read_default(c, &ctx, atom);
5058 free_and_return:
5059     av_free(moov_data);
5060     av_free(cmov_data);
5061     return ret;
5062 #else
5063     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5064     return AVERROR(ENOSYS);
5065 #endif
5066 }
5067
5068 /* edit list atom */
5069 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5070 {
5071     MOVStreamContext *sc;
5072     int i, edit_count, version;
5073     int64_t elst_entry_size;
5074
5075     if (c->fc->nb_streams < 1 || c->ignore_editlist)
5076         return 0;
5077     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5078
5079     version = avio_r8(pb); /* version */
5080     avio_rb24(pb); /* flags */
5081     edit_count = avio_rb32(pb); /* entries */
5082     atom.size -= 8;
5083
5084     elst_entry_size = version == 1 ? 20 : 12;
5085     if (atom.size != edit_count * elst_entry_size) {
5086         if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5087             av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5088                    edit_count, atom.size + 8);
5089             return AVERROR_INVALIDDATA;
5090         } else {
5091             edit_count = atom.size / elst_entry_size;
5092             if (edit_count * elst_entry_size != atom.size) {
5093                 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5094             }
5095         }
5096     }
5097
5098     if (!edit_count)
5099         return 0;
5100     if (sc->elst_data)
5101         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5102     av_free(sc->elst_data);
5103     sc->elst_count = 0;
5104     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5105     if (!sc->elst_data)
5106         return AVERROR(ENOMEM);
5107
5108     av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5109     for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5110         MOVElst *e = &sc->elst_data[i];
5111
5112         if (version == 1) {
5113             e->duration = avio_rb64(pb);
5114             e->time     = avio_rb64(pb);
5115             atom.size -= 16;
5116         } else {
5117             e->duration = avio_rb32(pb); /* segment duration */
5118             e->time     = (int32_t)avio_rb32(pb); /* media time */
5119             atom.size -= 8;
5120         }
5121         e->rate = avio_rb32(pb) / 65536.0;
5122         atom.size -= 4;
5123         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5124                e->duration, e->time, e->rate);
5125
5126         if (e->time < 0 && e->time != -1 &&
5127             c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5128             av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5129                    c->fc->nb_streams-1, i, e->time);
5130             return AVERROR_INVALIDDATA;
5131         }
5132     }
5133     sc->elst_count = i;
5134
5135     return 0;
5136 }
5137
5138 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5139 {
5140     MOVStreamContext *sc;
5141
5142     if (c->fc->nb_streams < 1)
5143         return AVERROR_INVALIDDATA;
5144     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5145     sc->timecode_track = avio_rb32(pb);
5146     return 0;
5147 }
5148
5149 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5150 {
5151     AVStream *st;
5152     int version, color_range, color_primaries, color_trc, color_space;
5153
5154     if (c->fc->nb_streams < 1)
5155         return 0;
5156     st = c->fc->streams[c->fc->nb_streams - 1];
5157
5158     if (atom.size < 5) {
5159         av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5160         return AVERROR_INVALIDDATA;
5161     }
5162
5163     version = avio_r8(pb);
5164     if (version != 1) {
5165         av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5166         return 0;
5167     }
5168     avio_skip(pb, 3); /* flags */
5169
5170     avio_skip(pb, 2); /* profile + level */
5171     color_range     = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5172     color_primaries = avio_r8(pb);
5173     color_trc       = avio_r8(pb);
5174     color_space     = avio_r8(pb);
5175     if (avio_rb16(pb)) /* codecIntializationDataSize */
5176         return AVERROR_INVALIDDATA;
5177
5178     if (!av_color_primaries_name(color_primaries))
5179         color_primaries = AVCOL_PRI_UNSPECIFIED;
5180     if (!av_color_transfer_name(color_trc))
5181         color_trc = AVCOL_TRC_UNSPECIFIED;
5182     if (!av_color_space_name(color_space))
5183         color_space = AVCOL_SPC_UNSPECIFIED;
5184
5185     st->codecpar->color_range     = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5186     st->codecpar->color_primaries = color_primaries;
5187     st->codecpar->color_trc       = color_trc;
5188     st->codecpar->color_space     = color_space;
5189
5190     return 0;
5191 }
5192
5193 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5194 {
5195     MOVStreamContext *sc;
5196     const int chroma_den = 50000;
5197     const int luma_den = 10000;
5198     int i, j, version;
5199
5200     if (c->fc->nb_streams < 1)
5201         return AVERROR_INVALIDDATA;
5202
5203     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5204
5205     if (atom.size < 5) {
5206         av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5207         return AVERROR_INVALIDDATA;
5208     }
5209
5210     version = avio_r8(pb);
5211     if (version) {
5212         av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5213         return 0;
5214     }
5215     avio_skip(pb, 3); /* flags */
5216
5217     sc->mastering = av_mastering_display_metadata_alloc();
5218     if (!sc->mastering)
5219         return AVERROR(ENOMEM);
5220
5221     for (i = 0; i < 3; i++)
5222         for (j = 0; j < 2; j++)
5223             sc->mastering->display_primaries[i][j] =
5224                 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5225     for (i = 0; i < 2; i++)
5226         sc->mastering->white_point[i] =
5227             av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5228     sc->mastering->max_luminance =
5229         av_make_q(lrint(((double)avio_rb32(pb) / (1 <<  8)) * luma_den), luma_den);
5230     sc->mastering->min_luminance =
5231         av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5232
5233     sc->mastering->has_primaries = 1;
5234     sc->mastering->has_luminance = 1;
5235
5236     return 0;
5237 }
5238
5239 static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5240 {
5241     MOVStreamContext *sc;
5242     const int mapping[3] = {1, 2, 0};
5243     const int chroma_den = 50000;
5244     const int luma_den = 10000;
5245     int i;
5246
5247     if (c->fc->nb_streams < 1)
5248         return AVERROR_INVALIDDATA;
5249
5250     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5251
5252     if (atom.size < 24) {
5253         av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5254         return AVERROR_INVALIDDATA;
5255     }
5256
5257     sc->mastering = av_mastering_display_metadata_alloc();
5258     if (!sc->mastering)
5259         return AVERROR(ENOMEM);
5260
5261     for (i = 0; i < 3; i++) {
5262         const int j = mapping[i];
5263         sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5264         sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5265     }
5266     sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5267     sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5268
5269     sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5270     sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5271
5272     sc->mastering->has_luminance = 1;
5273     sc->mastering->has_primaries = 1;
5274
5275     return 0;
5276 }
5277
5278 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5279 {
5280     MOVStreamContext *sc;
5281     int version;
5282
5283     if (c->fc->nb_streams < 1)
5284         return AVERROR_INVALIDDATA;
5285
5286     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5287
5288     if (atom.size < 5) {
5289         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5290         return AVERROR_INVALIDDATA;
5291     }
5292
5293     version = avio_r8(pb);
5294     if (version) {
5295         av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5296         return 0;
5297     }
5298     avio_skip(pb, 3); /* flags */
5299
5300     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5301     if (!sc->coll)
5302         return AVERROR(ENOMEM);
5303
5304     sc->coll->MaxCLL  = avio_rb16(pb);
5305     sc->coll->MaxFALL = avio_rb16(pb);
5306
5307     return 0;
5308 }
5309
5310 static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5311 {
5312     MOVStreamContext *sc;
5313
5314     if (c->fc->nb_streams < 1)
5315         return AVERROR_INVALIDDATA;
5316
5317     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5318
5319     if (atom.size < 4) {
5320         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5321         return AVERROR_INVALIDDATA;
5322     }
5323
5324     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5325     if (!sc->coll)
5326         return AVERROR(ENOMEM);
5327
5328     sc->coll->MaxCLL  = avio_rb16(pb);
5329     sc->coll->MaxFALL = avio_rb16(pb);
5330
5331     return 0;
5332 }
5333
5334 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5335 {
5336     AVStream *st;
5337     MOVStreamContext *sc;
5338     enum AVStereo3DType type;
5339     int mode;
5340
5341     if (c->fc->nb_streams < 1)
5342         return 0;
5343
5344     st = c->fc->streams[c->fc->nb_streams - 1];
5345     sc = st->priv_data;
5346
5347     if (atom.size < 5) {
5348         av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5349         return AVERROR_INVALIDDATA;
5350     }
5351     avio_skip(pb, 4); /* version + flags */
5352
5353     mode = avio_r8(pb);
5354     switch (mode) {
5355     case 0:
5356         type = AV_STEREO3D_2D;
5357         break;
5358     case 1:
5359         type = AV_STEREO3D_TOPBOTTOM;
5360         break;
5361     case 2:
5362         type = AV_STEREO3D_SIDEBYSIDE;
5363         break;
5364     default:
5365         av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5366         return 0;
5367     }
5368
5369     sc->stereo3d = av_stereo3d_alloc();
5370     if (!sc->stereo3d)
5371         return AVERROR(ENOMEM);
5372
5373     sc->stereo3d->type = type;
5374     return 0;
5375 }
5376
5377 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5378 {
5379     AVStream *st;
5380     MOVStreamContext *sc;
5381     int size, version, layout;
5382     int32_t yaw, pitch, roll;
5383     uint32_t l = 0, t = 0, r = 0, b = 0;
5384     uint32_t tag, padding = 0;
5385     enum AVSphericalProjection projection;
5386
5387     if (c->fc->nb_streams < 1)
5388         return 0;
5389
5390     st = c->fc->streams[c->fc->nb_streams - 1];
5391     sc = st->priv_data;
5392
5393     if (atom.size < 8) {
5394         av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5395         return AVERROR_INVALIDDATA;
5396     }
5397
5398     size = avio_rb32(pb);
5399     if (size <= 12 || size > atom.size)
5400         return AVERROR_INVALIDDATA;
5401
5402     tag = avio_rl32(pb);
5403     if (tag != MKTAG('s','v','h','d')) {
5404         av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5405         return 0;
5406     }
5407     version = avio_r8(pb);
5408     if (version != 0) {
5409         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5410                version);
5411         return 0;
5412     }
5413     avio_skip(pb, 3); /* flags */
5414     avio_skip(pb, size - 12); /* metadata_source */
5415
5416     size = avio_rb32(pb);
5417     if (size > atom.size)
5418         return AVERROR_INVALIDDATA;
5419
5420     tag = avio_rl32(pb);
5421     if (tag != MKTAG('p','r','o','j')) {
5422         av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5423         return 0;
5424     }
5425
5426     size = avio_rb32(pb);
5427     if (size > atom.size)
5428         return AVERROR_INVALIDDATA;
5429
5430     tag = avio_rl32(pb);
5431     if (tag != MKTAG('p','r','h','d')) {
5432         av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5433         return 0;
5434     }
5435     version = avio_r8(pb);
5436     if (version != 0) {
5437         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5438                version);
5439         return 0;
5440     }
5441     avio_skip(pb, 3); /* flags */
5442
5443     /* 16.16 fixed point */
5444     yaw   = avio_rb32(pb);
5445     pitch = avio_rb32(pb);
5446     roll  = avio_rb32(pb);
5447
5448     size = avio_rb32(pb);
5449     if (size > atom.size)
5450         return AVERROR_INVALIDDATA;
5451
5452     tag = avio_rl32(pb);
5453     version = avio_r8(pb);
5454     if (version != 0) {
5455         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5456                version);
5457         return 0;
5458     }
5459     avio_skip(pb, 3); /* flags */
5460     switch (tag) {
5461     case MKTAG('c','b','m','p'):
5462         layout = avio_rb32(pb);
5463         if (layout) {
5464             av_log(c->fc, AV_LOG_WARNING,
5465                    "Unsupported cubemap layout %d\n", layout);
5466             return 0;
5467         }
5468         projection = AV_SPHERICAL_CUBEMAP;
5469         padding = avio_rb32(pb);
5470         break;
5471     case MKTAG('e','q','u','i'):
5472         t = avio_rb32(pb);
5473         b = avio_rb32(pb);
5474         l = avio_rb32(pb);
5475         r = avio_rb32(pb);
5476
5477         if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5478             av_log(c->fc, AV_LOG_ERROR,
5479                    "Invalid bounding rectangle coordinates "
5480                    "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5481             return AVERROR_INVALIDDATA;
5482         }
5483
5484         if (l || t || r || b)
5485             projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5486         else
5487             projection = AV_SPHERICAL_EQUIRECTANGULAR;
5488         break;
5489     default:
5490         av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5491         return 0;
5492     }
5493
5494     sc->spherical = av_spherical_alloc(&sc->spherical_size);
5495     if (!sc->spherical)
5496         return AVERROR(ENOMEM);
5497
5498     sc->spherical->projection = projection;
5499
5500     sc->spherical->yaw   = yaw;
5501     sc->spherical->pitch = pitch;
5502     sc->spherical->roll  = roll;
5503
5504     sc->spherical->padding = padding;
5505
5506     sc->spherical->bound_left   = l;
5507     sc->spherical->bound_top    = t;
5508     sc->spherical->bound_right  = r;
5509     sc->spherical->bound_bottom = b;
5510
5511     return 0;
5512 }
5513
5514 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5515 {
5516     int ret = 0;
5517     uint8_t *buffer = av_malloc(len + 1);
5518     const char *val;
5519
5520     if (!buffer)
5521         return AVERROR(ENOMEM);
5522     buffer[len] = '\0';
5523
5524     ret = ffio_read_size(pb, buffer, len);
5525     if (ret < 0)
5526         goto out;
5527
5528     /* Check for mandatory keys and values, try to support XML as best-effort */
5529     if (!sc->spherical &&
5530         av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5531         (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5532         av_stristr(val, "true") &&
5533         (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5534         av_stristr(val, "true") &&
5535         (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5536         av_stristr(val, "equirectangular")) {
5537         sc->spherical = av_spherical_alloc(&sc->spherical_size);
5538         if (!sc->spherical)
5539             goto out;
5540
5541         sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5542
5543         if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5544             enum AVStereo3DType mode;
5545
5546             if (av_stristr(buffer, "left-right"))
5547                 mode = AV_STEREO3D_SIDEBYSIDE;
5548             else if (av_stristr(buffer, "top-bottom"))
5549                 mode = AV_STEREO3D_TOPBOTTOM;
5550             else
5551                 mode = AV_STEREO3D_2D;
5552
5553             sc->stereo3d = av_stereo3d_alloc();
5554             if (!sc->stereo3d)
5555                 goto out;
5556
5557             sc->stereo3d->type = mode;
5558         }
5559
5560         /* orientation */
5561         val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5562         if (val)
5563             sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5564         val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5565         if (val)
5566             sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5567         val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5568         if (val)
5569             sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5570     }
5571
5572 out:
5573     av_free(buffer);
5574     return ret;
5575 }
5576
5577 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5578 {
5579     AVStream *st;
5580     MOVStreamContext *sc;
5581     int64_t ret;
5582     uint8_t uuid[16];
5583     static const uint8_t uuid_isml_manifest[] = {
5584         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5585         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5586     };
5587     static const uint8_t uuid_xmp[] = {
5588         0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5589         0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5590     };
5591     static const uint8_t uuid_spherical[] = {
5592         0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5593         0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5594     };
5595
5596     if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5597         return AVERROR_INVALIDDATA;
5598
5599     if (c->fc->nb_streams < 1)
5600         return 0;
5601     st = c->fc->streams[c->fc->nb_streams - 1];
5602     sc = st->priv_data;
5603
5604     ret = avio_read(pb, uuid, sizeof(uuid));
5605     if (ret < 0) {
5606         return ret;
5607     } else if (ret != sizeof(uuid)) {
5608         return AVERROR_INVALIDDATA;
5609     }
5610     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5611         uint8_t *buffer, *ptr;
5612         char *endptr;
5613         size_t len = atom.size - sizeof(uuid);
5614
5615         if (len < 4) {
5616             return AVERROR_INVALIDDATA;
5617         }
5618         ret = avio_skip(pb, 4); // zeroes
5619         len -= 4;
5620
5621         buffer = av_mallocz(len + 1);
5622         if (!buffer) {
5623             return AVERROR(ENOMEM);
5624         }
5625         ret = avio_read(pb, buffer, len);
5626         if (ret < 0) {
5627             av_free(buffer);
5628             return ret;
5629         } else if (ret != len) {
5630             av_free(buffer);
5631             return AVERROR_INVALIDDATA;
5632         }
5633
5634         ptr = buffer;
5635         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5636             ptr += sizeof("systemBitrate=\"") - 1;
5637             c->bitrates_count++;
5638             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5639             if (!c->bitrates) {
5640                 c->bitrates_count = 0;
5641                 av_free(buffer);
5642                 return AVERROR(ENOMEM);
5643             }
5644             errno = 0;
5645             ret = strtol(ptr, &endptr, 10);
5646             if (ret < 0 || errno || *endptr != '"') {
5647                 c->bitrates[c->bitrates_count - 1] = 0;
5648             } else {
5649                 c->bitrates[c->bitrates_count - 1] = ret;
5650             }
5651         }
5652
5653         av_free(buffer);
5654     } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5655         uint8_t *buffer;
5656         size_t len = atom.size - sizeof(uuid);
5657         if (c->export_xmp) {
5658             buffer = av_mallocz(len + 1);
5659             if (!buffer) {
5660                 return AVERROR(ENOMEM);
5661             }
5662             ret = avio_read(pb, buffer, len);
5663             if (ret < 0) {
5664                 av_free(buffer);
5665                 return ret;
5666             } else if (ret != len) {
5667                 av_free(buffer);
5668                 return AVERROR_INVALIDDATA;
5669             }
5670             buffer[len] = '\0';
5671             av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5672             av_free(buffer);
5673         } else {
5674             // skip all uuid atom, which makes it fast for long uuid-xmp file
5675             ret = avio_skip(pb, len);
5676             if (ret < 0)
5677                 return ret;
5678         }
5679     } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5680         size_t len = atom.size - sizeof(uuid);
5681         ret = mov_parse_uuid_spherical(sc, pb, len);
5682         if (ret < 0)
5683             return ret;
5684         if (!sc->spherical)
5685             av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5686     }
5687
5688     return 0;
5689 }
5690
5691 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5692 {
5693     int ret;
5694     uint8_t content[16];
5695
5696     if (atom.size < 8)
5697         return 0;
5698
5699     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5700     if (ret < 0)
5701         return ret;
5702
5703     if (   !c->found_moov
5704         && !c->found_mdat
5705         && !memcmp(content, "Anevia\x1A\x1A", 8)
5706         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5707         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5708     }
5709
5710     return 0;
5711 }
5712
5713 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5714 {
5715     uint32_t format = avio_rl32(pb);
5716     MOVStreamContext *sc;
5717     enum AVCodecID id;
5718     AVStream *st;
5719
5720     if (c->fc->nb_streams < 1)
5721         return 0;
5722     st = c->fc->streams[c->fc->nb_streams - 1];
5723     sc = st->priv_data;
5724
5725     switch (sc->format)
5726     {
5727     case MKTAG('e','n','c','v'):        // encrypted video
5728     case MKTAG('e','n','c','a'):        // encrypted audio
5729         id = mov_codec_id(st, format);
5730         if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5731             st->codecpar->codec_id != id) {
5732             av_log(c->fc, AV_LOG_WARNING,
5733                    "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5734                    (char*)&format, st->codecpar->codec_id);
5735             break;
5736         }
5737
5738         st->codecpar->codec_id = id;
5739         sc->format = format;
5740         break;
5741
5742     default:
5743         if (format != sc->format) {
5744             av_log(c->fc, AV_LOG_WARNING,
5745                    "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5746                    (char*)&format, (char*)&sc->format);
5747         }
5748         break;
5749     }
5750
5751     return 0;
5752 }
5753
5754 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5755 {
5756     AVStream *st;
5757     MOVStreamContext *sc;
5758     size_t auxiliary_info_size;
5759
5760     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5761         return 0;
5762
5763     st = c->fc->streams[c->fc->nb_streams - 1];
5764     sc = st->priv_data;
5765
5766     if (sc->cenc.aes_ctr) {
5767         av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5768         return AVERROR_INVALIDDATA;
5769     }
5770
5771     avio_r8(pb); /* version */
5772     sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5773
5774     avio_rb32(pb);        /* entries */
5775
5776     if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5777         av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5778         return AVERROR_INVALIDDATA;
5779     }
5780
5781     /* save the auxiliary info as is */
5782     auxiliary_info_size = atom.size - 8;
5783
5784     sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5785     if (!sc->cenc.auxiliary_info) {
5786         return AVERROR(ENOMEM);
5787     }
5788
5789     sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5790     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5791     sc->cenc.auxiliary_info_index = 0;
5792
5793     if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5794         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5795         return AVERROR_INVALIDDATA;
5796     }
5797
5798     /* initialize the cipher */
5799     sc->cenc.aes_ctr = av_aes_ctr_alloc();
5800     if (!sc->cenc.aes_ctr) {
5801         return AVERROR(ENOMEM);
5802     }
5803
5804     return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5805 }
5806
5807 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5808 {
5809     AVStream *st;
5810     MOVStreamContext *sc;
5811     size_t data_size;
5812     int atom_header_size;
5813     int flags;
5814
5815     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5816         return 0;
5817
5818     st = c->fc->streams[c->fc->nb_streams - 1];
5819     sc = st->priv_data;
5820
5821     if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5822         av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5823         return AVERROR_INVALIDDATA;
5824     }
5825
5826     atom_header_size = 9;
5827
5828     avio_r8(pb); /* version */
5829     flags = avio_rb24(pb);
5830
5831     if ((flags & 0x01) != 0) {
5832         atom_header_size += 8;
5833
5834         avio_rb32(pb);    /* info type */
5835         avio_rb32(pb);    /* info type param */
5836     }
5837
5838     sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5839     avio_rb32(pb);    /* entries */
5840
5841     if (atom.size <= atom_header_size) {
5842         return 0;
5843     }
5844
5845     if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5846         av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5847         return AVERROR_INVALIDDATA;
5848     }
5849
5850     /* save the auxiliary info sizes as is */
5851     data_size = atom.size - atom_header_size;
5852
5853     sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5854     if (!sc->cenc.auxiliary_info_sizes) {
5855         return AVERROR(ENOMEM);
5856     }
5857
5858     sc->cenc.auxiliary_info_sizes_count = data_size;
5859
5860     if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5861         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5862         return AVERROR_INVALIDDATA;
5863     }
5864
5865     return 0;
5866 }
5867
5868 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5869 {
5870     AVStream *st;
5871     int last, type, size, ret;
5872     uint8_t buf[4];
5873
5874     if (c->fc->nb_streams < 1)
5875         return 0;
5876     st = c->fc->streams[c->fc->nb_streams-1];
5877
5878     if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5879         return AVERROR_INVALIDDATA;
5880
5881     /* Check FlacSpecificBox version. */
5882     if (avio_r8(pb) != 0)
5883         return AVERROR_INVALIDDATA;
5884
5885     avio_rb24(pb); /* Flags */
5886
5887     avio_read(pb, buf, sizeof(buf));
5888     flac_parse_block_header(buf, &last, &type, &size);
5889
5890     if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5891         av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5892         return AVERROR_INVALIDDATA;
5893     }
5894
5895     ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5896     if (ret < 0)
5897         return ret;
5898
5899     if (!last)
5900         av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5901
5902     return 0;
5903 }
5904
5905 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5906 {
5907     size_t auxiliary_info_seek_offset = 0;
5908     int i;
5909
5910     if (sc->cenc.auxiliary_info_default_size) {
5911         auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5912     } else if (sc->cenc.auxiliary_info_sizes) {
5913         if (index > sc->cenc.auxiliary_info_sizes_count) {
5914             av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5915                 index, sc->cenc.auxiliary_info_sizes_count);
5916             return AVERROR_INVALIDDATA;
5917         }
5918
5919         for (i = 0; i < index; i++) {
5920             auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5921         }
5922     }
5923
5924     if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5925         av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5926             auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5927         return AVERROR_INVALIDDATA;
5928     }
5929
5930     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5931     sc->cenc.auxiliary_info_index = index;
5932     return 0;
5933 }
5934
5935 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5936 {
5937     uint32_t encrypted_bytes;
5938     uint16_t subsample_count;
5939     uint16_t clear_bytes;
5940     uint8_t* input_end = input + size;
5941     int ret;
5942
5943     if (index != sc->cenc.auxiliary_info_index) {
5944         ret = mov_seek_auxiliary_info(c, sc, index);
5945         if (ret < 0) {
5946             return ret;
5947         }
5948     }
5949
5950     /* read the iv */
5951     if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5952         av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5953         return AVERROR_INVALIDDATA;
5954     }
5955
5956     av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5957     sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5958
5959     if (!sc->cenc.use_subsamples)
5960     {
5961         /* decrypt the whole packet */
5962         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5963         return 0;
5964     }
5965
5966     /* read the subsample count */
5967     if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5968         av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5969         return AVERROR_INVALIDDATA;
5970     }
5971
5972     subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5973     sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5974
5975     for (; subsample_count > 0; subsample_count--)
5976     {
5977         if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5978             av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5979             return AVERROR_INVALIDDATA;
5980         }
5981
5982         /* read the number of clear / encrypted bytes */
5983         clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5984         sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5985         encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5986         sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5987
5988         if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5989             av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5990             return AVERROR_INVALIDDATA;
5991         }
5992
5993         /* skip the clear bytes */
5994         input += clear_bytes;
5995
5996         /* decrypt the encrypted bytes */
5997         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5998         input += encrypted_bytes;
5999     }
6000
6001     if (input < input_end) {
6002         av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
6003         return AVERROR_INVALIDDATA;
6004     }
6005
6006     sc->cenc.auxiliary_info_index++;
6007     return 0;
6008 }
6009
6010 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6011 {
6012     const int OPUS_SEEK_PREROLL_MS = 80;
6013     AVStream *st;
6014     size_t size;
6015     int16_t pre_skip;
6016
6017     if (c->fc->nb_streams < 1)
6018         return 0;
6019     st = c->fc->streams[c->fc->nb_streams-1];
6020
6021     if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6022         return AVERROR_INVALIDDATA;
6023
6024     /* Check OpusSpecificBox version. */
6025     if (avio_r8(pb) != 0) {
6026         av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6027         return AVERROR_INVALIDDATA;
6028     }
6029
6030     /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6031     size = atom.size + 8;
6032
6033     if (ff_alloc_extradata(st->codecpar, size))
6034         return AVERROR(ENOMEM);
6035
6036     AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6037     AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6038     AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6039     avio_read(pb, st->codecpar->extradata + 9, size - 9);
6040
6041     /* OpusSpecificBox is stored in big-endian, but OpusHead is
6042        little-endian; aside from the preceeding magic and version they're
6043        otherwise currently identical.  Data after output gain at offset 16
6044        doesn't need to be bytewapped. */
6045     pre_skip = AV_RB16(st->codecpar->extradata + 10);
6046     AV_WL16(st->codecpar->extradata + 10, pre_skip);
6047     AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6048     AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6049
6050     st->codecpar->initial_padding = pre_skip;
6051     st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6052                                               (AVRational){1, 1000},
6053                                               (AVRational){1, 48000});
6054
6055     return 0;
6056 }
6057
6058 static const MOVParseTableEntry mov_default_parse_table[] = {
6059 { MKTAG('A','C','L','R'), mov_read_aclr },
6060 { MKTAG('A','P','R','G'), mov_read_avid },
6061 { MKTAG('A','A','L','P'), mov_read_avid },
6062 { MKTAG('A','R','E','S'), mov_read_ares },
6063 { MKTAG('a','v','s','s'), mov_read_avss },
6064 { MKTAG('c','h','p','l'), mov_read_chpl },
6065 { MKTAG('c','o','6','4'), mov_read_stco },
6066 { MKTAG('c','o','l','r'), mov_read_colr },
6067 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6068 { MKTAG('d','i','n','f'), mov_read_default },
6069 { MKTAG('D','p','x','E'), mov_read_dpxe },
6070 { MKTAG('d','r','e','f'), mov_read_dref },
6071 { MKTAG('e','d','t','s'), mov_read_default },
6072 { MKTAG('e','l','s','t'), mov_read_elst },
6073 { MKTAG('e','n','d','a'), mov_read_enda },
6074 { MKTAG('f','i','e','l'), mov_read_fiel },
6075 { MKTAG('a','d','r','m'), mov_read_adrm },
6076 { MKTAG('f','t','y','p'), mov_read_ftyp },
6077 { MKTAG('g','l','b','l'), mov_read_glbl },
6078 { MKTAG('h','d','l','r'), mov_read_hdlr },
6079 { MKTAG('i','l','s','t'), mov_read_ilst },
6080 { MKTAG('j','p','2','h'), mov_read_jp2h },
6081 { MKTAG('m','d','a','t'), mov_read_mdat },
6082 { MKTAG('m','d','h','d'), mov_read_mdhd },
6083 { MKTAG('m','d','i','a'), mov_read_default },
6084 { MKTAG('m','e','t','a'), mov_read_meta },
6085 { MKTAG('m','i','n','f'), mov_read_default },
6086 { MKTAG('m','o','o','f'), mov_read_moof },
6087 { MKTAG('m','o','o','v'), mov_read_moov },
6088 { MKTAG('m','v','e','x'), mov_read_default },
6089 { MKTAG('m','v','h','d'), mov_read_mvhd },
6090 { MKTAG('S','M','I',' '), mov_read_svq3 },
6091 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6092 { MKTAG('a','v','c','C'), mov_read_glbl },
6093 { MKTAG('p','a','s','p'), mov_read_pasp },
6094 { MKTAG('s','i','d','x'), mov_read_sidx },
6095 { MKTAG('s','t','b','l'), mov_read_default },
6096 { MKTAG('s','t','c','o'), mov_read_stco },
6097 { MKTAG('s','t','p','s'), mov_read_stps },
6098 { MKTAG('s','t','r','f'), mov_read_strf },
6099 { MKTAG('s','t','s','c'), mov_read_stsc },
6100 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6101 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6102 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6103 { MKTAG('s','t','t','s'), mov_read_stts },
6104 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6105 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6106 { MKTAG('t','f','d','t'), mov_read_tfdt },
6107 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6108 { MKTAG('t','r','a','k'), mov_read_trak },
6109 { MKTAG('t','r','a','f'), mov_read_default },
6110 { MKTAG('t','r','e','f'), mov_read_default },
6111 { MKTAG('t','m','c','d'), mov_read_tmcd },
6112 { MKTAG('c','h','a','p'), mov_read_chap },
6113 { MKTAG('t','r','e','x'), mov_read_trex },
6114 { MKTAG('t','r','u','n'), mov_read_trun },
6115 { MKTAG('u','d','t','a'), mov_read_default },
6116 { MKTAG('w','a','v','e'), mov_read_wave },
6117 { MKTAG('e','s','d','s'), mov_read_esds },
6118 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6119 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6120 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6121 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6122 { MKTAG('w','f','e','x'), mov_read_wfex },
6123 { MKTAG('c','m','o','v'), mov_read_cmov },
6124 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6125 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6126 { MKTAG('s','b','g','p'), mov_read_sbgp },
6127 { MKTAG('h','v','c','C'), mov_read_glbl },
6128 { MKTAG('u','u','i','d'), mov_read_uuid },
6129 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6130 { MKTAG('f','r','e','e'), mov_read_free },
6131 { MKTAG('-','-','-','-'), mov_read_custom },
6132 { MKTAG('s','i','n','f'), mov_read_default },
6133 { MKTAG('f','r','m','a'), mov_read_frma },
6134 { MKTAG('s','e','n','c'), mov_read_senc },
6135 { MKTAG('s','a','i','z'), mov_read_saiz },
6136 { MKTAG('d','f','L','a'), mov_read_dfla },
6137 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6138 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6139 { MKTAG('d','O','p','s'), mov_read_dops },
6140 { MKTAG('S','m','D','m'), mov_read_smdm },
6141 { MKTAG('C','o','L','L'), mov_read_coll },
6142 { MKTAG('v','p','c','C'), mov_read_vpcc },
6143 { MKTAG('m','d','c','v'), mov_read_mdcv },
6144 { MKTAG('c','l','l','i'), mov_read_clli },
6145 { 0, NULL }
6146 };
6147
6148 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6149 {
6150     int64_t total_size = 0;
6151     MOVAtom a;
6152     int i;
6153
6154     if (c->atom_depth > 10) {
6155         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6156         return AVERROR_INVALIDDATA;
6157     }
6158     c->atom_depth ++;
6159
6160     if (atom.size < 0)
6161         atom.size = INT64_MAX;
6162     while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6163         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
6164         a.size = atom.size;
6165         a.type=0;
6166         if (atom.size >= 8) {
6167             a.size = avio_rb32(pb);
6168             a.type = avio_rl32(pb);
6169             if (a.type == MKTAG('f','r','e','e') &&
6170                 a.size >= 8 &&
6171                 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
6172                 c->moov_retry) {
6173                 uint8_t buf[8];
6174                 uint32_t *type = (uint32_t *)buf + 1;
6175                 if (avio_read(pb, buf, 8) != 8)
6176                     return AVERROR_INVALIDDATA;
6177                 avio_seek(pb, -8, SEEK_CUR);
6178                 if (*type == MKTAG('m','v','h','d') ||
6179                     *type == MKTAG('c','m','o','v')) {
6180                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6181                     a.type = MKTAG('m','o','o','v');
6182                 }
6183             }
6184             if (atom.type != MKTAG('r','o','o','t') &&
6185                 atom.type != MKTAG('m','o','o','v'))
6186             {
6187                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6188                 {
6189                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6190                     avio_skip(pb, -8);
6191                     c->atom_depth --;
6192                     return 0;
6193                 }
6194             }
6195             total_size += 8;
6196             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6197                 a.size = avio_rb64(pb) - 8;
6198                 total_size += 8;
6199             }
6200         }
6201         av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6202                av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6203         if (a.size == 0) {
6204             a.size = atom.size - total_size + 8;
6205         }
6206         a.size -= 8;
6207         if (a.size < 0)
6208             break;
6209         a.size = FFMIN(a.size, atom.size - total_size);
6210
6211         for (i = 0; mov_default_parse_table[i].type; i++)
6212             if (mov_default_parse_table[i].type == a.type) {
6213                 parse = mov_default_parse_table[i].parse;
6214                 break;
6215             }
6216
6217         // container is user data
6218         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6219                        atom.type == MKTAG('i','l','s','t')))
6220             parse = mov_read_udta_string;
6221
6222         // Supports parsing the QuickTime Metadata Keys.
6223         // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6224         if (!parse && c->found_hdlr_mdta &&
6225             atom.type == MKTAG('m','e','t','a') &&
6226             a.type == MKTAG('k','e','y','s')) {
6227             parse = mov_read_keys;
6228         }
6229
6230         if (!parse) { /* skip leaf atoms data */
6231             avio_skip(pb, a.size);
6232         } else {
6233             int64_t start_pos = avio_tell(pb);
6234             int64_t left;
6235             int err = parse(c, pb, a);
6236             if (err < 0) {
6237                 c->atom_depth --;
6238                 return err;
6239             }
6240             if (c->found_moov && c->found_mdat &&
6241                 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
6242                  start_pos + a.size == avio_size(pb))) {
6243                 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
6244                     c->next_root_atom = start_pos + a.size;
6245                 c->atom_depth --;
6246                 return 0;
6247             }
6248             left = a.size - avio_tell(pb) + start_pos;
6249             if (left > 0) /* skip garbage at atom end */
6250                 avio_skip(pb, left);
6251             else if (left < 0) {
6252                 av_log(c->fc, AV_LOG_WARNING,
6253                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
6254                        (char*)&a.type, -left);
6255                 avio_seek(pb, left, SEEK_CUR);
6256             }
6257         }
6258
6259         total_size += a.size;
6260     }
6261
6262     if (total_size < atom.size && atom.size < 0x7ffff)
6263         avio_skip(pb, atom.size - total_size);
6264
6265     c->atom_depth --;
6266     return 0;
6267 }
6268
6269 static int mov_probe(AVProbeData *p)
6270 {
6271     int64_t offset;
6272     uint32_t tag;
6273     int score = 0;
6274     int moov_offset = -1;
6275
6276     /* check file header */
6277     offset = 0;
6278     for (;;) {
6279         /* ignore invalid offset */
6280         if ((offset + 8) > (unsigned int)p->buf_size)
6281             break;
6282         tag = AV_RL32(p->buf + offset + 4);
6283         switch(tag) {
6284         /* check for obvious tags */
6285         case MKTAG('m','o','o','v'):
6286             moov_offset = offset + 4;
6287         case MKTAG('m','d','a','t'):
6288         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6289         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6290         case MKTAG('f','t','y','p'):
6291             if (AV_RB32(p->buf+offset) < 8 &&
6292                 (AV_RB32(p->buf+offset) != 1 ||
6293                  offset + 12 > (unsigned int)p->buf_size ||
6294                  AV_RB64(p->buf+offset + 8) == 0)) {
6295                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6296             } else if (tag == MKTAG('f','t','y','p') &&
6297                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6298                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6299                     )) {
6300                 score = FFMAX(score, 5);
6301             } else {
6302                 score = AVPROBE_SCORE_MAX;
6303             }
6304             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6305             break;
6306         /* those are more common words, so rate then a bit less */
6307         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6308         case MKTAG('w','i','d','e'):
6309         case MKTAG('f','r','e','e'):
6310         case MKTAG('j','u','n','k'):
6311         case MKTAG('p','i','c','t'):
6312             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6313             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6314             break;
6315         case MKTAG(0x82,0x82,0x7f,0x7d):
6316         case MKTAG('s','k','i','p'):
6317         case MKTAG('u','u','i','d'):
6318         case MKTAG('p','r','f','l'):
6319             /* if we only find those cause probedata is too small at least rate them */
6320             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6321             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6322             break;
6323         default:
6324             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6325         }
6326     }
6327     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6328         /* moov atom in the header - we should make sure that this is not a
6329          * MOV-packed MPEG-PS */
6330         offset = moov_offset;
6331
6332         while(offset < (p->buf_size - 16)){ /* Sufficient space */
6333                /* We found an actual hdlr atom */
6334             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
6335                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
6336                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6337                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6338                 /* We found a media handler reference atom describing an
6339                  * MPEG-PS-in-MOV, return a
6340                  * low score to force expanding the probe window until
6341                  * mpegps_probe finds what it needs */
6342                 return 5;
6343             }else
6344                 /* Keep looking */
6345                 offset+=2;
6346         }
6347     }
6348
6349     return score;
6350 }
6351
6352 // must be done after parsing all trak because there's no order requirement
6353 static void mov_read_chapters(AVFormatContext *s)
6354 {
6355     MOVContext *mov = s->priv_data;
6356     AVStream *st;
6357     MOVStreamContext *sc;
6358     int64_t cur_pos;
6359     int i, j;
6360     int chapter_track;
6361
6362     for (j = 0; j < mov->nb_chapter_tracks; j++) {
6363         chapter_track = mov->chapter_tracks[j];
6364         st = NULL;
6365         for (i = 0; i < s->nb_streams; i++)
6366             if (s->streams[i]->id == chapter_track) {
6367                 st = s->streams[i];
6368                 break;
6369             }
6370         if (!st) {
6371             av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6372             continue;
6373         }
6374
6375         sc = st->priv_data;
6376         cur_pos = avio_tell(sc->pb);
6377
6378         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6379             st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6380             if (st->nb_index_entries) {
6381                 // Retrieve the first frame, if possible
6382                 AVPacket pkt;
6383                 AVIndexEntry *sample = &st->index_entries[0];
6384                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6385                     av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6386                     goto finish;
6387                 }
6388
6389                 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6390                     goto finish;
6391
6392                 st->attached_pic              = pkt;
6393                 st->attached_pic.stream_index = st->index;
6394                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
6395             }
6396         } else {
6397             st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6398             st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6399             st->discard = AVDISCARD_ALL;
6400             for (i = 0; i < st->nb_index_entries; i++) {
6401                 AVIndexEntry *sample = &st->index_entries[i];
6402                 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6403                 uint8_t *title;
6404                 uint16_t ch;
6405                 int len, title_len;
6406
6407                 if (end < sample->timestamp) {
6408                     av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6409                     end = AV_NOPTS_VALUE;
6410                 }
6411
6412                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6413                     av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6414                     goto finish;
6415                 }
6416
6417                 // the first two bytes are the length of the title
6418                 len = avio_rb16(sc->pb);
6419                 if (len > sample->size-2)
6420                     continue;
6421                 title_len = 2*len + 1;
6422                 if (!(title = av_mallocz(title_len)))
6423                     goto finish;
6424
6425                 // The samples could theoretically be in any encoding if there's an encd
6426                 // atom following, but in practice are only utf-8 or utf-16, distinguished
6427                 // instead by the presence of a BOM
6428                 if (!len) {
6429                     title[0] = 0;
6430                 } else {
6431                     ch = avio_rb16(sc->pb);
6432                     if (ch == 0xfeff)
6433                         avio_get_str16be(sc->pb, len, title, title_len);
6434                     else if (ch == 0xfffe)
6435                         avio_get_str16le(sc->pb, len, title, title_len);
6436                     else {
6437                         AV_WB16(title, ch);
6438                         if (len == 1 || len == 2)
6439                             title[len] = 0;
6440                         else
6441                             avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6442                     }
6443                 }
6444
6445                 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6446                 av_freep(&title);
6447             }
6448         }
6449 finish:
6450         avio_seek(sc->pb, cur_pos, SEEK_SET);
6451     }
6452 }
6453
6454 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6455                                              uint32_t value, int flags)
6456 {
6457     AVTimecode tc;
6458     char buf[AV_TIMECODE_STR_SIZE];
6459     AVRational rate = st->avg_frame_rate;
6460     int ret = av_timecode_init(&tc, rate, flags, 0, s);
6461     if (ret < 0)
6462         return ret;
6463     av_dict_set(&st->metadata, "timecode",
6464                 av_timecode_make_string(&tc, buf, value), 0);
6465     return 0;
6466 }
6467
6468 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6469 {
6470     MOVStreamContext *sc = st->priv_data;
6471     char buf[AV_TIMECODE_STR_SIZE];
6472     int64_t cur_pos = avio_tell(sc->pb);
6473     int hh, mm, ss, ff, drop;
6474
6475     if (!st->nb_index_entries)
6476         return -1;
6477
6478     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6479     avio_skip(s->pb, 13);
6480     hh = avio_r8(s->pb);
6481     mm = avio_r8(s->pb);
6482     ss = avio_r8(s->pb);
6483     drop = avio_r8(s->pb);
6484     ff = avio_r8(s->pb);
6485     snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6486              hh, mm, ss, drop ? ';' : ':', ff);
6487     av_dict_set(&st->metadata, "timecode", buf, 0);
6488
6489     avio_seek(sc->pb, cur_pos, SEEK_SET);
6490     return 0;
6491 }
6492
6493 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6494 {
6495     MOVStreamContext *sc = st->priv_data;
6496     int flags = 0;
6497     int64_t cur_pos = avio_tell(sc->pb);
6498     uint32_t value;
6499
6500     if (!st->nb_index_entries)
6501         return -1;
6502
6503     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6504     value = avio_rb32(s->pb);
6505
6506     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6507     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6508     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6509
6510     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6511      * not the case) and thus assume "frame number format" instead of QT one.
6512      * No sample with tmcd track can be found with a QT timecode at the moment,
6513      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6514      * format). */
6515     parse_timecode_in_framenum_format(s, st, value, flags);
6516
6517     avio_seek(sc->pb, cur_pos, SEEK_SET);
6518     return 0;
6519 }
6520
6521 static int mov_read_close(AVFormatContext *s)
6522 {
6523     MOVContext *mov = s->priv_data;
6524     int i, j;
6525
6526     for (i = 0; i < s->nb_streams; i++) {
6527         AVStream *st = s->streams[i];
6528         MOVStreamContext *sc = st->priv_data;
6529
6530         if (!sc)
6531             continue;
6532
6533         av_freep(&sc->ctts_data);
6534         for (j = 0; j < sc->drefs_count; j++) {
6535             av_freep(&sc->drefs[j].path);
6536             av_freep(&sc->drefs[j].dir);
6537         }
6538         av_freep(&sc->drefs);
6539
6540         sc->drefs_count = 0;
6541
6542         if (!sc->pb_is_copied)
6543             ff_format_io_close(s, &sc->pb);
6544
6545         sc->pb = NULL;
6546         av_freep(&sc->chunk_offsets);
6547         av_freep(&sc->stsc_data);
6548         av_freep(&sc->sample_sizes);
6549         av_freep(&sc->keyframes);
6550         av_freep(&sc->stts_data);
6551         av_freep(&sc->stps_data);
6552         av_freep(&sc->elst_data);
6553         av_freep(&sc->rap_group);
6554         av_freep(&sc->display_matrix);
6555         av_freep(&sc->index_ranges);
6556
6557         if (sc->extradata)
6558             for (j = 0; j < sc->stsd_count; j++)
6559                 av_free(sc->extradata[j]);
6560         av_freep(&sc->extradata);
6561         av_freep(&sc->extradata_size);
6562
6563         av_freep(&sc->cenc.auxiliary_info);
6564         av_freep(&sc->cenc.auxiliary_info_sizes);
6565         av_aes_ctr_free(sc->cenc.aes_ctr);
6566
6567         av_freep(&sc->stereo3d);
6568         av_freep(&sc->spherical);
6569         av_freep(&sc->mastering);
6570         av_freep(&sc->coll);
6571     }
6572
6573     if (mov->dv_demux) {
6574         avformat_free_context(mov->dv_fctx);
6575         mov->dv_fctx = NULL;
6576     }
6577
6578     if (mov->meta_keys) {
6579         for (i = 1; i < mov->meta_keys_count; i++) {
6580             av_freep(&mov->meta_keys[i]);
6581         }
6582         av_freep(&mov->meta_keys);
6583     }
6584
6585     av_freep(&mov->trex_data);
6586     av_freep(&mov->bitrates);
6587
6588     for (i = 0; i < mov->frag_index.nb_items; i++) {
6589         av_freep(&mov->frag_index.item[i].stream_info);
6590     }
6591     av_freep(&mov->frag_index.item);
6592
6593     av_freep(&mov->aes_decrypt);
6594     av_freep(&mov->chapter_tracks);
6595
6596     return 0;
6597 }
6598
6599 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6600 {
6601     int i;
6602
6603     for (i = 0; i < s->nb_streams; i++) {
6604         AVStream *st = s->streams[i];
6605         MOVStreamContext *sc = st->priv_data;
6606
6607         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6608             sc->timecode_track == tmcd_id)
6609             return 1;
6610     }
6611     return 0;
6612 }
6613
6614 /* look for a tmcd track not referenced by any video track, and export it globally */
6615 static void export_orphan_timecode(AVFormatContext *s)
6616 {
6617     int i;
6618
6619     for (i = 0; i < s->nb_streams; i++) {
6620         AVStream *st = s->streams[i];
6621
6622         if (st->codecpar->codec_tag  == MKTAG('t','m','c','d') &&
6623             !tmcd_is_referenced(s, i + 1)) {
6624             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6625             if (tcr) {
6626                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6627                 break;
6628             }
6629         }
6630     }
6631 }
6632
6633 static int read_tfra(MOVContext *mov, AVIOContext *f)
6634 {
6635     int version, fieldlength, i, j;
6636     int64_t pos = avio_tell(f);
6637     uint32_t size = avio_rb32(f);
6638     unsigned track_id, item_count;
6639
6640     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6641         return 1;
6642     }
6643     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6644
6645     version = avio_r8(f);
6646     avio_rb24(f);
6647     track_id = avio_rb32(f);
6648     fieldlength = avio_rb32(f);
6649     item_count = avio_rb32(f);
6650     for (i = 0; i < item_count; i++) {
6651         int64_t time, offset;
6652         int index;
6653         MOVFragmentStreamInfo * frag_stream_info;
6654
6655         if (avio_feof(f)) {
6656             return AVERROR_INVALIDDATA;
6657         }
6658
6659         if (version == 1) {
6660             time   = avio_rb64(f);
6661             offset = avio_rb64(f);
6662         } else {
6663             time   = avio_rb32(f);
6664             offset = avio_rb32(f);
6665         }
6666
6667         // The first sample of each stream in a fragment is always a random
6668         // access sample.  So it's entry in the tfra can be used as the
6669         // initial PTS of the fragment.
6670         index = update_frag_index(mov, offset);
6671         frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
6672         if (frag_stream_info &&
6673             frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
6674             frag_stream_info->first_tfra_pts = time;
6675
6676         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6677             avio_r8(f);
6678         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6679             avio_r8(f);
6680         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6681             avio_r8(f);
6682     }
6683
6684     avio_seek(f, pos + size, SEEK_SET);
6685     return 0;
6686 }
6687
6688 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6689 {
6690     int64_t stream_size = avio_size(f);
6691     int64_t original_pos = avio_tell(f);
6692     int64_t seek_ret;
6693     int32_t mfra_size;
6694     int ret = -1;
6695     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6696         ret = seek_ret;
6697         goto fail;
6698     }
6699     mfra_size = avio_rb32(f);
6700     if (mfra_size < 0 || mfra_size > stream_size) {
6701         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6702         goto fail;
6703     }
6704     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6705         ret = seek_ret;
6706         goto fail;
6707     }
6708     if (avio_rb32(f) != mfra_size) {
6709         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6710         goto fail;
6711     }
6712     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6713         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6714         goto fail;
6715     }
6716     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6717     do {
6718         ret = read_tfra(c, f);
6719         if (ret < 0)
6720             goto fail;
6721     } while (!ret);
6722     ret = 0;
6723 fail:
6724     seek_ret = avio_seek(f, original_pos, SEEK_SET);
6725     if (seek_ret < 0) {
6726         av_log(c->fc, AV_LOG_ERROR,
6727                "failed to seek back after looking for mfra\n");
6728         ret = seek_ret;
6729     }
6730     return ret;
6731 }
6732
6733 static int mov_read_header(AVFormatContext *s)
6734 {
6735     MOVContext *mov = s->priv_data;
6736     AVIOContext *pb = s->pb;
6737     int j, err;
6738     MOVAtom atom = { AV_RL32("root") };
6739     int i;
6740
6741     if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6742         av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6743             mov->decryption_key_len, AES_CTR_KEY_SIZE);
6744         return AVERROR(EINVAL);
6745     }
6746
6747     mov->fc = s;
6748     mov->trak_index = -1;
6749     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6750     if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6751         atom.size = avio_size(pb);
6752     else
6753         atom.size = INT64_MAX;
6754
6755     /* check MOV header */
6756     do {
6757         if (mov->moov_retry)
6758             avio_seek(pb, 0, SEEK_SET);
6759         if ((err = mov_read_default(mov, pb, atom)) < 0) {
6760             av_log(s, AV_LOG_ERROR, "error reading header\n");
6761             mov_read_close(s);
6762             return err;
6763         }
6764     } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6765     if (!mov->found_moov) {
6766         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6767         mov_read_close(s);
6768         return AVERROR_INVALIDDATA;
6769     }
6770     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6771
6772     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6773         if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6774             mov_read_chapters(s);
6775         for (i = 0; i < s->nb_streams; i++)
6776             if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6777                 mov_read_timecode_track(s, s->streams[i]);
6778             } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6779                 mov_read_rtmd_track(s, s->streams[i]);
6780             }
6781     }
6782
6783     /* copy timecode metadata from tmcd tracks to the related video streams */
6784     for (i = 0; i < s->nb_streams; i++) {
6785         AVStream *st = s->streams[i];
6786         MOVStreamContext *sc = st->priv_data;
6787         if (sc->timecode_track > 0) {
6788             AVDictionaryEntry *tcr;
6789             int tmcd_st_id = -1;
6790
6791             for (j = 0; j < s->nb_streams; j++)
6792                 if (s->streams[j]->id == sc->timecode_track)
6793                     tmcd_st_id = j;
6794
6795             if (tmcd_st_id < 0 || tmcd_st_id == i)
6796                 continue;
6797             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6798             if (tcr)
6799                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6800         }
6801     }
6802     export_orphan_timecode(s);
6803
6804     for (i = 0; i < s->nb_streams; i++) {
6805         AVStream *st = s->streams[i];
6806         MOVStreamContext *sc = st->priv_data;
6807         fix_timescale(mov, sc);
6808         if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6809             st->skip_samples = sc->start_pad;
6810         }
6811         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6812             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6813                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6814         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6815             if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6816                 st->codecpar->width  = sc->width;
6817                 st->codecpar->height = sc->height;
6818             }
6819             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6820                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6821                     return err;
6822             }
6823         }
6824         if (mov->handbrake_version &&
6825             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
6826             st->codecpar->codec_id == AV_CODEC_ID_MP3
6827         ) {
6828             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6829             st->need_parsing = AVSTREAM_PARSE_FULL;
6830         }
6831     }
6832
6833     if (mov->trex_data) {
6834         for (i = 0; i < s->nb_streams; i++) {
6835             AVStream *st = s->streams[i];
6836             MOVStreamContext *sc = st->priv_data;
6837             if (st->duration > 0) {
6838                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6839                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6840                            sc->data_size, sc->time_scale);
6841                     mov_read_close(s);
6842                     return AVERROR_INVALIDDATA;
6843                 }
6844                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6845             }
6846         }
6847     }
6848
6849     if (mov->use_mfra_for > 0) {
6850         for (i = 0; i < s->nb_streams; i++) {
6851             AVStream *st = s->streams[i];
6852             MOVStreamContext *sc = st->priv_data;
6853             if (sc->duration_for_fps > 0) {
6854                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6855                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6856                            sc->data_size, sc->time_scale);
6857                     mov_read_close(s);
6858                     return AVERROR_INVALIDDATA;
6859                 }
6860                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6861                     sc->duration_for_fps;
6862             }
6863         }
6864     }
6865
6866     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6867         if (mov->bitrates[i]) {
6868             s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6869         }
6870     }
6871
6872     ff_rfps_calculate(s);
6873
6874     for (i = 0; i < s->nb_streams; i++) {
6875         AVStream *st = s->streams[i];
6876         MOVStreamContext *sc = st->priv_data;
6877
6878         switch (st->codecpar->codec_type) {
6879         case AVMEDIA_TYPE_AUDIO:
6880             err = ff_replaygain_export(st, s->metadata);
6881             if (err < 0) {
6882                 mov_read_close(s);
6883                 return err;
6884             }
6885             break;
6886         case AVMEDIA_TYPE_VIDEO:
6887             if (sc->display_matrix) {
6888                 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6889                                               sizeof(int32_t) * 9);
6890                 if (err < 0)
6891                     return err;
6892
6893                 sc->display_matrix = NULL;
6894             }
6895             if (sc->stereo3d) {
6896                 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6897                                               (uint8_t *)sc->stereo3d,
6898                                               sizeof(*sc->stereo3d));
6899                 if (err < 0)
6900                     return err;
6901
6902                 sc->stereo3d = NULL;
6903             }
6904             if (sc->spherical) {
6905                 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6906                                               (uint8_t *)sc->spherical,
6907                                               sc->spherical_size);
6908                 if (err < 0)
6909                     return err;
6910
6911                 sc->spherical = NULL;
6912             }
6913             if (sc->mastering) {
6914                 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6915                                               (uint8_t *)sc->mastering,
6916                                               sizeof(*sc->mastering));
6917                 if (err < 0)
6918                     return err;
6919
6920                 sc->mastering = NULL;
6921             }
6922             if (sc->coll) {
6923                 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6924                                               (uint8_t *)sc->coll,
6925                                               sc->coll_size);
6926                 if (err < 0)
6927                     return err;
6928
6929                 sc->coll = NULL;
6930             }
6931             break;
6932         }
6933     }
6934     ff_configure_buffers_for_index(s, AV_TIME_BASE);
6935
6936     for (i = 0; i < mov->frag_index.nb_items; i++)
6937         if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
6938             mov->frag_index.item[i].headers_read = 1;
6939
6940     return 0;
6941 }
6942
6943 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6944 {
6945     AVIndexEntry *sample = NULL;
6946     int64_t best_dts = INT64_MAX;
6947     int i;
6948     for (i = 0; i < s->nb_streams; i++) {
6949         AVStream *avst = s->streams[i];
6950         MOVStreamContext *msc = avst->priv_data;
6951         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6952             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6953             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6954             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6955             if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6956                 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6957                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6958                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6959                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6960                 sample = current_sample;
6961                 best_dts = dts;
6962                 *st = avst;
6963             }
6964         }
6965     }
6966     return sample;
6967 }
6968
6969 static int should_retry(AVIOContext *pb, int error_code) {
6970     if (error_code == AVERROR_EOF || avio_feof(pb))
6971         return 0;
6972
6973     return 1;
6974 }
6975
6976 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
6977 {
6978     int ret;
6979     MOVContext *mov = s->priv_data;
6980
6981     if (index >= 0 && index < mov->frag_index.nb_items)
6982         target = mov->frag_index.item[index].moof_offset;
6983     if (avio_seek(s->pb, target, SEEK_SET) != target) {
6984         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6985         return AVERROR_INVALIDDATA;
6986     }
6987
6988     mov->next_root_atom = 0;
6989     if (index < 0 || index >= mov->frag_index.nb_items)
6990         index = search_frag_moof_offset(&mov->frag_index, target);
6991     if (index < mov->frag_index.nb_items) {
6992         if (index + 1 < mov->frag_index.nb_items)
6993             mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6994         if (mov->frag_index.item[index].headers_read)
6995             return 0;
6996         mov->frag_index.item[index].headers_read = 1;
6997     }
6998
6999     mov->found_mdat = 0;
7000
7001     ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
7002     if (ret < 0)
7003         return ret;
7004     if (avio_feof(s->pb))
7005         return AVERROR_EOF;
7006     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
7007
7008     return 1;
7009 }
7010
7011 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
7012 {
7013     uint8_t *side, *extradata;
7014     int extradata_size;
7015
7016     /* Save the current index. */
7017     sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
7018
7019     /* Notify the decoder that extradata changed. */
7020     extradata_size = sc->extradata_size[sc->last_stsd_index];
7021     extradata = sc->extradata[sc->last_stsd_index];
7022     if (extradata_size > 0 && extradata) {
7023         side = av_packet_new_side_data(pkt,
7024                                        AV_PKT_DATA_NEW_EXTRADATA,
7025                                        extradata_size);
7026         if (!side)
7027             return AVERROR(ENOMEM);
7028         memcpy(side, extradata, extradata_size);
7029     }
7030
7031     return 0;
7032 }
7033
7034 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
7035 {
7036     MOVContext *mov = s->priv_data;
7037     MOVStreamContext *sc;
7038     AVIndexEntry *sample;
7039     AVStream *st = NULL;
7040     int64_t current_index;
7041     int ret;
7042     mov->fc = s;
7043  retry:
7044     sample = mov_find_next_sample(s, &st);
7045     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7046         if (!mov->next_root_atom)
7047             return AVERROR_EOF;
7048         if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7049             return ret;
7050         goto retry;
7051     }
7052     sc = st->priv_data;
7053     /* must be done just before reading, to avoid infinite loop on sample */
7054     current_index = sc->current_index;
7055     mov_current_sample_inc(sc);
7056
7057     if (mov->next_root_atom) {
7058         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7059         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7060     }
7061
7062     if (st->discard != AVDISCARD_ALL) {
7063         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7064         if (ret64 != sample->pos) {
7065             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7066                    sc->ffindex, sample->pos);
7067             if (should_retry(sc->pb, ret64)) {
7068                 mov_current_sample_dec(sc);
7069             }
7070             return AVERROR_INVALIDDATA;
7071         }
7072
7073         if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7074             av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7075             goto retry;
7076         }
7077
7078         ret = av_get_packet(sc->pb, pkt, sample->size);
7079         if (ret < 0) {
7080             if (should_retry(sc->pb, ret)) {
7081                 mov_current_sample_dec(sc);
7082             }
7083             return ret;
7084         }
7085         if (sc->has_palette) {
7086             uint8_t *pal;
7087
7088             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
7089             if (!pal) {
7090                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7091             } else {
7092                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
7093                 sc->has_palette = 0;
7094             }
7095         }
7096 #if CONFIG_DV_DEMUXER
7097         if (mov->dv_demux && sc->dv_audio_container) {
7098             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7099             av_freep(&pkt->data);
7100             pkt->size = 0;
7101             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7102             if (ret < 0)
7103                 return ret;
7104         }
7105 #endif
7106         if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7107             if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7108                 st->need_parsing = AVSTREAM_PARSE_FULL;
7109         }
7110     }
7111
7112     pkt->stream_index = sc->ffindex;
7113     pkt->dts = sample->timestamp;
7114     if (sample->flags & AVINDEX_DISCARD_FRAME) {
7115         pkt->flags |= AV_PKT_FLAG_DISCARD;
7116     }
7117     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7118         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7119         /* update ctts context */
7120         sc->ctts_sample++;
7121         if (sc->ctts_index < sc->ctts_count &&
7122             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7123             sc->ctts_index++;
7124             sc->ctts_sample = 0;
7125         }
7126     } else {
7127         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7128             st->index_entries[sc->current_sample].timestamp : st->duration;
7129         pkt->duration = next_dts - pkt->dts;
7130         pkt->pts = pkt->dts;
7131     }
7132     if (st->discard == AVDISCARD_ALL)
7133         goto retry;
7134     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7135     pkt->pos = sample->pos;
7136
7137     /* Multiple stsd handling. */
7138     if (sc->stsc_data) {
7139         /* Keep track of the stsc index for the given sample, then check
7140         * if the stsd index is different from the last used one. */
7141         sc->stsc_sample++;
7142         if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7143             mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7144             sc->stsc_index++;
7145             sc->stsc_sample = 0;
7146         /* Do not check indexes after a switch. */
7147         } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7148                    sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7149                    sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7150             ret = mov_change_extradata(sc, pkt);
7151             if (ret < 0)
7152                 return ret;
7153         }
7154     }
7155
7156     if (mov->aax_mode)
7157         aax_filter(pkt->data, pkt->size, mov);
7158
7159     if (sc->cenc.aes_ctr) {
7160         ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
7161         if (ret) {
7162             return ret;
7163         }
7164     }
7165
7166     return 0;
7167 }
7168
7169 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7170 {
7171     MOVContext *mov = s->priv_data;
7172     int index;
7173
7174     if (!mov->frag_index.complete)
7175         return 0;
7176
7177     index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7178     if (index < 0)
7179         index = 0;
7180     if (!mov->frag_index.item[index].headers_read)
7181         return mov_switch_root(s, -1, index);
7182     if (index + 1 < mov->frag_index.nb_items)
7183         mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7184
7185     return 0;
7186 }
7187
7188 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7189 {
7190     MOVStreamContext *sc = st->priv_data;
7191     int sample, time_sample, ret;
7192     unsigned int i;
7193
7194     // Here we consider timestamp to be PTS, hence try to offset it so that we
7195     // can search over the DTS timeline.
7196     timestamp -= (sc->min_corrected_pts + sc->dts_shift);
7197
7198     ret = mov_seek_fragment(s, st, timestamp);
7199     if (ret < 0)
7200         return ret;
7201
7202     sample = av_index_search_timestamp(st, timestamp, flags);
7203     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7204     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7205         sample = 0;
7206     if (sample < 0) /* not sure what to do */
7207         return AVERROR_INVALIDDATA;
7208     mov_current_sample_set(sc, sample);
7209     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7210     /* adjust ctts index */
7211     if (sc->ctts_data) {
7212         time_sample = 0;
7213         for (i = 0; i < sc->ctts_count; i++) {
7214             int next = time_sample + sc->ctts_data[i].count;
7215             if (next > sc->current_sample) {
7216                 sc->ctts_index = i;
7217                 sc->ctts_sample = sc->current_sample - time_sample;
7218                 break;
7219             }
7220             time_sample = next;
7221         }
7222     }
7223
7224     /* adjust stsd index */
7225     time_sample = 0;
7226     for (i = 0; i < sc->stsc_count; i++) {
7227         int64_t next = time_sample + mov_get_stsc_samples(sc, i);
7228         if (next > sc->current_sample) {
7229             sc->stsc_index = i;
7230             sc->stsc_sample = sc->current_sample - time_sample;
7231             break;
7232         }
7233         av_assert0(next == (int)next);
7234         time_sample = next;
7235     }
7236
7237     return sample;
7238 }
7239
7240 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7241 {
7242     MOVContext *mc = s->priv_data;
7243     AVStream *st;
7244     int sample;
7245     int i;
7246
7247     if (stream_index >= s->nb_streams)
7248         return AVERROR_INVALIDDATA;
7249
7250     st = s->streams[stream_index];
7251     sample = mov_seek_stream(s, st, sample_time, flags);
7252     if (sample < 0)
7253         return sample;
7254
7255     if (mc->seek_individually) {
7256         /* adjust seek timestamp to found sample timestamp */
7257         int64_t seek_timestamp = st->index_entries[sample].timestamp;
7258
7259         for (i = 0; i < s->nb_streams; i++) {
7260             int64_t timestamp;
7261             MOVStreamContext *sc = s->streams[i]->priv_data;
7262             st = s->streams[i];
7263             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7264
7265             if (stream_index == i)
7266                 continue;
7267
7268             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7269             mov_seek_stream(s, st, timestamp, flags);
7270         }
7271     } else {
7272         for (i = 0; i < s->nb_streams; i++) {
7273             MOVStreamContext *sc;
7274             st = s->streams[i];
7275             sc = st->priv_data;
7276             mov_current_sample_set(sc, 0);
7277         }
7278         while (1) {
7279             MOVStreamContext *sc;
7280             AVIndexEntry *entry = mov_find_next_sample(s, &st);
7281             if (!entry)
7282                 return AVERROR_INVALIDDATA;
7283             sc = st->priv_data;
7284             if (sc->ffindex == stream_index && sc->current_sample == sample)
7285                 break;
7286             mov_current_sample_inc(sc);
7287         }
7288     }
7289     return 0;
7290 }
7291
7292 #define OFFSET(x) offsetof(MOVContext, x)
7293 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7294 static const AVOption mov_options[] = {
7295     {"use_absolute_path",
7296         "allow using absolute path when opening alias, this is a possible security issue",
7297         OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7298         0, 1, FLAGS},
7299     {"seek_streams_individually",
7300         "Seek each stream individually to the to the closest point",
7301         OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7302         0, 1, FLAGS},
7303     {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7304         0, 1, FLAGS},
7305     {"advanced_editlist",
7306         "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7307         OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7308         0, 1, FLAGS},
7309     {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7310         0, 1, FLAGS},
7311     {"use_mfra_for",
7312         "use mfra for fragment timestamps",
7313         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7314         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7315         "use_mfra_for"},
7316     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7317         FLAGS, "use_mfra_for" },
7318     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7319         FLAGS, "use_mfra_for" },
7320     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7321         FLAGS, "use_mfra_for" },
7322     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7323         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7324     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7325         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7326     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7327         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7328     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7329         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7330         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7331         .flags = AV_OPT_FLAG_DECODING_PARAM },
7332     { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7333     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7334         {.i64 = 0}, 0, 1, FLAGS },
7335
7336     { NULL },
7337 };
7338
7339 static const AVClass mov_class = {
7340     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7341     .item_name  = av_default_item_name,
7342     .option     = mov_options,
7343     .version    = LIBAVUTIL_VERSION_INT,
7344 };
7345
7346 AVInputFormat ff_mov_demuxer = {
7347     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
7348     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7349     .priv_class     = &mov_class,
7350     .priv_data_size = sizeof(MOVContext),
7351     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
7352     .read_probe     = mov_probe,
7353     .read_header    = mov_read_header,
7354     .read_packet    = mov_read_packet,
7355     .read_close     = mov_read_close,
7356     .read_seek      = mov_read_seek,
7357     .flags          = AVFMT_NO_BYTE_SEEK,
7358 };