]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
Merge commit 'aeaa108bafa11db290f1ada0e22dbfbd655cf2ba'
[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
2634     if (pb->eof_reached) {
2635         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSC atom\n");
2636         return AVERROR_EOF;
2637     }
2638
2639     return 0;
2640 }
2641
2642 static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
2643 {
2644     return index < count - 1;
2645 }
2646
2647 /* Compute the samples value for the stsc entry at the given index. */
2648 static inline int64_t mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
2649 {
2650     int chunk_count;
2651
2652     if (mov_stsc_index_valid(index, sc->stsc_count))
2653         chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
2654     else
2655         chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
2656
2657     return sc->stsc_data[index].count * (int64_t)chunk_count;
2658 }
2659
2660 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2661 {
2662     AVStream *st;
2663     MOVStreamContext *sc;
2664     unsigned i, entries;
2665
2666     if (c->fc->nb_streams < 1)
2667         return 0;
2668     st = c->fc->streams[c->fc->nb_streams-1];
2669     sc = st->priv_data;
2670
2671     avio_rb32(pb); // version + flags
2672
2673     entries = avio_rb32(pb);
2674     if (sc->stps_data)
2675         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2676     av_free(sc->stps_data);
2677     sc->stps_count = 0;
2678     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2679     if (!sc->stps_data)
2680         return AVERROR(ENOMEM);
2681
2682     for (i = 0; i < entries && !pb->eof_reached; i++) {
2683         sc->stps_data[i] = avio_rb32(pb);
2684     }
2685
2686     sc->stps_count = i;
2687
2688     if (pb->eof_reached) {
2689         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STPS atom\n");
2690         return AVERROR_EOF;
2691     }
2692
2693     return 0;
2694 }
2695
2696 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2697 {
2698     AVStream *st;
2699     MOVStreamContext *sc;
2700     unsigned int i, entries;
2701
2702     if (c->fc->nb_streams < 1)
2703         return 0;
2704     st = c->fc->streams[c->fc->nb_streams-1];
2705     sc = st->priv_data;
2706
2707     avio_r8(pb); /* version */
2708     avio_rb24(pb); /* flags */
2709
2710     entries = avio_rb32(pb);
2711
2712     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2713
2714     if (!entries)
2715     {
2716         sc->keyframe_absent = 1;
2717         if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2718             st->need_parsing = AVSTREAM_PARSE_HEADERS;
2719         return 0;
2720     }
2721     if (sc->keyframes)
2722         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2723     if (entries >= UINT_MAX / sizeof(int))
2724         return AVERROR_INVALIDDATA;
2725     av_freep(&sc->keyframes);
2726     sc->keyframe_count = 0;
2727     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2728     if (!sc->keyframes)
2729         return AVERROR(ENOMEM);
2730
2731     for (i = 0; i < entries && !pb->eof_reached; i++) {
2732         sc->keyframes[i] = avio_rb32(pb);
2733     }
2734
2735     sc->keyframe_count = i;
2736
2737     if (pb->eof_reached) {
2738         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSS atom\n");
2739         return AVERROR_EOF;
2740     }
2741
2742     return 0;
2743 }
2744
2745 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2746 {
2747     AVStream *st;
2748     MOVStreamContext *sc;
2749     unsigned int i, entries, sample_size, field_size, num_bytes;
2750     GetBitContext gb;
2751     unsigned char* buf;
2752     int ret;
2753
2754     if (c->fc->nb_streams < 1)
2755         return 0;
2756     st = c->fc->streams[c->fc->nb_streams-1];
2757     sc = st->priv_data;
2758
2759     avio_r8(pb); /* version */
2760     avio_rb24(pb); /* flags */
2761
2762     if (atom.type == MKTAG('s','t','s','z')) {
2763         sample_size = avio_rb32(pb);
2764         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2765             sc->sample_size = sample_size;
2766         sc->stsz_sample_size = sample_size;
2767         field_size = 32;
2768     } else {
2769         sample_size = 0;
2770         avio_rb24(pb); /* reserved */
2771         field_size = avio_r8(pb);
2772     }
2773     entries = avio_rb32(pb);
2774
2775     av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2776
2777     sc->sample_count = entries;
2778     if (sample_size)
2779         return 0;
2780
2781     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2782         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2783         return AVERROR_INVALIDDATA;
2784     }
2785
2786     if (!entries)
2787         return 0;
2788     if (entries >= (UINT_MAX - 4) / field_size)
2789         return AVERROR_INVALIDDATA;
2790     if (sc->sample_sizes)
2791         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2792     av_free(sc->sample_sizes);
2793     sc->sample_count = 0;
2794     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2795     if (!sc->sample_sizes)
2796         return AVERROR(ENOMEM);
2797
2798     num_bytes = (entries*field_size+4)>>3;
2799
2800     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2801     if (!buf) {
2802         av_freep(&sc->sample_sizes);
2803         return AVERROR(ENOMEM);
2804     }
2805
2806     ret = ffio_read_size(pb, buf, num_bytes);
2807     if (ret < 0) {
2808         av_freep(&sc->sample_sizes);
2809         av_free(buf);
2810         return ret;
2811     }
2812
2813     init_get_bits(&gb, buf, 8*num_bytes);
2814
2815     for (i = 0; i < entries && !pb->eof_reached; i++) {
2816         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2817         sc->data_size += sc->sample_sizes[i];
2818     }
2819
2820     sc->sample_count = i;
2821
2822     av_free(buf);
2823
2824     if (pb->eof_reached) {
2825         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STSZ atom\n");
2826         return AVERROR_EOF;
2827     }
2828
2829     return 0;
2830 }
2831
2832 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2833 {
2834     AVStream *st;
2835     MOVStreamContext *sc;
2836     unsigned int i, entries, alloc_size = 0;
2837     int64_t duration=0;
2838     int64_t total_sample_count=0;
2839
2840     if (c->fc->nb_streams < 1)
2841         return 0;
2842     st = c->fc->streams[c->fc->nb_streams-1];
2843     sc = st->priv_data;
2844
2845     avio_r8(pb); /* version */
2846     avio_rb24(pb); /* flags */
2847     entries = avio_rb32(pb);
2848
2849     av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2850             c->fc->nb_streams-1, entries);
2851
2852     if (sc->stts_data)
2853         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2854     av_freep(&sc->stts_data);
2855     sc->stts_count = 0;
2856     if (entries >= INT_MAX / sizeof(*sc->stts_data))
2857         return AVERROR(ENOMEM);
2858
2859     for (i = 0; i < entries && !pb->eof_reached; i++) {
2860         int sample_duration;
2861         unsigned int sample_count;
2862         unsigned int min_entries = FFMIN(FFMAX(i + 1, 1024 * 1024), entries);
2863         MOVStts *stts_data = av_fast_realloc(sc->stts_data, &alloc_size,
2864                                              min_entries * sizeof(*sc->stts_data));
2865         if (!stts_data) {
2866             av_freep(&sc->stts_data);
2867             sc->stts_count = 0;
2868             return AVERROR(ENOMEM);
2869         }
2870         sc->stts_count = min_entries;
2871         sc->stts_data = stts_data;
2872
2873         sample_count=avio_rb32(pb);
2874         sample_duration = avio_rb32(pb);
2875
2876         sc->stts_data[i].count= sample_count;
2877         sc->stts_data[i].duration= sample_duration;
2878
2879         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2880                 sample_count, sample_duration);
2881
2882         if (   i+1 == entries
2883             && i
2884             && sample_count == 1
2885             && total_sample_count > 100
2886             && sample_duration/10 > duration / total_sample_count)
2887             sample_duration = duration / total_sample_count;
2888         duration+=(int64_t)sample_duration*(uint64_t)sample_count;
2889         total_sample_count+=sample_count;
2890     }
2891
2892     sc->stts_count = i;
2893
2894     if (duration > 0 &&
2895         duration <= INT64_MAX - sc->duration_for_fps &&
2896         total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
2897     ) {
2898         sc->duration_for_fps  += duration;
2899         sc->nb_frames_for_fps += total_sample_count;
2900     }
2901
2902     if (pb->eof_reached) {
2903         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted STTS atom\n");
2904         return AVERROR_EOF;
2905     }
2906
2907     st->nb_frames= total_sample_count;
2908     if (duration)
2909         st->duration= duration;
2910     sc->track_end = duration;
2911     return 0;
2912 }
2913
2914 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2915 {
2916     if (duration < 0) {
2917         if (duration == INT_MIN) {
2918             av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2919             duration++;
2920         }
2921         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2922     }
2923 }
2924
2925 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2926 {
2927     AVStream *st;
2928     MOVStreamContext *sc;
2929     unsigned int i, entries, ctts_count = 0;
2930
2931     if (c->fc->nb_streams < 1)
2932         return 0;
2933     st = c->fc->streams[c->fc->nb_streams-1];
2934     sc = st->priv_data;
2935
2936     avio_r8(pb); /* version */
2937     avio_rb24(pb); /* flags */
2938     entries = avio_rb32(pb);
2939
2940     av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2941
2942     if (!entries)
2943         return 0;
2944     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2945         return AVERROR_INVALIDDATA;
2946     av_freep(&sc->ctts_data);
2947     sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
2948     if (!sc->ctts_data)
2949         return AVERROR(ENOMEM);
2950
2951     for (i = 0; i < entries && !pb->eof_reached; i++) {
2952         int count    =avio_rb32(pb);
2953         int duration =avio_rb32(pb);
2954
2955         if (count <= 0) {
2956             av_log(c->fc, AV_LOG_TRACE,
2957                    "ignoring CTTS entry with count=%d duration=%d\n",
2958                    count, duration);
2959             continue;
2960         }
2961
2962         add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size,
2963                        count, duration);
2964
2965         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2966                 count, duration);
2967
2968         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2969             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2970             av_freep(&sc->ctts_data);
2971             sc->ctts_count = 0;
2972             return 0;
2973         }
2974
2975         if (i+2<entries)
2976             mov_update_dts_shift(sc, duration);
2977     }
2978
2979     sc->ctts_count = ctts_count;
2980
2981     if (pb->eof_reached) {
2982         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted CTTS atom\n");
2983         return AVERROR_EOF;
2984     }
2985
2986     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2987
2988     return 0;
2989 }
2990
2991 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2992 {
2993     AVStream *st;
2994     MOVStreamContext *sc;
2995     unsigned int i, entries;
2996     uint8_t version;
2997     uint32_t grouping_type;
2998
2999     if (c->fc->nb_streams < 1)
3000         return 0;
3001     st = c->fc->streams[c->fc->nb_streams-1];
3002     sc = st->priv_data;
3003
3004     version = avio_r8(pb); /* version */
3005     avio_rb24(pb); /* flags */
3006     grouping_type = avio_rl32(pb);
3007     if (grouping_type != MKTAG( 'r','a','p',' '))
3008         return 0; /* only support 'rap ' grouping */
3009     if (version == 1)
3010         avio_rb32(pb); /* grouping_type_parameter */
3011
3012     entries = avio_rb32(pb);
3013     if (!entries)
3014         return 0;
3015     if (sc->rap_group)
3016         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
3017     av_free(sc->rap_group);
3018     sc->rap_group_count = 0;
3019     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
3020     if (!sc->rap_group)
3021         return AVERROR(ENOMEM);
3022
3023     for (i = 0; i < entries && !pb->eof_reached; i++) {
3024         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
3025         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
3026     }
3027
3028     sc->rap_group_count = i;
3029
3030     if (pb->eof_reached) {
3031         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted SBGP atom\n");
3032         return AVERROR_EOF;
3033     }
3034
3035     return 0;
3036 }
3037
3038 /**
3039  * Get ith edit list entry (media time, duration).
3040  */
3041 static int get_edit_list_entry(MOVContext *mov,
3042                                const MOVStreamContext *msc,
3043                                unsigned int edit_list_index,
3044                                int64_t *edit_list_media_time,
3045                                int64_t *edit_list_duration,
3046                                int64_t global_timescale)
3047 {
3048     if (edit_list_index == msc->elst_count) {
3049         return 0;
3050     }
3051     *edit_list_media_time = msc->elst_data[edit_list_index].time;
3052     *edit_list_duration = msc->elst_data[edit_list_index].duration;
3053
3054     /* duration is in global timescale units;convert to msc timescale */
3055     if (global_timescale == 0) {
3056       avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
3057       return 0;
3058     }
3059     *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
3060                                      global_timescale);
3061     return 1;
3062 }
3063
3064 /**
3065  * Find the closest previous frame to the timestamp_pts, in e_old index
3066  * entries. Searching for just any frame / just key frames can be controlled by
3067  * last argument 'flag'.
3068  * Note that if ctts_data is not NULL, we will always search for a key frame
3069  * irrespective of the value of 'flag'. If we don't find any keyframe, we will
3070  * return the first frame of the video.
3071  *
3072  * Here the timestamp_pts is considered to be a presentation timestamp and
3073  * the timestamp of index entries are considered to be decoding timestamps.
3074  *
3075  * Returns 0 if successful in finding a frame, else returns -1.
3076  * Places the found index corresponding output arg.
3077  *
3078  * If ctts_old is not NULL, then refines the searched entry by searching
3079  * backwards from the found timestamp, to find the frame with correct PTS.
3080  *
3081  * Places the found ctts_index and ctts_sample in corresponding output args.
3082  */
3083 static int find_prev_closest_index(AVStream *st,
3084                                    AVIndexEntry *e_old,
3085                                    int nb_old,
3086                                    MOVStts* ctts_data,
3087                                    int64_t ctts_count,
3088                                    int64_t timestamp_pts,
3089                                    int flag,
3090                                    int64_t* index,
3091                                    int64_t* ctts_index,
3092                                    int64_t* ctts_sample)
3093 {
3094     MOVStreamContext *msc = st->priv_data;
3095     AVIndexEntry *e_keep = st->index_entries;
3096     int nb_keep = st->nb_index_entries;
3097     int64_t i = 0;
3098     int64_t index_ctts_count;
3099
3100     av_assert0(index);
3101
3102     // If dts_shift > 0, then all the index timestamps will have to be offset by
3103     // at least dts_shift amount to obtain PTS.
3104     // Hence we decrement the searched timestamp_pts by dts_shift to find the closest index element.
3105     if (msc->dts_shift > 0) {
3106         timestamp_pts -= msc->dts_shift;
3107     }
3108
3109     st->index_entries = e_old;
3110     st->nb_index_entries = nb_old;
3111     *index = av_index_search_timestamp(st, timestamp_pts, flag | AVSEEK_FLAG_BACKWARD);
3112
3113     // Keep going backwards in the index entries until the timestamp is the same.
3114     if (*index >= 0) {
3115         for (i = *index; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
3116              i--) {
3117             if ((flag & AVSEEK_FLAG_ANY) ||
3118                 (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
3119                 *index = i - 1;
3120             }
3121         }
3122     }
3123
3124     // If we have CTTS then refine the search, by searching backwards over PTS
3125     // computed by adding corresponding CTTS durations to index timestamps.
3126     if (ctts_data && *index >= 0) {
3127         av_assert0(ctts_index);
3128         av_assert0(ctts_sample);
3129         // Find out the ctts_index for the found frame.
3130         *ctts_index = 0;
3131         *ctts_sample = 0;
3132         for (index_ctts_count = 0; index_ctts_count < *index; index_ctts_count++) {
3133             if (*ctts_index < ctts_count) {
3134                 (*ctts_sample)++;
3135                 if (ctts_data[*ctts_index].count == *ctts_sample) {
3136                     (*ctts_index)++;
3137                     *ctts_sample = 0;
3138                 }
3139             }
3140         }
3141
3142         while (*index >= 0 && (*ctts_index) >= 0 && (*ctts_index) < ctts_count) {
3143             // Find a "key frame" with PTS <= timestamp_pts (So that we can decode B-frames correctly).
3144             // No need to add dts_shift to the timestamp here becase timestamp_pts has already been
3145             // compensated by dts_shift above.
3146             if ((e_old[*index].timestamp + ctts_data[*ctts_index].duration) <= timestamp_pts &&
3147                 (e_old[*index].flags & AVINDEX_KEYFRAME)) {
3148                 break;
3149             }
3150
3151             (*index)--;
3152             if (*ctts_sample == 0) {
3153                 (*ctts_index)--;
3154                 if (*ctts_index >= 0)
3155                   *ctts_sample = ctts_data[*ctts_index].count - 1;
3156             } else {
3157                 (*ctts_sample)--;
3158             }
3159         }
3160     }
3161
3162     /* restore AVStream state*/
3163     st->index_entries = e_keep;
3164     st->nb_index_entries = nb_keep;
3165     return *index >= 0 ? 0 : -1;
3166 }
3167
3168 /**
3169  * Add index entry with the given values, to the end of st->index_entries.
3170  * Returns the new size st->index_entries if successful, else returns -1.
3171  *
3172  * This function is similar to ff_add_index_entry in libavformat/utils.c
3173  * except that here we are always unconditionally adding an index entry to
3174  * the end, instead of searching the entries list and skipping the add if
3175  * there is an existing entry with the same timestamp.
3176  * This is needed because the mov_fix_index calls this func with the same
3177  * unincremented timestamp for successive discarded frames.
3178  */
3179 static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
3180                                int size, int distance, int flags)
3181 {
3182     AVIndexEntry *entries, *ie;
3183     int64_t index = -1;
3184     const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
3185
3186     // Double the allocation each time, to lower memory fragmentation.
3187     // Another difference from ff_add_index_entry function.
3188     const size_t requested_size =
3189         min_size_needed > st->index_entries_allocated_size ?
3190         FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
3191         min_size_needed;
3192
3193     if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
3194         return -1;
3195
3196     entries = av_fast_realloc(st->index_entries,
3197                               &st->index_entries_allocated_size,
3198                               requested_size);
3199     if(!entries)
3200         return -1;
3201
3202     st->index_entries= entries;
3203
3204     index= st->nb_index_entries++;
3205     ie= &entries[index];
3206
3207     ie->pos = pos;
3208     ie->timestamp = timestamp;
3209     ie->min_distance= distance;
3210     ie->size= size;
3211     ie->flags = flags;
3212     return index;
3213 }
3214
3215 /**
3216  * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
3217  * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
3218  */
3219 static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
3220                                        int64_t* frame_duration_buffer,
3221                                        int frame_duration_buffer_size) {
3222     int i = 0;
3223     av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
3224     for (i = 0; i < frame_duration_buffer_size; i++) {
3225         end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
3226         st->index_entries[end_index - 1 - i].timestamp = end_ts;
3227     }
3228 }
3229
3230 /**
3231  * Append a new ctts entry to ctts_data.
3232  * Returns the new ctts_count if successful, else returns -1.
3233  */
3234 static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
3235                               int count, int duration)
3236 {
3237     MOVStts *ctts_buf_new;
3238     const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
3239     const size_t requested_size =
3240         min_size_needed > *allocated_size ?
3241         FFMAX(min_size_needed, 2 * (*allocated_size)) :
3242         min_size_needed;
3243
3244     if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
3245         return -1;
3246
3247     ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
3248
3249     if(!ctts_buf_new)
3250         return -1;
3251
3252     *ctts_data = ctts_buf_new;
3253
3254     ctts_buf_new[*ctts_count].count = count;
3255     ctts_buf_new[*ctts_count].duration = duration;
3256
3257     *ctts_count = (*ctts_count) + 1;
3258     return *ctts_count;
3259 }
3260
3261 #define MAX_REORDER_DELAY 16
3262 static void mov_estimate_video_delay(MOVContext *c, AVStream* st) {
3263     MOVStreamContext *msc = st->priv_data;
3264     int ind;
3265     int ctts_ind = 0;
3266     int ctts_sample = 0;
3267     int64_t pts_buf[MAX_REORDER_DELAY + 1]; // Circular buffer to sort pts.
3268     int buf_start = 0;
3269     int buf_size = 0;
3270     int j, r, num_swaps;
3271
3272     if (st->codecpar->video_delay <= 0 && msc->ctts_data &&
3273         st->codecpar->codec_id == AV_CODEC_ID_H264) {
3274         st->codecpar->video_delay = 0;
3275         for(ind = 0; ind < st->nb_index_entries && ctts_ind < msc->ctts_count; ++ind) {
3276             if (buf_size == (MAX_REORDER_DELAY + 1)) {
3277                 // If circular buffer is full, then move the first element forward.
3278                 buf_start = (buf_start + 1) % buf_size;
3279             } else {
3280                 ++buf_size;
3281             }
3282
3283             // Point j to the last elem of the buffer and insert the current pts there.
3284             j = (buf_start + buf_size - 1) % buf_size;
3285             pts_buf[j] = st->index_entries[ind].timestamp + msc->ctts_data[ctts_ind].duration;
3286
3287             // The timestamps that are already in the sorted buffer, and are greater than the
3288             // current pts, are exactly the timestamps that need to be buffered to output PTS
3289             // in correct sorted order.
3290             // Hence the video delay (which is the buffer size used to sort DTS and output PTS),
3291             // can be computed as the maximum no. of swaps any particular timestamp needs to
3292             // go through, to keep this buffer in sorted order.
3293             num_swaps = 0;
3294             while (j != buf_start) {
3295                 r = (j - 1 + buf_size) % buf_size;
3296                 if (pts_buf[j] < pts_buf[r]) {
3297                     FFSWAP(int64_t, pts_buf[j], pts_buf[r]);
3298                     ++num_swaps;
3299                 }
3300                 j = r;
3301             }
3302             st->codecpar->video_delay = FFMAX(st->codecpar->video_delay, num_swaps);
3303
3304             ctts_sample++;
3305             if (ctts_sample == msc->ctts_data[ctts_ind].count) {
3306                 ctts_ind++;
3307                 ctts_sample = 0;
3308             }
3309         }
3310         av_log(c->fc, AV_LOG_DEBUG, "Setting codecpar->delay to %d for stream st: %d\n",
3311                st->codecpar->video_delay, st->index);
3312     }
3313 }
3314
3315 static void mov_current_sample_inc(MOVStreamContext *sc)
3316 {
3317     sc->current_sample++;
3318     sc->current_index++;
3319     if (sc->index_ranges &&
3320         sc->current_index >= sc->current_index_range->end &&
3321         sc->current_index_range->end) {
3322         sc->current_index_range++;
3323         sc->current_index = sc->current_index_range->start;
3324     }
3325 }
3326
3327 static void mov_current_sample_dec(MOVStreamContext *sc)
3328 {
3329     sc->current_sample--;
3330     sc->current_index--;
3331     if (sc->index_ranges &&
3332         sc->current_index < sc->current_index_range->start &&
3333         sc->current_index_range > sc->index_ranges) {
3334         sc->current_index_range--;
3335         sc->current_index = sc->current_index_range->end - 1;
3336     }
3337 }
3338
3339 static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
3340 {
3341     int64_t range_size;
3342
3343     sc->current_sample = current_sample;
3344     sc->current_index = current_sample;
3345     if (!sc->index_ranges) {
3346         return;
3347     }
3348
3349     for (sc->current_index_range = sc->index_ranges;
3350         sc->current_index_range->end;
3351         sc->current_index_range++) {
3352         range_size = sc->current_index_range->end - sc->current_index_range->start;
3353         if (range_size > current_sample) {
3354             sc->current_index = sc->current_index_range->start + current_sample;
3355             break;
3356         }
3357         current_sample -= range_size;
3358     }
3359 }
3360
3361 /**
3362  * Fix st->index_entries, so that it contains only the entries (and the entries
3363  * which are needed to decode them) that fall in the edit list time ranges.
3364  * Also fixes the timestamps of the index entries to match the timeline
3365  * specified the edit lists.
3366  */
3367 static void mov_fix_index(MOVContext *mov, AVStream *st)
3368 {
3369     MOVStreamContext *msc = st->priv_data;
3370     AVIndexEntry *e_old = st->index_entries;
3371     int nb_old = st->nb_index_entries;
3372     const AVIndexEntry *e_old_end = e_old + nb_old;
3373     const AVIndexEntry *current = NULL;
3374     MOVStts *ctts_data_old = msc->ctts_data;
3375     int64_t ctts_index_old = 0;
3376     int64_t ctts_sample_old = 0;
3377     int64_t ctts_count_old = msc->ctts_count;
3378     int64_t edit_list_media_time = 0;
3379     int64_t edit_list_duration = 0;
3380     int64_t frame_duration = 0;
3381     int64_t edit_list_dts_counter = 0;
3382     int64_t edit_list_dts_entry_end = 0;
3383     int64_t edit_list_start_ctts_sample = 0;
3384     int64_t curr_cts;
3385     int64_t curr_ctts = 0;
3386     int64_t empty_edits_sum_duration = 0;
3387     int64_t edit_list_index = 0;
3388     int64_t index;
3389     int flags;
3390     int64_t start_dts = 0;
3391     int64_t edit_list_start_encountered = 0;
3392     int64_t search_timestamp = 0;
3393     int64_t* frame_duration_buffer = NULL;
3394     int num_discarded_begin = 0;
3395     int first_non_zero_audio_edit = -1;
3396     int packet_skip_samples = 0;
3397     MOVIndexRange *current_index_range;
3398     int i;
3399     int found_keyframe_after_edit = 0;
3400
3401     if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
3402         return;
3403     }
3404
3405     // allocate the index ranges array
3406     msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
3407     if (!msc->index_ranges) {
3408         av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
3409         return;
3410     }
3411     msc->current_index_range = msc->index_ranges;
3412     current_index_range = msc->index_ranges - 1;
3413
3414     // Clean AVStream from traces of old index
3415     st->index_entries = NULL;
3416     st->index_entries_allocated_size = 0;
3417     st->nb_index_entries = 0;
3418
3419     // Clean ctts fields of MOVStreamContext
3420     msc->ctts_data = NULL;
3421     msc->ctts_count = 0;
3422     msc->ctts_index = 0;
3423     msc->ctts_sample = 0;
3424     msc->ctts_allocated_size = 0;
3425
3426     // Reinitialize min_corrected_pts so that it can be computed again.
3427     msc->min_corrected_pts = -1;
3428
3429     // If the dts_shift is positive (in case of negative ctts values in mov),
3430     // then negate the DTS by dts_shift
3431     if (msc->dts_shift > 0) {
3432         edit_list_dts_entry_end -= msc->dts_shift;
3433         av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
3434     }
3435
3436     start_dts = edit_list_dts_entry_end;
3437
3438     while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
3439                                &edit_list_duration, mov->time_scale)) {
3440         av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
3441                st->index, edit_list_index, edit_list_media_time, edit_list_duration);
3442         edit_list_index++;
3443         edit_list_dts_counter = edit_list_dts_entry_end;
3444         edit_list_dts_entry_end += edit_list_duration;
3445         num_discarded_begin = 0;
3446         if (edit_list_media_time == -1) {
3447             empty_edits_sum_duration += edit_list_duration;
3448             continue;
3449         }
3450
3451         // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
3452         // according to the edit list below.
3453         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3454             if (first_non_zero_audio_edit < 0) {
3455                 first_non_zero_audio_edit = 1;
3456             } else {
3457                 first_non_zero_audio_edit = 0;
3458             }
3459
3460             if (first_non_zero_audio_edit > 0)
3461                 st->skip_samples = msc->start_pad = 0;
3462         }
3463
3464         // While reordering frame index according to edit list we must handle properly
3465         // the scenario when edit list entry starts from none key frame.
3466         // We find closest previous key frame and preserve it and consequent frames in index.
3467         // All frames which are outside edit list entry time boundaries will be dropped after decoding.
3468         search_timestamp = edit_list_media_time;
3469         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3470             // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
3471             // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
3472             // edit_list_media_time to cover the decoder delay.
3473             search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
3474         }
3475
3476         if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, 0,
3477                                     &index, &ctts_index_old, &ctts_sample_old) < 0) {
3478             av_log(mov->fc, AV_LOG_WARNING,
3479                    "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
3480                    st->index, edit_list_index, search_timestamp);
3481             if (find_prev_closest_index(st, e_old, nb_old, ctts_data_old, ctts_count_old, search_timestamp, AVSEEK_FLAG_ANY,
3482                                         &index, &ctts_index_old, &ctts_sample_old) < 0) {
3483                 av_log(mov->fc, AV_LOG_WARNING,
3484                        "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n",
3485                        st->index, edit_list_index, search_timestamp);
3486                 index = 0;
3487                 ctts_index_old = 0;
3488                 ctts_sample_old = 0;
3489             }
3490         }
3491         current = e_old + index;
3492         edit_list_start_ctts_sample = ctts_sample_old;
3493
3494         // Iterate over index and arrange it according to edit list
3495         edit_list_start_encountered = 0;
3496         found_keyframe_after_edit = 0;
3497         for (; current < e_old_end; current++, index++) {
3498             // check  if frame outside edit list mark it for discard
3499             frame_duration = (current + 1 <  e_old_end) ?
3500                              ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
3501
3502             flags = current->flags;
3503
3504             // frames (pts) before or after edit list
3505             curr_cts = current->timestamp + msc->dts_shift;
3506             curr_ctts = 0;
3507
3508             if (ctts_data_old && ctts_index_old < ctts_count_old) {
3509                 curr_ctts = ctts_data_old[ctts_index_old].duration;
3510                 av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
3511                        curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
3512                 curr_cts += curr_ctts;
3513                 ctts_sample_old++;
3514                 if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
3515                     if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3516                                        &msc->ctts_allocated_size,
3517                                        ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3518                                        ctts_data_old[ctts_index_old].duration) == -1) {
3519                         av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3520                                ctts_index_old,
3521                                ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
3522                                ctts_data_old[ctts_index_old].duration);
3523                         break;
3524                     }
3525                     ctts_index_old++;
3526                     ctts_sample_old = 0;
3527                     edit_list_start_ctts_sample = 0;
3528                 }
3529             }
3530
3531             if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
3532                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
3533                     curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
3534                     first_non_zero_audio_edit > 0) {
3535                     packet_skip_samples = edit_list_media_time - curr_cts;
3536                     st->skip_samples += packet_skip_samples;
3537
3538                     // Shift the index entry timestamp by packet_skip_samples to be correct.
3539                     edit_list_dts_counter -= packet_skip_samples;
3540                     if (edit_list_start_encountered == 0)  {
3541                         edit_list_start_encountered = 1;
3542                         // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3543                         // discarded packets.
3544                         if (frame_duration_buffer) {
3545                             fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3546                                                        frame_duration_buffer, num_discarded_begin);
3547                             av_freep(&frame_duration_buffer);
3548                         }
3549                     }
3550
3551                     av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
3552                 } else {
3553                     flags |= AVINDEX_DISCARD_FRAME;
3554                     av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
3555
3556                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
3557                         num_discarded_begin++;
3558                         frame_duration_buffer = av_realloc(frame_duration_buffer,
3559                                                            num_discarded_begin * sizeof(int64_t));
3560                         if (!frame_duration_buffer) {
3561                             av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
3562                             break;
3563                         }
3564                         frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
3565
3566                         // Increment skip_samples for the first non-zero audio edit list
3567                         if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
3568                             st->skip_samples += frame_duration;
3569                         }
3570                     }
3571                 }
3572             } else {
3573                 if (msc->min_corrected_pts < 0) {
3574                     msc->min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
3575                 } else {
3576                     msc->min_corrected_pts = FFMIN(msc->min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
3577                 }
3578                 if (edit_list_start_encountered == 0) {
3579                     edit_list_start_encountered = 1;
3580                     // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
3581                     // discarded packets.
3582                     if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
3583                         fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
3584                                                    frame_duration_buffer, num_discarded_begin);
3585                         av_freep(&frame_duration_buffer);
3586                     }
3587                 }
3588             }
3589
3590             if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
3591                                 current->min_distance, flags) == -1) {
3592                 av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
3593                 break;
3594             }
3595
3596             // Update the index ranges array
3597             if (current_index_range < msc->index_ranges || index != current_index_range->end) {
3598                 current_index_range++;
3599                 current_index_range->start = index;
3600             }
3601             current_index_range->end = index + 1;
3602
3603             // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
3604             if (edit_list_start_encountered > 0) {
3605                 edit_list_dts_counter = edit_list_dts_counter + frame_duration;
3606             }
3607
3608             // Break when found first key frame after edit entry completion
3609             if ((curr_cts + frame_duration >= (edit_list_duration + edit_list_media_time)) &&
3610                 ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
3611                 if (ctts_data_old) {
3612                     // If we have CTTS and this is the first keyframe after edit elist,
3613                     // wait for one more, because there might be trailing B-frames after this I-frame
3614                     // that do belong to the edit.
3615                     if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && found_keyframe_after_edit == 0) {
3616                         found_keyframe_after_edit = 1;
3617                         continue;
3618                     }
3619                     if (ctts_sample_old != 0) {
3620                         if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
3621                                            &msc->ctts_allocated_size,
3622                                            ctts_sample_old - edit_list_start_ctts_sample,
3623                                            ctts_data_old[ctts_index_old].duration) == -1) {
3624                             av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
3625                                    ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
3626                                    ctts_data_old[ctts_index_old].duration);
3627                             break;
3628                         }
3629                     }
3630                 }
3631                 break;
3632             }
3633         }
3634     }
3635     // If there are empty edits, then msc->min_corrected_pts might be positive
3636     // intentionally. So we subtract the sum duration of emtpy edits here.
3637     msc->min_corrected_pts -= empty_edits_sum_duration;
3638
3639     // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
3640     // dts by that amount to make the first pts zero.
3641     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && msc->min_corrected_pts > 0) {
3642         av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", msc->min_corrected_pts);
3643         for (i = 0; i < st->nb_index_entries; ++i) {
3644             st->index_entries[i].timestamp -= msc->min_corrected_pts;
3645         }
3646     }
3647
3648     // Update av stream length
3649     st->duration = edit_list_dts_entry_end - start_dts;
3650     msc->start_pad = st->skip_samples;
3651
3652     // Free the old index and the old CTTS structures
3653     av_free(e_old);
3654     av_free(ctts_data_old);
3655     av_freep(&frame_duration_buffer);
3656
3657     // Null terminate the index ranges array
3658     current_index_range++;
3659     current_index_range->start = 0;
3660     current_index_range->end = 0;
3661     msc->current_index = msc->index_ranges[0].start;
3662 }
3663
3664 static void mov_build_index(MOVContext *mov, AVStream *st)
3665 {
3666     MOVStreamContext *sc = st->priv_data;
3667     int64_t current_offset;
3668     int64_t current_dts = 0;
3669     unsigned int stts_index = 0;
3670     unsigned int stsc_index = 0;
3671     unsigned int stss_index = 0;
3672     unsigned int stps_index = 0;
3673     unsigned int i, j;
3674     uint64_t stream_size = 0;
3675     MOVStts *ctts_data_old = sc->ctts_data;
3676     unsigned int ctts_count_old = sc->ctts_count;
3677
3678     if (sc->elst_count) {
3679         int i, edit_start_index = 0, multiple_edits = 0;
3680         int64_t empty_duration = 0; // empty duration of the first edit list entry
3681         int64_t start_time = 0; // start time of the media
3682
3683         for (i = 0; i < sc->elst_count; i++) {
3684             const MOVElst *e = &sc->elst_data[i];
3685             if (i == 0 && e->time == -1) {
3686                 /* if empty, the first entry is the start time of the stream
3687                  * relative to the presentation itself */
3688                 empty_duration = e->duration;
3689                 edit_start_index = 1;
3690             } else if (i == edit_start_index && e->time >= 0) {
3691                 start_time = e->time;
3692             } else {
3693                 multiple_edits = 1;
3694             }
3695         }
3696
3697         if (multiple_edits && !mov->advanced_editlist)
3698             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
3699                    "Use -advanced_editlist to correctly decode otherwise "
3700                    "a/v desync might occur\n");
3701
3702         /* adjust first dts according to edit list */
3703         if ((empty_duration || start_time) && mov->time_scale > 0) {
3704             if (empty_duration)
3705                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
3706             sc->time_offset = start_time - empty_duration;
3707             sc->min_corrected_pts = start_time;
3708             if (!mov->advanced_editlist)
3709                 current_dts = -sc->time_offset;
3710         }
3711
3712         if (!multiple_edits && !mov->advanced_editlist &&
3713             st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
3714             sc->start_pad = start_time;
3715     }
3716
3717     /* only use old uncompressed audio chunk demuxing when stts specifies it */
3718     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
3719           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
3720         unsigned int current_sample = 0;
3721         unsigned int stts_sample = 0;
3722         unsigned int sample_size;
3723         unsigned int distance = 0;
3724         unsigned int rap_group_index = 0;
3725         unsigned int rap_group_sample = 0;
3726         int64_t last_dts = 0;
3727         int64_t dts_correction = 0;
3728         int rap_group_present = sc->rap_group_count && sc->rap_group;
3729         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
3730
3731         current_dts -= sc->dts_shift;
3732         last_dts     = current_dts;
3733
3734         if (!sc->sample_count || st->nb_index_entries)
3735             return;
3736         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3737             return;
3738         if (av_reallocp_array(&st->index_entries,
3739                               st->nb_index_entries + sc->sample_count,
3740                               sizeof(*st->index_entries)) < 0) {
3741             st->nb_index_entries = 0;
3742             return;
3743         }
3744         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
3745
3746         if (ctts_data_old) {
3747             // Expand ctts entries such that we have a 1-1 mapping with samples
3748             if (sc->sample_count >= UINT_MAX / sizeof(*sc->ctts_data))
3749                 return;
3750             sc->ctts_count = 0;
3751             sc->ctts_allocated_size = 0;
3752             sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size,
3753                                     sc->sample_count * sizeof(*sc->ctts_data));
3754             if (!sc->ctts_data) {
3755                 av_free(ctts_data_old);
3756                 return;
3757             }
3758
3759             memset((uint8_t*)(sc->ctts_data), 0, sc->ctts_allocated_size);
3760
3761             for (i = 0; i < ctts_count_old &&
3762                         sc->ctts_count < sc->sample_count; i++)
3763                 for (j = 0; j < ctts_data_old[i].count &&
3764                             sc->ctts_count < sc->sample_count; j++)
3765                     add_ctts_entry(&sc->ctts_data, &sc->ctts_count,
3766                                    &sc->ctts_allocated_size, 1,
3767                                    ctts_data_old[i].duration);
3768             av_free(ctts_data_old);
3769         }
3770
3771         for (i = 0; i < sc->chunk_count; i++) {
3772             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
3773             current_offset = sc->chunk_offsets[i];
3774             while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3775                 i + 1 == sc->stsc_data[stsc_index + 1].first)
3776                 stsc_index++;
3777
3778             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
3779                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
3780                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
3781                 sc->stsz_sample_size = sc->sample_size;
3782             }
3783             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
3784                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
3785                 sc->stsz_sample_size = sc->sample_size;
3786             }
3787
3788             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
3789                 int keyframe = 0;
3790                 if (current_sample >= sc->sample_count) {
3791                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
3792                     return;
3793                 }
3794
3795                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
3796                     keyframe = 1;
3797                     if (stss_index + 1 < sc->keyframe_count)
3798                         stss_index++;
3799                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
3800                     keyframe = 1;
3801                     if (stps_index + 1 < sc->stps_count)
3802                         stps_index++;
3803                 }
3804                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
3805                     if (sc->rap_group[rap_group_index].index > 0)
3806                         keyframe = 1;
3807                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
3808                         rap_group_sample = 0;
3809                         rap_group_index++;
3810                     }
3811                 }
3812                 if (sc->keyframe_absent
3813                     && !sc->stps_count
3814                     && !rap_group_present
3815                     && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
3816                      keyframe = 1;
3817                 if (keyframe)
3818                     distance = 0;
3819                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
3820                 if (sc->pseudo_stream_id == -1 ||
3821                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
3822                     AVIndexEntry *e;
3823                     if (sample_size > 0x3FFFFFFF) {
3824                         av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
3825                         return;
3826                     }
3827                     e = &st->index_entries[st->nb_index_entries++];
3828                     e->pos = current_offset;
3829                     e->timestamp = current_dts;
3830                     e->size = sample_size;
3831                     e->min_distance = distance;
3832                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
3833                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3834                             "size %u, distance %u, keyframe %d\n", st->index, current_sample,
3835                             current_offset, current_dts, sample_size, distance, keyframe);
3836                     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
3837                         ff_rfps_add_frame(mov->fc, st, current_dts);
3838                 }
3839
3840                 current_offset += sample_size;
3841                 stream_size += sample_size;
3842
3843                 /* A negative sample duration is invalid based on the spec,
3844                  * but some samples need it to correct the DTS. */
3845                 if (sc->stts_data[stts_index].duration < 0) {
3846                     av_log(mov->fc, AV_LOG_WARNING,
3847                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
3848                            sc->stts_data[stts_index].duration, stts_index,
3849                            st->index);
3850                     dts_correction += sc->stts_data[stts_index].duration - 1;
3851                     sc->stts_data[stts_index].duration = 1;
3852                 }
3853                 current_dts += sc->stts_data[stts_index].duration;
3854                 if (!dts_correction || current_dts + dts_correction > last_dts) {
3855                     current_dts += dts_correction;
3856                     dts_correction = 0;
3857                 } else {
3858                     /* Avoid creating non-monotonous DTS */
3859                     dts_correction += current_dts - last_dts - 1;
3860                     current_dts = last_dts + 1;
3861                 }
3862                 last_dts = current_dts;
3863                 distance++;
3864                 stts_sample++;
3865                 current_sample++;
3866                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
3867                     stts_sample = 0;
3868                     stts_index++;
3869                 }
3870             }
3871         }
3872         if (st->duration > 0)
3873             st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
3874     } else {
3875         unsigned chunk_samples, total = 0;
3876
3877         // compute total chunk count
3878         for (i = 0; i < sc->stsc_count; i++) {
3879             unsigned count, chunk_count;
3880
3881             chunk_samples = sc->stsc_data[i].count;
3882             if (i != sc->stsc_count - 1 &&
3883                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
3884                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
3885                 return;
3886             }
3887
3888             if (sc->samples_per_frame >= 160) { // gsm
3889                 count = chunk_samples / sc->samples_per_frame;
3890             } else if (sc->samples_per_frame > 1) {
3891                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
3892                 count = (chunk_samples+samples-1) / samples;
3893             } else {
3894                 count = (chunk_samples+1023) / 1024;
3895             }
3896
3897             if (mov_stsc_index_valid(i, sc->stsc_count))
3898                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
3899             else
3900                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
3901             total += chunk_count * count;
3902         }
3903
3904         av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
3905         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
3906             return;
3907         if (av_reallocp_array(&st->index_entries,
3908                               st->nb_index_entries + total,
3909                               sizeof(*st->index_entries)) < 0) {
3910             st->nb_index_entries = 0;
3911             return;
3912         }
3913         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
3914
3915         // populate index
3916         for (i = 0; i < sc->chunk_count; i++) {
3917             current_offset = sc->chunk_offsets[i];
3918             if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
3919                 i + 1 == sc->stsc_data[stsc_index + 1].first)
3920                 stsc_index++;
3921             chunk_samples = sc->stsc_data[stsc_index].count;
3922
3923             while (chunk_samples > 0) {
3924                 AVIndexEntry *e;
3925                 unsigned size, samples;
3926
3927                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
3928                     avpriv_request_sample(mov->fc,
3929                            "Zero bytes per frame, but %d samples per frame",
3930                            sc->samples_per_frame);
3931                     return;
3932                 }
3933
3934                 if (sc->samples_per_frame >= 160) { // gsm
3935                     samples = sc->samples_per_frame;
3936                     size = sc->bytes_per_frame;
3937                 } else {
3938                     if (sc->samples_per_frame > 1) {
3939                         samples = FFMIN((1024 / sc->samples_per_frame)*
3940                                         sc->samples_per_frame, chunk_samples);
3941                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
3942                     } else {
3943                         samples = FFMIN(1024, chunk_samples);
3944                         size = samples * sc->sample_size;
3945                     }
3946                 }
3947
3948                 if (st->nb_index_entries >= total) {
3949                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
3950                     return;
3951                 }
3952                 if (size > 0x3FFFFFFF) {
3953                     av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
3954                     return;
3955                 }
3956                 e = &st->index_entries[st->nb_index_entries++];
3957                 e->pos = current_offset;
3958                 e->timestamp = current_dts;
3959                 e->size = size;
3960                 e->min_distance = 0;
3961                 e->flags = AVINDEX_KEYFRAME;
3962                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
3963                        "size %u, duration %u\n", st->index, i, current_offset, current_dts,
3964                        size, samples);
3965
3966                 current_offset += size;
3967                 current_dts += samples;
3968                 chunk_samples -= samples;
3969             }
3970         }
3971     }
3972
3973     if (!mov->ignore_editlist && mov->advanced_editlist) {
3974         // Fix index according to edit lists.
3975         mov_fix_index(mov, st);
3976     }
3977
3978     mov_estimate_video_delay(mov, st);
3979 }
3980
3981 static int test_same_origin(const char *src, const char *ref) {
3982     char src_proto[64];
3983     char ref_proto[64];
3984     char src_auth[256];
3985     char ref_auth[256];
3986     char src_host[256];
3987     char ref_host[256];
3988     int src_port=-1;
3989     int ref_port=-1;
3990
3991     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
3992     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
3993
3994     if (strlen(src) == 0) {
3995         return -1;
3996     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
3997         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
3998         strlen(src_host) + 1 >= sizeof(src_host) ||
3999         strlen(ref_host) + 1 >= sizeof(ref_host)) {
4000         return 0;
4001     } else if (strcmp(src_proto, ref_proto) ||
4002                strcmp(src_auth, ref_auth) ||
4003                strcmp(src_host, ref_host) ||
4004                src_port != ref_port) {
4005         return 0;
4006     } else
4007         return 1;
4008 }
4009
4010 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
4011 {
4012     /* try relative path, we do not try the absolute because it can leak information about our
4013        system to an attacker */
4014     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
4015         char filename[1025];
4016         const char *src_path;
4017         int i, l;
4018
4019         /* find a source dir */
4020         src_path = strrchr(src, '/');
4021         if (src_path)
4022             src_path++;
4023         else
4024             src_path = src;
4025
4026         /* find a next level down to target */
4027         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
4028             if (ref->path[l] == '/') {
4029                 if (i == ref->nlvl_to - 1)
4030                     break;
4031                 else
4032                     i++;
4033             }
4034
4035         /* compose filename if next level down to target was found */
4036         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
4037             memcpy(filename, src, src_path - src);
4038             filename[src_path - src] = 0;
4039
4040             for (i = 1; i < ref->nlvl_from; i++)
4041                 av_strlcat(filename, "../", sizeof(filename));
4042
4043             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
4044             if (!c->use_absolute_path) {
4045                 int same_origin = test_same_origin(src, filename);
4046
4047                 if (!same_origin) {
4048                     av_log(c->fc, AV_LOG_ERROR,
4049                         "Reference with mismatching origin, %s not tried for security reasons, "
4050                         "set demuxer option use_absolute_path to allow it anyway\n",
4051                         ref->path);
4052                     return AVERROR(ENOENT);
4053                 }
4054
4055                 if(strstr(ref->path + l + 1, "..") ||
4056                    strstr(ref->path + l + 1, ":") ||
4057                    (ref->nlvl_from > 1 && same_origin < 0) ||
4058                    (filename[0] == '/' && src_path == src))
4059                     return AVERROR(ENOENT);
4060             }
4061
4062             if (strlen(filename) + 1 == sizeof(filename))
4063                 return AVERROR(ENOENT);
4064             if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
4065                 return 0;
4066         }
4067     } else if (c->use_absolute_path) {
4068         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
4069                "this is a possible security issue\n");
4070         if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
4071             return 0;
4072     } else {
4073         av_log(c->fc, AV_LOG_ERROR,
4074                "Absolute path %s not tried for security reasons, "
4075                "set demuxer option use_absolute_path to allow absolute paths\n",
4076                ref->path);
4077     }
4078
4079     return AVERROR(ENOENT);
4080 }
4081
4082 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
4083 {
4084     if (sc->time_scale <= 0) {
4085         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
4086         sc->time_scale = c->time_scale;
4087         if (sc->time_scale <= 0)
4088             sc->time_scale = 1;
4089     }
4090 }
4091
4092 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4093 {
4094     AVStream *st;
4095     MOVStreamContext *sc;
4096     int ret;
4097
4098     st = avformat_new_stream(c->fc, NULL);
4099     if (!st) return AVERROR(ENOMEM);
4100     st->id = c->fc->nb_streams;
4101     sc = av_mallocz(sizeof(MOVStreamContext));
4102     if (!sc) return AVERROR(ENOMEM);
4103
4104     st->priv_data = sc;
4105     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
4106     sc->ffindex = st->index;
4107     c->trak_index = st->index;
4108
4109     if ((ret = mov_read_default(c, pb, atom)) < 0)
4110         return ret;
4111
4112     c->trak_index = -1;
4113
4114     /* sanity checks */
4115     if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
4116                             (!sc->sample_size && !sc->sample_count))) ||
4117         (!sc->chunk_count && sc->sample_count)) {
4118         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
4119                st->index);
4120         return 0;
4121     }
4122
4123     fix_timescale(c, sc);
4124
4125     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
4126
4127     mov_build_index(c, st);
4128
4129     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
4130         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
4131         if (c->enable_drefs) {
4132             if (mov_open_dref(c, &sc->pb, c->fc->url, dref) < 0)
4133                 av_log(c->fc, AV_LOG_ERROR,
4134                        "stream %d, error opening alias: path='%s', dir='%s', "
4135                        "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
4136                        st->index, dref->path, dref->dir, dref->filename,
4137                        dref->volume, dref->nlvl_from, dref->nlvl_to);
4138         } else {
4139             av_log(c->fc, AV_LOG_WARNING,
4140                    "Skipped opening external track: "
4141                    "stream %d, alias: path='%s', dir='%s', "
4142                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
4143                    "Set enable_drefs to allow this.\n",
4144                    st->index, dref->path, dref->dir, dref->filename,
4145                    dref->volume, dref->nlvl_from, dref->nlvl_to);
4146         }
4147     } else {
4148         sc->pb = c->fc->pb;
4149         sc->pb_is_copied = 1;
4150     }
4151
4152     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
4153         if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
4154             sc->height && sc->width &&
4155             (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
4156             st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
4157                                              ((double)st->codecpar->width * sc->height), INT_MAX);
4158         }
4159
4160 #if FF_API_R_FRAME_RATE
4161         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
4162             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
4163                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
4164 #endif
4165     }
4166
4167     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
4168     if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
4169         TAG_IS_AVCI(st->codecpar->codec_tag)) {
4170         ret = ff_generate_avci_extradata(st);
4171         if (ret < 0)
4172             return ret;
4173     }
4174
4175     switch (st->codecpar->codec_id) {
4176 #if CONFIG_H261_DECODER
4177     case AV_CODEC_ID_H261:
4178 #endif
4179 #if CONFIG_H263_DECODER
4180     case AV_CODEC_ID_H263:
4181 #endif
4182 #if CONFIG_MPEG4_DECODER
4183     case AV_CODEC_ID_MPEG4:
4184 #endif
4185         st->codecpar->width = 0; /* let decoder init width/height */
4186         st->codecpar->height= 0;
4187         break;
4188     }
4189
4190     // If the duration of the mp3 packets is not constant, then they could need a parser
4191     if (st->codecpar->codec_id == AV_CODEC_ID_MP3
4192         && sc->stts_count > 3
4193         && sc->stts_count*10 > st->nb_frames
4194         && sc->time_scale == st->codecpar->sample_rate) {
4195             st->need_parsing = AVSTREAM_PARSE_FULL;
4196     }
4197     /* Do not need those anymore. */
4198     av_freep(&sc->chunk_offsets);
4199     av_freep(&sc->sample_sizes);
4200     av_freep(&sc->keyframes);
4201     av_freep(&sc->stts_data);
4202     av_freep(&sc->stps_data);
4203     av_freep(&sc->elst_data);
4204     av_freep(&sc->rap_group);
4205
4206     return 0;
4207 }
4208
4209 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4210 {
4211     int ret;
4212     c->itunes_metadata = 1;
4213     ret = mov_read_default(c, pb, atom);
4214     c->itunes_metadata = 0;
4215     return ret;
4216 }
4217
4218 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4219 {
4220     uint32_t count;
4221     uint32_t i;
4222
4223     if (atom.size < 8)
4224         return 0;
4225
4226     avio_skip(pb, 4);
4227     count = avio_rb32(pb);
4228     if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
4229         av_log(c->fc, AV_LOG_ERROR,
4230                "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
4231         return AVERROR_INVALIDDATA;
4232     }
4233
4234     c->meta_keys_count = count + 1;
4235     c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
4236     if (!c->meta_keys)
4237         return AVERROR(ENOMEM);
4238
4239     for (i = 1; i <= count; ++i) {
4240         uint32_t key_size = avio_rb32(pb);
4241         uint32_t type = avio_rl32(pb);
4242         if (key_size < 8) {
4243             av_log(c->fc, AV_LOG_ERROR,
4244                    "The key# %"PRIu32" in meta has invalid size:"
4245                    "%"PRIu32"\n", i, key_size);
4246             return AVERROR_INVALIDDATA;
4247         }
4248         key_size -= 8;
4249         if (type != MKTAG('m','d','t','a')) {
4250             avio_skip(pb, key_size);
4251         }
4252         c->meta_keys[i] = av_mallocz(key_size + 1);
4253         if (!c->meta_keys[i])
4254             return AVERROR(ENOMEM);
4255         avio_read(pb, c->meta_keys[i], key_size);
4256     }
4257
4258     return 0;
4259 }
4260
4261 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4262 {
4263     int64_t end = avio_tell(pb) + atom.size;
4264     uint8_t *key = NULL, *val = NULL, *mean = NULL;
4265     int i;
4266     int ret = 0;
4267     AVStream *st;
4268     MOVStreamContext *sc;
4269
4270     if (c->fc->nb_streams < 1)
4271         return 0;
4272     st = c->fc->streams[c->fc->nb_streams-1];
4273     sc = st->priv_data;
4274
4275     for (i = 0; i < 3; i++) {
4276         uint8_t **p;
4277         uint32_t len, tag;
4278
4279         if (end - avio_tell(pb) <= 12)
4280             break;
4281
4282         len = avio_rb32(pb);
4283         tag = avio_rl32(pb);
4284         avio_skip(pb, 4); // flags
4285
4286         if (len < 12 || len - 12 > end - avio_tell(pb))
4287             break;
4288         len -= 12;
4289
4290         if (tag == MKTAG('m', 'e', 'a', 'n'))
4291             p = &mean;
4292         else if (tag == MKTAG('n', 'a', 'm', 'e'))
4293             p = &key;
4294         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
4295             avio_skip(pb, 4);
4296             len -= 4;
4297             p = &val;
4298         } else
4299             break;
4300
4301         *p = av_malloc(len + 1);
4302         if (!*p) {
4303             ret = AVERROR(ENOMEM);
4304             break;
4305         }
4306         ret = ffio_read_size(pb, *p, len);
4307         if (ret < 0) {
4308             av_freep(p);
4309             break;
4310         }
4311         (*p)[len] = 0;
4312     }
4313
4314     if (mean && key && val) {
4315         if (strcmp(key, "iTunSMPB") == 0) {
4316             int priming, remainder, samples;
4317             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
4318                 if(priming>0 && priming<16384)
4319                     sc->start_pad = priming;
4320             }
4321         }
4322         if (strcmp(key, "cdec") != 0) {
4323             av_dict_set(&c->fc->metadata, key, val,
4324                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
4325             key = val = NULL;
4326         }
4327     } else {
4328         av_log(c->fc, AV_LOG_VERBOSE,
4329                "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
4330     }
4331
4332     avio_seek(pb, end, SEEK_SET);
4333     av_freep(&key);
4334     av_freep(&val);
4335     av_freep(&mean);
4336     return ret;
4337 }
4338
4339 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4340 {
4341     while (atom.size > 8) {
4342         uint32_t tag = avio_rl32(pb);
4343         atom.size -= 4;
4344         if (tag == MKTAG('h','d','l','r')) {
4345             avio_seek(pb, -8, SEEK_CUR);
4346             atom.size += 8;
4347             return mov_read_default(c, pb, atom);
4348         }
4349     }
4350     return 0;
4351 }
4352
4353 // return 1 when matrix is identity, 0 otherwise
4354 #define IS_MATRIX_IDENT(matrix)            \
4355     ( (matrix)[0][0] == (1 << 16) &&       \
4356       (matrix)[1][1] == (1 << 16) &&       \
4357       (matrix)[2][2] == (1 << 30) &&       \
4358      !(matrix)[0][1] && !(matrix)[0][2] && \
4359      !(matrix)[1][0] && !(matrix)[1][2] && \
4360      !(matrix)[2][0] && !(matrix)[2][1])
4361
4362 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4363 {
4364     int i, j, e;
4365     int width;
4366     int height;
4367     int display_matrix[3][3];
4368     int res_display_matrix[3][3] = { { 0 } };
4369     AVStream *st;
4370     MOVStreamContext *sc;
4371     int version;
4372     int flags;
4373
4374     if (c->fc->nb_streams < 1)
4375         return 0;
4376     st = c->fc->streams[c->fc->nb_streams-1];
4377     sc = st->priv_data;
4378
4379     version = avio_r8(pb);
4380     flags = avio_rb24(pb);
4381     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
4382
4383     if (version == 1) {
4384         avio_rb64(pb);
4385         avio_rb64(pb);
4386     } else {
4387         avio_rb32(pb); /* creation time */
4388         avio_rb32(pb); /* modification time */
4389     }
4390     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
4391     avio_rb32(pb); /* reserved */
4392
4393     /* highlevel (considering edits) duration in movie timebase */
4394     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
4395     avio_rb32(pb); /* reserved */
4396     avio_rb32(pb); /* reserved */
4397
4398     avio_rb16(pb); /* layer */
4399     avio_rb16(pb); /* alternate group */
4400     avio_rb16(pb); /* volume */
4401     avio_rb16(pb); /* reserved */
4402
4403     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
4404     // they're kept in fixed point format through all calculations
4405     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
4406     // side data, but the scale factor is not needed to calculate aspect ratio
4407     for (i = 0; i < 3; i++) {
4408         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
4409         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
4410         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
4411     }
4412
4413     width = avio_rb32(pb);       // 16.16 fixed point track width
4414     height = avio_rb32(pb);      // 16.16 fixed point track height
4415     sc->width = width >> 16;
4416     sc->height = height >> 16;
4417
4418     // apply the moov display matrix (after the tkhd one)
4419     for (i = 0; i < 3; i++) {
4420         const int sh[3] = { 16, 16, 30 };
4421         for (j = 0; j < 3; j++) {
4422             for (e = 0; e < 3; e++) {
4423                 res_display_matrix[i][j] +=
4424                     ((int64_t) display_matrix[i][e] *
4425                      c->movie_display_matrix[e][j]) >> sh[e];
4426             }
4427         }
4428     }
4429
4430     // save the matrix when it is not the default identity
4431     if (!IS_MATRIX_IDENT(res_display_matrix)) {
4432         double rotate;
4433
4434         av_freep(&sc->display_matrix);
4435         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
4436         if (!sc->display_matrix)
4437             return AVERROR(ENOMEM);
4438
4439         for (i = 0; i < 3; i++)
4440             for (j = 0; j < 3; j++)
4441                 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
4442
4443 #if FF_API_OLD_ROTATE_API
4444         rotate = av_display_rotation_get(sc->display_matrix);
4445         if (!isnan(rotate)) {
4446             char rotate_buf[64];
4447             rotate = -rotate;
4448             if (rotate < 0) // for backward compatibility
4449                 rotate += 360;
4450             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
4451             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
4452         }
4453 #endif
4454     }
4455
4456     // transform the display width/height according to the matrix
4457     // to keep the same scale, use [width height 1<<16]
4458     if (width && height && sc->display_matrix) {
4459         double disp_transform[2];
4460
4461         for (i = 0; i < 2; i++)
4462             disp_transform[i] = hypot(sc->display_matrix[0 + i],
4463                                       sc->display_matrix[3 + i]);
4464
4465         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
4466             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
4467             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
4468             st->sample_aspect_ratio = av_d2q(
4469                 disp_transform[0] / disp_transform[1],
4470                 INT_MAX);
4471     }
4472     return 0;
4473 }
4474
4475 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4476 {
4477     MOVFragment *frag = &c->fragment;
4478     MOVTrackExt *trex = NULL;
4479     int flags, track_id, i;
4480
4481     avio_r8(pb); /* version */
4482     flags = avio_rb24(pb);
4483
4484     track_id = avio_rb32(pb);
4485     if (!track_id)
4486         return AVERROR_INVALIDDATA;
4487     frag->track_id = track_id;
4488     set_frag_stream(&c->frag_index, track_id);
4489     for (i = 0; i < c->trex_count; i++)
4490         if (c->trex_data[i].track_id == frag->track_id) {
4491             trex = &c->trex_data[i];
4492             break;
4493         }
4494     if (!trex) {
4495         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
4496         return AVERROR_INVALIDDATA;
4497     }
4498
4499     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
4500                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
4501                              frag->moof_offset : frag->implicit_offset;
4502     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
4503
4504     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
4505                      avio_rb32(pb) : trex->duration;
4506     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
4507                      avio_rb32(pb) : trex->size;
4508     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
4509                      avio_rb32(pb) : trex->flags;
4510     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
4511
4512     return 0;
4513 }
4514
4515 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4516 {
4517     unsigned i, num;
4518     void *new_tracks;
4519
4520     num = atom.size / 4;
4521     if (!(new_tracks = av_malloc_array(num, sizeof(int))))
4522         return AVERROR(ENOMEM);
4523
4524     av_free(c->chapter_tracks);
4525     c->chapter_tracks = new_tracks;
4526     c->nb_chapter_tracks = num;
4527
4528     for (i = 0; i < num && !pb->eof_reached; i++)
4529         c->chapter_tracks[i] = avio_rb32(pb);
4530
4531     return 0;
4532 }
4533
4534 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4535 {
4536     MOVTrackExt *trex;
4537     int err;
4538
4539     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
4540         return AVERROR_INVALIDDATA;
4541     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
4542                                  sizeof(*c->trex_data))) < 0) {
4543         c->trex_count = 0;
4544         return err;
4545     }
4546
4547     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
4548
4549     trex = &c->trex_data[c->trex_count++];
4550     avio_r8(pb); /* version */
4551     avio_rb24(pb); /* flags */
4552     trex->track_id = avio_rb32(pb);
4553     trex->stsd_id  = avio_rb32(pb);
4554     trex->duration = avio_rb32(pb);
4555     trex->size     = avio_rb32(pb);
4556     trex->flags    = avio_rb32(pb);
4557     return 0;
4558 }
4559
4560 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4561 {
4562     MOVFragment *frag = &c->fragment;
4563     AVStream *st = NULL;
4564     MOVStreamContext *sc;
4565     int version, i;
4566     MOVFragmentStreamInfo * frag_stream_info;
4567     int64_t base_media_decode_time;
4568
4569     for (i = 0; i < c->fc->nb_streams; i++) {
4570         if (c->fc->streams[i]->id == frag->track_id) {
4571             st = c->fc->streams[i];
4572             break;
4573         }
4574     }
4575     if (!st) {
4576         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4577         return AVERROR_INVALIDDATA;
4578     }
4579     sc = st->priv_data;
4580     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
4581         return 0;
4582     version = avio_r8(pb);
4583     avio_rb24(pb); /* flags */
4584     if (version) {
4585         base_media_decode_time = avio_rb64(pb);
4586     } else {
4587         base_media_decode_time = avio_rb32(pb);
4588     }
4589
4590     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4591     if (frag_stream_info)
4592         frag_stream_info->tfdt_dts = base_media_decode_time;
4593     sc->track_end = base_media_decode_time;
4594
4595     return 0;
4596 }
4597
4598 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4599 {
4600     MOVFragment *frag = &c->fragment;
4601     AVStream *st = NULL;
4602     MOVStreamContext *sc;
4603     MOVStts *ctts_data;
4604     uint64_t offset;
4605     int64_t dts, pts = AV_NOPTS_VALUE;
4606     int data_offset = 0;
4607     unsigned entries, first_sample_flags = frag->flags;
4608     int flags, distance, i;
4609     int64_t prev_dts = AV_NOPTS_VALUE;
4610     int next_frag_index = -1, index_entry_pos;
4611     size_t requested_size;
4612     size_t old_ctts_allocated_size;
4613     AVIndexEntry *new_entries;
4614     MOVFragmentStreamInfo * frag_stream_info;
4615
4616     for (i = 0; i < c->fc->nb_streams; i++) {
4617         if (c->fc->streams[i]->id == frag->track_id) {
4618             st = c->fc->streams[i];
4619             break;
4620         }
4621     }
4622     if (!st) {
4623         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
4624         return AVERROR_INVALIDDATA;
4625     }
4626     sc = st->priv_data;
4627     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
4628         return 0;
4629
4630     // Find the next frag_index index that has a valid index_entry for
4631     // the current track_id.
4632     //
4633     // A valid index_entry means the trun for the fragment was read
4634     // and it's samples are in index_entries at the given position.
4635     // New index entries will be inserted before the index_entry found.
4636     index_entry_pos = st->nb_index_entries;
4637     for (i = c->frag_index.current + 1; i < c->frag_index.nb_items; i++) {
4638         frag_stream_info = get_frag_stream_info(&c->frag_index, i, frag->track_id);
4639         if (frag_stream_info && frag_stream_info->index_entry >= 0) {
4640             next_frag_index = i;
4641             index_entry_pos = frag_stream_info->index_entry;
4642             break;
4643         }
4644     }
4645
4646     avio_r8(pb); /* version */
4647     flags = avio_rb24(pb);
4648     entries = avio_rb32(pb);
4649     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
4650
4651     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
4652         return AVERROR_INVALIDDATA;
4653     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
4654     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
4655
4656     frag_stream_info = get_current_frag_stream_info(&c->frag_index);
4657     if (frag_stream_info)
4658     {
4659         if (frag_stream_info->first_tfra_pts != AV_NOPTS_VALUE &&
4660             c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
4661             pts = frag_stream_info->first_tfra_pts;
4662             av_log(c->fc, AV_LOG_DEBUG, "found mfra time %"PRId64
4663                     ", using it for pts\n", pts);
4664         } else if (frag_stream_info->sidx_pts != AV_NOPTS_VALUE) {
4665             // FIXME: sidx earliest_presentation_time is *PTS*, s.b.
4666             // pts = frag_stream_info->sidx_pts;
4667             dts = frag_stream_info->sidx_pts - sc->time_offset;
4668             av_log(c->fc, AV_LOG_DEBUG, "found sidx time %"PRId64
4669                     ", using it for pts\n", pts);
4670         } else if (frag_stream_info->tfdt_dts != AV_NOPTS_VALUE) {
4671             dts = frag_stream_info->tfdt_dts - sc->time_offset;
4672             av_log(c->fc, AV_LOG_DEBUG, "found tfdt time %"PRId64
4673                     ", using it for dts\n", dts);
4674         } else {
4675             dts = sc->track_end - sc->time_offset;
4676             av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4677                     ", using it for dts\n", dts);
4678         }
4679     } else {
4680         dts = sc->track_end - sc->time_offset;
4681         av_log(c->fc, AV_LOG_DEBUG, "found track end time %"PRId64
4682                 ", using it for dts\n", dts);
4683     }
4684     offset   = frag->base_data_offset + data_offset;
4685     distance = 0;
4686     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
4687
4688     // realloc space for new index entries
4689     if((unsigned)st->nb_index_entries + entries >= UINT_MAX / sizeof(AVIndexEntry)) {
4690         entries = UINT_MAX / sizeof(AVIndexEntry) - st->nb_index_entries;
4691         av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
4692     }
4693     if (entries <= 0)
4694         return -1;
4695
4696     requested_size = (st->nb_index_entries + entries) * sizeof(AVIndexEntry);
4697     new_entries = av_fast_realloc(st->index_entries,
4698                                   &st->index_entries_allocated_size,
4699                                   requested_size);
4700     if(!new_entries)
4701         return AVERROR(ENOMEM);
4702     st->index_entries= new_entries;
4703
4704     requested_size = (st->nb_index_entries + entries) * sizeof(*sc->ctts_data);
4705     old_ctts_allocated_size = sc->ctts_allocated_size;
4706     ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size,
4707                                 requested_size);
4708     if (!ctts_data)
4709         return AVERROR(ENOMEM);
4710     sc->ctts_data = ctts_data;
4711
4712     // In case there were samples without ctts entries, ensure they get
4713     // zero valued entries. This ensures clips which mix boxes with and
4714     // without ctts entries don't pickup uninitialized data.
4715     memset((uint8_t*)(sc->ctts_data) + old_ctts_allocated_size, 0,
4716            sc->ctts_allocated_size - old_ctts_allocated_size);
4717
4718     if (index_entry_pos < st->nb_index_entries) {
4719         // Make hole in index_entries and ctts_data for new samples
4720         memmove(st->index_entries + index_entry_pos + entries,
4721                 st->index_entries + index_entry_pos,
4722                 sizeof(*st->index_entries) *
4723                 (st->nb_index_entries - index_entry_pos));
4724         memmove(sc->ctts_data + index_entry_pos + entries,
4725                 sc->ctts_data + index_entry_pos,
4726                 sizeof(*sc->ctts_data) * (sc->ctts_count - index_entry_pos));
4727         if (index_entry_pos < sc->current_sample) {
4728             sc->current_sample += entries;
4729         }
4730     }
4731
4732     st->nb_index_entries += entries;
4733     sc->ctts_count = st->nb_index_entries;
4734
4735     // Record the index_entry position in frag_index of this fragment
4736     if (frag_stream_info)
4737         frag_stream_info->index_entry = index_entry_pos;
4738
4739     if (index_entry_pos > 0)
4740         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4741
4742     for (i = 0; i < entries && !pb->eof_reached; i++) {
4743         unsigned sample_size = frag->size;
4744         int sample_flags = i ? frag->flags : first_sample_flags;
4745         unsigned sample_duration = frag->duration;
4746         unsigned ctts_duration = 0;
4747         int keyframe = 0;
4748         int index_entry_flags = 0;
4749
4750         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
4751         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
4752         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
4753         if (flags & MOV_TRUN_SAMPLE_CTS)      ctts_duration   = avio_rb32(pb);
4754
4755         mov_update_dts_shift(sc, ctts_duration);
4756         if (pts != AV_NOPTS_VALUE) {
4757             dts = pts - sc->dts_shift;
4758             if (flags & MOV_TRUN_SAMPLE_CTS) {
4759                 dts -= ctts_duration;
4760             } else {
4761                 dts -= sc->time_offset;
4762             }
4763             av_log(c->fc, AV_LOG_DEBUG,
4764                    "pts %"PRId64" calculated dts %"PRId64
4765                    " sc->dts_shift %d ctts.duration %d"
4766                    " sc->time_offset %"PRId64
4767                    " flags & MOV_TRUN_SAMPLE_CTS %d\n",
4768                    pts, dts,
4769                    sc->dts_shift, ctts_duration,
4770                    sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
4771             pts = AV_NOPTS_VALUE;
4772         }
4773
4774         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
4775             keyframe = 1;
4776         else
4777             keyframe =
4778                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
4779                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
4780         if (keyframe) {
4781             distance = 0;
4782             index_entry_flags |= AVINDEX_KEYFRAME;
4783         }
4784         // Fragments can overlap in time.  Discard overlapping frames after
4785         // decoding.
4786         if (prev_dts >= dts)
4787             index_entry_flags |= AVINDEX_DISCARD_FRAME;
4788
4789         st->index_entries[index_entry_pos].pos = offset;
4790         st->index_entries[index_entry_pos].timestamp = dts;
4791         st->index_entries[index_entry_pos].size= sample_size;
4792         st->index_entries[index_entry_pos].min_distance= distance;
4793         st->index_entries[index_entry_pos].flags = index_entry_flags;
4794
4795         sc->ctts_data[index_entry_pos].count = 1;
4796         sc->ctts_data[index_entry_pos].duration = ctts_duration;
4797         index_entry_pos++;
4798
4799         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
4800                 "size %u, distance %d, keyframe %d\n", st->index,
4801                 index_entry_pos, offset, dts, sample_size, distance, keyframe);
4802         distance++;
4803         dts += sample_duration;
4804         offset += sample_size;
4805         sc->data_size += sample_size;
4806
4807         if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
4808             1 <= INT64_MAX - sc->nb_frames_for_fps
4809         ) {
4810             sc->duration_for_fps += sample_duration;
4811             sc->nb_frames_for_fps ++;
4812         }
4813     }
4814     if (i < entries) {
4815         // EOF found before reading all entries.  Fix the hole this would
4816         // leave in index_entries and ctts_data
4817         int gap = entries - i;
4818         memmove(st->index_entries + index_entry_pos,
4819                 st->index_entries + index_entry_pos + gap,
4820                 sizeof(*st->index_entries) *
4821                 (st->nb_index_entries - (index_entry_pos + gap)));
4822         memmove(sc->ctts_data + index_entry_pos,
4823                 sc->ctts_data + index_entry_pos + gap,
4824                 sizeof(*sc->ctts_data) *
4825                 (sc->ctts_count - (index_entry_pos + gap)));
4826
4827         st->nb_index_entries -= gap;
4828         sc->ctts_count -= gap;
4829         if (index_entry_pos < sc->current_sample) {
4830             sc->current_sample -= gap;
4831         }
4832         entries = i;
4833     }
4834
4835     // The end of this new fragment may overlap in time with the start
4836     // of the next fragment in index_entries. Mark the samples in the next
4837     // fragment that overlap with AVINDEX_DISCARD_FRAME
4838     prev_dts = AV_NOPTS_VALUE;
4839     if (index_entry_pos > 0)
4840         prev_dts = st->index_entries[index_entry_pos-1].timestamp;
4841     for (i = index_entry_pos; i < st->nb_index_entries; i++) {
4842         if (prev_dts < st->index_entries[i].timestamp)
4843             break;
4844         st->index_entries[i].flags |= AVINDEX_DISCARD_FRAME;
4845     }
4846
4847     // If a hole was created to insert the new index_entries into,
4848     // the index_entry recorded for all subsequent moof must
4849     // be incremented by the number of entries inserted.
4850     fix_frag_index_entries(&c->frag_index, next_frag_index,
4851                            frag->track_id, entries);
4852
4853     if (pb->eof_reached) {
4854         av_log(c->fc, AV_LOG_WARNING, "reached eof, corrupted TRUN atom\n");
4855         return AVERROR_EOF;
4856     }
4857
4858     frag->implicit_offset = offset;
4859
4860     sc->track_end = dts + sc->time_offset;
4861     if (st->duration < sc->track_end)
4862         st->duration = sc->track_end;
4863
4864     return 0;
4865 }
4866
4867 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4868 {
4869     int64_t offset = avio_tell(pb) + atom.size, pts, timestamp;
4870     uint8_t version;
4871     unsigned i, j, track_id, item_count;
4872     AVStream *st = NULL;
4873     AVStream *ref_st = NULL;
4874     MOVStreamContext *sc, *ref_sc = NULL;
4875     AVRational timescale;
4876
4877     version = avio_r8(pb);
4878     if (version > 1) {
4879         avpriv_request_sample(c->fc, "sidx version %u", version);
4880         return 0;
4881     }
4882
4883     avio_rb24(pb); // flags
4884
4885     track_id = avio_rb32(pb); // Reference ID
4886     for (i = 0; i < c->fc->nb_streams; i++) {
4887         if (c->fc->streams[i]->id == track_id) {
4888             st = c->fc->streams[i];
4889             break;
4890         }
4891     }
4892     if (!st) {
4893         av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
4894         return 0;
4895     }
4896
4897     sc = st->priv_data;
4898
4899     timescale = av_make_q(1, avio_rb32(pb));
4900
4901     if (timescale.den <= 0) {
4902         av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
4903         return AVERROR_INVALIDDATA;
4904     }
4905
4906     if (version == 0) {
4907         pts = avio_rb32(pb);
4908         offset += avio_rb32(pb);
4909     } else {
4910         pts = avio_rb64(pb);
4911         offset += avio_rb64(pb);
4912     }
4913
4914     avio_rb16(pb); // reserved
4915
4916     item_count = avio_rb16(pb);
4917
4918     for (i = 0; i < item_count; i++) {
4919         int index;
4920         MOVFragmentStreamInfo * frag_stream_info;
4921         uint32_t size = avio_rb32(pb);
4922         uint32_t duration = avio_rb32(pb);
4923         if (size & 0x80000000) {
4924             avpriv_request_sample(c->fc, "sidx reference_type 1");
4925             return AVERROR_PATCHWELCOME;
4926         }
4927         avio_rb32(pb); // sap_flags
4928         timestamp = av_rescale_q(pts, st->time_base, timescale);
4929
4930         index = update_frag_index(c, offset);
4931         frag_stream_info = get_frag_stream_info(&c->frag_index, index, track_id);
4932         if (frag_stream_info)
4933             frag_stream_info->sidx_pts = timestamp;
4934
4935         offset += size;
4936         pts += duration;
4937     }
4938
4939     st->duration = sc->track_end = pts;
4940
4941     sc->has_sidx = 1;
4942
4943     if (offset == avio_size(pb)) {
4944         // Find first entry in fragment index that came from an sidx.
4945         // This will pretty much always be the first entry.
4946         for (i = 0; i < c->frag_index.nb_items; i++) {
4947             MOVFragmentIndexItem * item = &c->frag_index.item[i];
4948             for (j = 0; ref_st == NULL && j < item->nb_stream_info; j++) {
4949                 MOVFragmentStreamInfo * si;
4950                 si = &item->stream_info[j];
4951                 if (si->sidx_pts != AV_NOPTS_VALUE) {
4952                     ref_st = c->fc->streams[j];
4953                     ref_sc = ref_st->priv_data;
4954                     break;
4955                 }
4956             }
4957         }
4958         for (i = 0; i < c->fc->nb_streams; i++) {
4959             st = c->fc->streams[i];
4960             sc = st->priv_data;
4961             if (!sc->has_sidx) {
4962                 st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
4963             }
4964         }
4965
4966         c->frag_index.complete = 1;
4967     }
4968
4969     return 0;
4970 }
4971
4972 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
4973 /* like the files created with Adobe Premiere 5.0, for samples see */
4974 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
4975 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4976 {
4977     int err;
4978
4979     if (atom.size < 8)
4980         return 0; /* continue */
4981     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
4982         avio_skip(pb, atom.size - 4);
4983         return 0;
4984     }
4985     atom.type = avio_rl32(pb);
4986     atom.size -= 8;
4987     if (atom.type != MKTAG('m','d','a','t')) {
4988         avio_skip(pb, atom.size);
4989         return 0;
4990     }
4991     err = mov_read_mdat(c, pb, atom);
4992     return err;
4993 }
4994
4995 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4996 {
4997 #if CONFIG_ZLIB
4998     AVIOContext ctx;
4999     uint8_t *cmov_data;
5000     uint8_t *moov_data; /* uncompressed data */
5001     long cmov_len, moov_len;
5002     int ret = -1;
5003
5004     avio_rb32(pb); /* dcom atom */
5005     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
5006         return AVERROR_INVALIDDATA;
5007     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
5008         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
5009         return AVERROR_INVALIDDATA;
5010     }
5011     avio_rb32(pb); /* cmvd atom */
5012     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
5013         return AVERROR_INVALIDDATA;
5014     moov_len = avio_rb32(pb); /* uncompressed size */
5015     cmov_len = atom.size - 6 * 4;
5016
5017     cmov_data = av_malloc(cmov_len);
5018     if (!cmov_data)
5019         return AVERROR(ENOMEM);
5020     moov_data = av_malloc(moov_len);
5021     if (!moov_data) {
5022         av_free(cmov_data);
5023         return AVERROR(ENOMEM);
5024     }
5025     ret = ffio_read_size(pb, cmov_data, cmov_len);
5026     if (ret < 0)
5027         goto free_and_return;
5028
5029     ret = AVERROR_INVALIDDATA;
5030     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
5031         goto free_and_return;
5032     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
5033         goto free_and_return;
5034     ctx.seekable = AVIO_SEEKABLE_NORMAL;
5035     atom.type = MKTAG('m','o','o','v');
5036     atom.size = moov_len;
5037     ret = mov_read_default(c, &ctx, atom);
5038 free_and_return:
5039     av_free(moov_data);
5040     av_free(cmov_data);
5041     return ret;
5042 #else
5043     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
5044     return AVERROR(ENOSYS);
5045 #endif
5046 }
5047
5048 /* edit list atom */
5049 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5050 {
5051     MOVStreamContext *sc;
5052     int i, edit_count, version;
5053     int64_t elst_entry_size;
5054
5055     if (c->fc->nb_streams < 1 || c->ignore_editlist)
5056         return 0;
5057     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
5058
5059     version = avio_r8(pb); /* version */
5060     avio_rb24(pb); /* flags */
5061     edit_count = avio_rb32(pb); /* entries */
5062     atom.size -= 8;
5063
5064     elst_entry_size = version == 1 ? 20 : 12;
5065     if (atom.size != edit_count * elst_entry_size) {
5066         if (c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5067             av_log(c->fc, AV_LOG_ERROR, "Invalid edit list entry_count: %d for elst atom of size: %"PRId64" bytes.\n",
5068                    edit_count, atom.size + 8);
5069             return AVERROR_INVALIDDATA;
5070         } else {
5071             edit_count = atom.size / elst_entry_size;
5072             if (edit_count * elst_entry_size != atom.size) {
5073                 av_log(c->fc, AV_LOG_WARNING, "ELST atom of %"PRId64" bytes, bigger than %d entries.", atom.size, edit_count);
5074             }
5075         }
5076     }
5077
5078     if (!edit_count)
5079         return 0;
5080     if (sc->elst_data)
5081         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
5082     av_free(sc->elst_data);
5083     sc->elst_count = 0;
5084     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
5085     if (!sc->elst_data)
5086         return AVERROR(ENOMEM);
5087
5088     av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
5089     for (i = 0; i < edit_count && atom.size > 0 && !pb->eof_reached; i++) {
5090         MOVElst *e = &sc->elst_data[i];
5091
5092         if (version == 1) {
5093             e->duration = avio_rb64(pb);
5094             e->time     = avio_rb64(pb);
5095             atom.size -= 16;
5096         } else {
5097             e->duration = avio_rb32(pb); /* segment duration */
5098             e->time     = (int32_t)avio_rb32(pb); /* media time */
5099             atom.size -= 8;
5100         }
5101         e->rate = avio_rb32(pb) / 65536.0;
5102         atom.size -= 4;
5103         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
5104                e->duration, e->time, e->rate);
5105
5106         if (e->time < 0 && e->time != -1 &&
5107             c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
5108             av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
5109                    c->fc->nb_streams-1, i, e->time);
5110             return AVERROR_INVALIDDATA;
5111         }
5112     }
5113     sc->elst_count = i;
5114
5115     return 0;
5116 }
5117
5118 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5119 {
5120     MOVStreamContext *sc;
5121
5122     if (c->fc->nb_streams < 1)
5123         return AVERROR_INVALIDDATA;
5124     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5125     sc->timecode_track = avio_rb32(pb);
5126     return 0;
5127 }
5128
5129 static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5130 {
5131     AVStream *st;
5132     int version, color_range, color_primaries, color_trc, color_space;
5133
5134     if (c->fc->nb_streams < 1)
5135         return 0;
5136     st = c->fc->streams[c->fc->nb_streams - 1];
5137
5138     if (atom.size < 5) {
5139         av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
5140         return AVERROR_INVALIDDATA;
5141     }
5142
5143     version = avio_r8(pb);
5144     if (version != 1) {
5145         av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
5146         return 0;
5147     }
5148     avio_skip(pb, 3); /* flags */
5149
5150     avio_skip(pb, 2); /* profile + level */
5151     color_range     = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
5152     color_primaries = avio_r8(pb);
5153     color_trc       = avio_r8(pb);
5154     color_space     = avio_r8(pb);
5155     if (avio_rb16(pb)) /* codecIntializationDataSize */
5156         return AVERROR_INVALIDDATA;
5157
5158     if (!av_color_primaries_name(color_primaries))
5159         color_primaries = AVCOL_PRI_UNSPECIFIED;
5160     if (!av_color_transfer_name(color_trc))
5161         color_trc = AVCOL_TRC_UNSPECIFIED;
5162     if (!av_color_space_name(color_space))
5163         color_space = AVCOL_SPC_UNSPECIFIED;
5164
5165     st->codecpar->color_range     = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
5166     st->codecpar->color_primaries = color_primaries;
5167     st->codecpar->color_trc       = color_trc;
5168     st->codecpar->color_space     = color_space;
5169
5170     return 0;
5171 }
5172
5173 static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5174 {
5175     MOVStreamContext *sc;
5176     const int chroma_den = 50000;
5177     const int luma_den = 10000;
5178     int i, j, version;
5179
5180     if (c->fc->nb_streams < 1)
5181         return AVERROR_INVALIDDATA;
5182
5183     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5184
5185     if (atom.size < 5) {
5186         av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
5187         return AVERROR_INVALIDDATA;
5188     }
5189
5190     version = avio_r8(pb);
5191     if (version) {
5192         av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
5193         return 0;
5194     }
5195     avio_skip(pb, 3); /* flags */
5196
5197     sc->mastering = av_mastering_display_metadata_alloc();
5198     if (!sc->mastering)
5199         return AVERROR(ENOMEM);
5200
5201     for (i = 0; i < 3; i++)
5202         for (j = 0; j < 2; j++)
5203             sc->mastering->display_primaries[i][j] =
5204                 av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5205     for (i = 0; i < 2; i++)
5206         sc->mastering->white_point[i] =
5207             av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
5208     sc->mastering->max_luminance =
5209         av_make_q(lrint(((double)avio_rb32(pb) / (1 <<  8)) * luma_den), luma_den);
5210     sc->mastering->min_luminance =
5211         av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
5212
5213     sc->mastering->has_primaries = 1;
5214     sc->mastering->has_luminance = 1;
5215
5216     return 0;
5217 }
5218
5219 static int mov_read_mdcv(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5220 {
5221     MOVStreamContext *sc;
5222     const int mapping[3] = {1, 2, 0};
5223     const int chroma_den = 50000;
5224     const int luma_den = 10000;
5225     int i;
5226
5227     if (c->fc->nb_streams < 1)
5228         return AVERROR_INVALIDDATA;
5229
5230     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5231
5232     if (atom.size < 24) {
5233         av_log(c->fc, AV_LOG_ERROR, "Invalid Mastering Display Color Volume box\n");
5234         return AVERROR_INVALIDDATA;
5235     }
5236
5237     sc->mastering = av_mastering_display_metadata_alloc();
5238     if (!sc->mastering)
5239         return AVERROR(ENOMEM);
5240
5241     for (i = 0; i < 3; i++) {
5242         const int j = mapping[i];
5243         sc->mastering->display_primaries[j][0] = av_make_q(avio_rb16(pb), chroma_den);
5244         sc->mastering->display_primaries[j][1] = av_make_q(avio_rb16(pb), chroma_den);
5245     }
5246     sc->mastering->white_point[0] = av_make_q(avio_rb16(pb), chroma_den);
5247     sc->mastering->white_point[1] = av_make_q(avio_rb16(pb), chroma_den);
5248
5249     sc->mastering->max_luminance = av_make_q(avio_rb32(pb), luma_den);
5250     sc->mastering->min_luminance = av_make_q(avio_rb32(pb), luma_den);
5251
5252     sc->mastering->has_luminance = 1;
5253     sc->mastering->has_primaries = 1;
5254
5255     return 0;
5256 }
5257
5258 static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5259 {
5260     MOVStreamContext *sc;
5261     int version;
5262
5263     if (c->fc->nb_streams < 1)
5264         return AVERROR_INVALIDDATA;
5265
5266     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5267
5268     if (atom.size < 5) {
5269         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
5270         return AVERROR_INVALIDDATA;
5271     }
5272
5273     version = avio_r8(pb);
5274     if (version) {
5275         av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
5276         return 0;
5277     }
5278     avio_skip(pb, 3); /* flags */
5279
5280     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5281     if (!sc->coll)
5282         return AVERROR(ENOMEM);
5283
5284     sc->coll->MaxCLL  = avio_rb16(pb);
5285     sc->coll->MaxFALL = avio_rb16(pb);
5286
5287     return 0;
5288 }
5289
5290 static int mov_read_clli(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5291 {
5292     MOVStreamContext *sc;
5293
5294     if (c->fc->nb_streams < 1)
5295         return AVERROR_INVALIDDATA;
5296
5297     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
5298
5299     if (atom.size < 4) {
5300         av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level Info box\n");
5301         return AVERROR_INVALIDDATA;
5302     }
5303
5304     sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
5305     if (!sc->coll)
5306         return AVERROR(ENOMEM);
5307
5308     sc->coll->MaxCLL  = avio_rb16(pb);
5309     sc->coll->MaxFALL = avio_rb16(pb);
5310
5311     return 0;
5312 }
5313
5314 static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5315 {
5316     AVStream *st;
5317     MOVStreamContext *sc;
5318     enum AVStereo3DType type;
5319     int mode;
5320
5321     if (c->fc->nb_streams < 1)
5322         return 0;
5323
5324     st = c->fc->streams[c->fc->nb_streams - 1];
5325     sc = st->priv_data;
5326
5327     if (atom.size < 5) {
5328         av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
5329         return AVERROR_INVALIDDATA;
5330     }
5331     avio_skip(pb, 4); /* version + flags */
5332
5333     mode = avio_r8(pb);
5334     switch (mode) {
5335     case 0:
5336         type = AV_STEREO3D_2D;
5337         break;
5338     case 1:
5339         type = AV_STEREO3D_TOPBOTTOM;
5340         break;
5341     case 2:
5342         type = AV_STEREO3D_SIDEBYSIDE;
5343         break;
5344     default:
5345         av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
5346         return 0;
5347     }
5348
5349     sc->stereo3d = av_stereo3d_alloc();
5350     if (!sc->stereo3d)
5351         return AVERROR(ENOMEM);
5352
5353     sc->stereo3d->type = type;
5354     return 0;
5355 }
5356
5357 static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5358 {
5359     AVStream *st;
5360     MOVStreamContext *sc;
5361     int size, version, layout;
5362     int32_t yaw, pitch, roll;
5363     uint32_t l = 0, t = 0, r = 0, b = 0;
5364     uint32_t tag, padding = 0;
5365     enum AVSphericalProjection projection;
5366
5367     if (c->fc->nb_streams < 1)
5368         return 0;
5369
5370     st = c->fc->streams[c->fc->nb_streams - 1];
5371     sc = st->priv_data;
5372
5373     if (atom.size < 8) {
5374         av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
5375         return AVERROR_INVALIDDATA;
5376     }
5377
5378     size = avio_rb32(pb);
5379     if (size <= 12 || size > atom.size)
5380         return AVERROR_INVALIDDATA;
5381
5382     tag = avio_rl32(pb);
5383     if (tag != MKTAG('s','v','h','d')) {
5384         av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
5385         return 0;
5386     }
5387     version = avio_r8(pb);
5388     if (version != 0) {
5389         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5390                version);
5391         return 0;
5392     }
5393     avio_skip(pb, 3); /* flags */
5394     avio_skip(pb, size - 12); /* metadata_source */
5395
5396     size = avio_rb32(pb);
5397     if (size > atom.size)
5398         return AVERROR_INVALIDDATA;
5399
5400     tag = avio_rl32(pb);
5401     if (tag != MKTAG('p','r','o','j')) {
5402         av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
5403         return 0;
5404     }
5405
5406     size = avio_rb32(pb);
5407     if (size > atom.size)
5408         return AVERROR_INVALIDDATA;
5409
5410     tag = avio_rl32(pb);
5411     if (tag != MKTAG('p','r','h','d')) {
5412         av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
5413         return 0;
5414     }
5415     version = avio_r8(pb);
5416     if (version != 0) {
5417         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5418                version);
5419         return 0;
5420     }
5421     avio_skip(pb, 3); /* flags */
5422
5423     /* 16.16 fixed point */
5424     yaw   = avio_rb32(pb);
5425     pitch = avio_rb32(pb);
5426     roll  = avio_rb32(pb);
5427
5428     size = avio_rb32(pb);
5429     if (size > atom.size)
5430         return AVERROR_INVALIDDATA;
5431
5432     tag = avio_rl32(pb);
5433     version = avio_r8(pb);
5434     if (version != 0) {
5435         av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
5436                version);
5437         return 0;
5438     }
5439     avio_skip(pb, 3); /* flags */
5440     switch (tag) {
5441     case MKTAG('c','b','m','p'):
5442         layout = avio_rb32(pb);
5443         if (layout) {
5444             av_log(c->fc, AV_LOG_WARNING,
5445                    "Unsupported cubemap layout %d\n", layout);
5446             return 0;
5447         }
5448         projection = AV_SPHERICAL_CUBEMAP;
5449         padding = avio_rb32(pb);
5450         break;
5451     case MKTAG('e','q','u','i'):
5452         t = avio_rb32(pb);
5453         b = avio_rb32(pb);
5454         l = avio_rb32(pb);
5455         r = avio_rb32(pb);
5456
5457         if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
5458             av_log(c->fc, AV_LOG_ERROR,
5459                    "Invalid bounding rectangle coordinates "
5460                    "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
5461             return AVERROR_INVALIDDATA;
5462         }
5463
5464         if (l || t || r || b)
5465             projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
5466         else
5467             projection = AV_SPHERICAL_EQUIRECTANGULAR;
5468         break;
5469     default:
5470         av_log(c->fc, AV_LOG_ERROR, "Unknown projection type: %s\n", av_fourcc2str(tag));
5471         return 0;
5472     }
5473
5474     sc->spherical = av_spherical_alloc(&sc->spherical_size);
5475     if (!sc->spherical)
5476         return AVERROR(ENOMEM);
5477
5478     sc->spherical->projection = projection;
5479
5480     sc->spherical->yaw   = yaw;
5481     sc->spherical->pitch = pitch;
5482     sc->spherical->roll  = roll;
5483
5484     sc->spherical->padding = padding;
5485
5486     sc->spherical->bound_left   = l;
5487     sc->spherical->bound_top    = t;
5488     sc->spherical->bound_right  = r;
5489     sc->spherical->bound_bottom = b;
5490
5491     return 0;
5492 }
5493
5494 static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
5495 {
5496     int ret = 0;
5497     uint8_t *buffer = av_malloc(len + 1);
5498     const char *val;
5499
5500     if (!buffer)
5501         return AVERROR(ENOMEM);
5502     buffer[len] = '\0';
5503
5504     ret = ffio_read_size(pb, buffer, len);
5505     if (ret < 0)
5506         goto out;
5507
5508     /* Check for mandatory keys and values, try to support XML as best-effort */
5509     if (!sc->spherical &&
5510         av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
5511         (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
5512         av_stristr(val, "true") &&
5513         (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
5514         av_stristr(val, "true") &&
5515         (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
5516         av_stristr(val, "equirectangular")) {
5517         sc->spherical = av_spherical_alloc(&sc->spherical_size);
5518         if (!sc->spherical)
5519             goto out;
5520
5521         sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
5522
5523         if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
5524             enum AVStereo3DType mode;
5525
5526             if (av_stristr(buffer, "left-right"))
5527                 mode = AV_STEREO3D_SIDEBYSIDE;
5528             else if (av_stristr(buffer, "top-bottom"))
5529                 mode = AV_STEREO3D_TOPBOTTOM;
5530             else
5531                 mode = AV_STEREO3D_2D;
5532
5533             sc->stereo3d = av_stereo3d_alloc();
5534             if (!sc->stereo3d)
5535                 goto out;
5536
5537             sc->stereo3d->type = mode;
5538         }
5539
5540         /* orientation */
5541         val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
5542         if (val)
5543             sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
5544         val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
5545         if (val)
5546             sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
5547         val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
5548         if (val)
5549             sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
5550     }
5551
5552 out:
5553     av_free(buffer);
5554     return ret;
5555 }
5556
5557 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5558 {
5559     AVStream *st;
5560     MOVStreamContext *sc;
5561     int64_t ret;
5562     uint8_t uuid[16];
5563     static const uint8_t uuid_isml_manifest[] = {
5564         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
5565         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
5566     };
5567     static const uint8_t uuid_xmp[] = {
5568         0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
5569         0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
5570     };
5571     static const uint8_t uuid_spherical[] = {
5572         0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
5573         0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
5574     };
5575
5576     if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
5577         return AVERROR_INVALIDDATA;
5578
5579     if (c->fc->nb_streams < 1)
5580         return 0;
5581     st = c->fc->streams[c->fc->nb_streams - 1];
5582     sc = st->priv_data;
5583
5584     ret = avio_read(pb, uuid, sizeof(uuid));
5585     if (ret < 0) {
5586         return ret;
5587     } else if (ret != sizeof(uuid)) {
5588         return AVERROR_INVALIDDATA;
5589     }
5590     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
5591         uint8_t *buffer, *ptr;
5592         char *endptr;
5593         size_t len = atom.size - sizeof(uuid);
5594
5595         if (len < 4) {
5596             return AVERROR_INVALIDDATA;
5597         }
5598         ret = avio_skip(pb, 4); // zeroes
5599         len -= 4;
5600
5601         buffer = av_mallocz(len + 1);
5602         if (!buffer) {
5603             return AVERROR(ENOMEM);
5604         }
5605         ret = avio_read(pb, buffer, len);
5606         if (ret < 0) {
5607             av_free(buffer);
5608             return ret;
5609         } else if (ret != len) {
5610             av_free(buffer);
5611             return AVERROR_INVALIDDATA;
5612         }
5613
5614         ptr = buffer;
5615         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
5616             ptr += sizeof("systemBitrate=\"") - 1;
5617             c->bitrates_count++;
5618             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
5619             if (!c->bitrates) {
5620                 c->bitrates_count = 0;
5621                 av_free(buffer);
5622                 return AVERROR(ENOMEM);
5623             }
5624             errno = 0;
5625             ret = strtol(ptr, &endptr, 10);
5626             if (ret < 0 || errno || *endptr != '"') {
5627                 c->bitrates[c->bitrates_count - 1] = 0;
5628             } else {
5629                 c->bitrates[c->bitrates_count - 1] = ret;
5630             }
5631         }
5632
5633         av_free(buffer);
5634     } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
5635         uint8_t *buffer;
5636         size_t len = atom.size - sizeof(uuid);
5637         if (c->export_xmp) {
5638             buffer = av_mallocz(len + 1);
5639             if (!buffer) {
5640                 return AVERROR(ENOMEM);
5641             }
5642             ret = avio_read(pb, buffer, len);
5643             if (ret < 0) {
5644                 av_free(buffer);
5645                 return ret;
5646             } else if (ret != len) {
5647                 av_free(buffer);
5648                 return AVERROR_INVALIDDATA;
5649             }
5650             buffer[len] = '\0';
5651             av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
5652             av_free(buffer);
5653         } else {
5654             // skip all uuid atom, which makes it fast for long uuid-xmp file
5655             ret = avio_skip(pb, len);
5656             if (ret < 0)
5657                 return ret;
5658         }
5659     } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
5660         size_t len = atom.size - sizeof(uuid);
5661         ret = mov_parse_uuid_spherical(sc, pb, len);
5662         if (ret < 0)
5663             return ret;
5664         if (!sc->spherical)
5665             av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
5666     }
5667
5668     return 0;
5669 }
5670
5671 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5672 {
5673     int ret;
5674     uint8_t content[16];
5675
5676     if (atom.size < 8)
5677         return 0;
5678
5679     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
5680     if (ret < 0)
5681         return ret;
5682
5683     if (   !c->found_moov
5684         && !c->found_mdat
5685         && !memcmp(content, "Anevia\x1A\x1A", 8)
5686         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
5687         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
5688     }
5689
5690     return 0;
5691 }
5692
5693 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5694 {
5695     uint32_t format = avio_rl32(pb);
5696     MOVStreamContext *sc;
5697     enum AVCodecID id;
5698     AVStream *st;
5699
5700     if (c->fc->nb_streams < 1)
5701         return 0;
5702     st = c->fc->streams[c->fc->nb_streams - 1];
5703     sc = st->priv_data;
5704
5705     switch (sc->format)
5706     {
5707     case MKTAG('e','n','c','v'):        // encrypted video
5708     case MKTAG('e','n','c','a'):        // encrypted audio
5709         id = mov_codec_id(st, format);
5710         if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
5711             st->codecpar->codec_id != id) {
5712             av_log(c->fc, AV_LOG_WARNING,
5713                    "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
5714                    (char*)&format, st->codecpar->codec_id);
5715             break;
5716         }
5717
5718         st->codecpar->codec_id = id;
5719         sc->format = format;
5720         break;
5721
5722     default:
5723         if (format != sc->format) {
5724             av_log(c->fc, AV_LOG_WARNING,
5725                    "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
5726                    (char*)&format, (char*)&sc->format);
5727         }
5728         break;
5729     }
5730
5731     return 0;
5732 }
5733
5734 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5735 {
5736     AVStream *st;
5737     MOVStreamContext *sc;
5738     size_t auxiliary_info_size;
5739
5740     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5741         return 0;
5742
5743     st = c->fc->streams[c->fc->nb_streams - 1];
5744     sc = st->priv_data;
5745
5746     if (sc->cenc.aes_ctr) {
5747         av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
5748         return AVERROR_INVALIDDATA;
5749     }
5750
5751     avio_r8(pb); /* version */
5752     sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
5753
5754     avio_rb32(pb);        /* entries */
5755
5756     if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5757         av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
5758         return AVERROR_INVALIDDATA;
5759     }
5760
5761     /* save the auxiliary info as is */
5762     auxiliary_info_size = atom.size - 8;
5763
5764     sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
5765     if (!sc->cenc.auxiliary_info) {
5766         return AVERROR(ENOMEM);
5767     }
5768
5769     sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
5770     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
5771     sc->cenc.auxiliary_info_index = 0;
5772
5773     if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
5774         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
5775         return AVERROR_INVALIDDATA;
5776     }
5777
5778     /* initialize the cipher */
5779     sc->cenc.aes_ctr = av_aes_ctr_alloc();
5780     if (!sc->cenc.aes_ctr) {
5781         return AVERROR(ENOMEM);
5782     }
5783
5784     return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
5785 }
5786
5787 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5788 {
5789     AVStream *st;
5790     MOVStreamContext *sc;
5791     size_t data_size;
5792     int atom_header_size;
5793     int flags;
5794
5795     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
5796         return 0;
5797
5798     st = c->fc->streams[c->fc->nb_streams - 1];
5799     sc = st->priv_data;
5800
5801     if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
5802         av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
5803         return AVERROR_INVALIDDATA;
5804     }
5805
5806     atom_header_size = 9;
5807
5808     avio_r8(pb); /* version */
5809     flags = avio_rb24(pb);
5810
5811     if ((flags & 0x01) != 0) {
5812         atom_header_size += 8;
5813
5814         avio_rb32(pb);    /* info type */
5815         avio_rb32(pb);    /* info type param */
5816     }
5817
5818     sc->cenc.auxiliary_info_default_size = avio_r8(pb);
5819     avio_rb32(pb);    /* entries */
5820
5821     if (atom.size <= atom_header_size) {
5822         return 0;
5823     }
5824
5825     if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
5826         av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
5827         return AVERROR_INVALIDDATA;
5828     }
5829
5830     /* save the auxiliary info sizes as is */
5831     data_size = atom.size - atom_header_size;
5832
5833     sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
5834     if (!sc->cenc.auxiliary_info_sizes) {
5835         return AVERROR(ENOMEM);
5836     }
5837
5838     sc->cenc.auxiliary_info_sizes_count = data_size;
5839
5840     if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
5841         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
5842         return AVERROR_INVALIDDATA;
5843     }
5844
5845     return 0;
5846 }
5847
5848 static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5849 {
5850     AVStream *st;
5851     int last, type, size, ret;
5852     uint8_t buf[4];
5853
5854     if (c->fc->nb_streams < 1)
5855         return 0;
5856     st = c->fc->streams[c->fc->nb_streams-1];
5857
5858     if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
5859         return AVERROR_INVALIDDATA;
5860
5861     /* Check FlacSpecificBox version. */
5862     if (avio_r8(pb) != 0)
5863         return AVERROR_INVALIDDATA;
5864
5865     avio_rb24(pb); /* Flags */
5866
5867     avio_read(pb, buf, sizeof(buf));
5868     flac_parse_block_header(buf, &last, &type, &size);
5869
5870     if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
5871         av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
5872         return AVERROR_INVALIDDATA;
5873     }
5874
5875     ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
5876     if (ret < 0)
5877         return ret;
5878
5879     if (!last)
5880         av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
5881
5882     return 0;
5883 }
5884
5885 static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
5886 {
5887     size_t auxiliary_info_seek_offset = 0;
5888     int i;
5889
5890     if (sc->cenc.auxiliary_info_default_size) {
5891         auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
5892     } else if (sc->cenc.auxiliary_info_sizes) {
5893         if (index > sc->cenc.auxiliary_info_sizes_count) {
5894             av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
5895                 index, sc->cenc.auxiliary_info_sizes_count);
5896             return AVERROR_INVALIDDATA;
5897         }
5898
5899         for (i = 0; i < index; i++) {
5900             auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
5901         }
5902     }
5903
5904     if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
5905         av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
5906             auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
5907         return AVERROR_INVALIDDATA;
5908     }
5909
5910     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
5911     sc->cenc.auxiliary_info_index = index;
5912     return 0;
5913 }
5914
5915 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
5916 {
5917     uint32_t encrypted_bytes;
5918     uint16_t subsample_count;
5919     uint16_t clear_bytes;
5920     uint8_t* input_end = input + size;
5921     int ret;
5922
5923     if (index != sc->cenc.auxiliary_info_index) {
5924         ret = mov_seek_auxiliary_info(c, sc, index);
5925         if (ret < 0) {
5926             return ret;
5927         }
5928     }
5929
5930     /* read the iv */
5931     if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5932         av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
5933         return AVERROR_INVALIDDATA;
5934     }
5935
5936     av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
5937     sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
5938
5939     if (!sc->cenc.use_subsamples)
5940     {
5941         /* decrypt the whole packet */
5942         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
5943         return 0;
5944     }
5945
5946     /* read the subsample count */
5947     if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5948         av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
5949         return AVERROR_INVALIDDATA;
5950     }
5951
5952     subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
5953     sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5954
5955     for (; subsample_count > 0; subsample_count--)
5956     {
5957         if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
5958             av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
5959             return AVERROR_INVALIDDATA;
5960         }
5961
5962         /* read the number of clear / encrypted bytes */
5963         clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
5964         sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
5965         encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
5966         sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
5967
5968         if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
5969             av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
5970             return AVERROR_INVALIDDATA;
5971         }
5972
5973         /* skip the clear bytes */
5974         input += clear_bytes;
5975
5976         /* decrypt the encrypted bytes */
5977         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
5978         input += encrypted_bytes;
5979     }
5980
5981     if (input < input_end) {
5982         av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
5983         return AVERROR_INVALIDDATA;
5984     }
5985
5986     sc->cenc.auxiliary_info_index++;
5987     return 0;
5988 }
5989
5990 static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
5991 {
5992     const int OPUS_SEEK_PREROLL_MS = 80;
5993     AVStream *st;
5994     size_t size;
5995     int16_t pre_skip;
5996
5997     if (c->fc->nb_streams < 1)
5998         return 0;
5999     st = c->fc->streams[c->fc->nb_streams-1];
6000
6001     if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
6002         return AVERROR_INVALIDDATA;
6003
6004     /* Check OpusSpecificBox version. */
6005     if (avio_r8(pb) != 0) {
6006         av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
6007         return AVERROR_INVALIDDATA;
6008     }
6009
6010     /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
6011     size = atom.size + 8;
6012
6013     if (ff_alloc_extradata(st->codecpar, size))
6014         return AVERROR(ENOMEM);
6015
6016     AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
6017     AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
6018     AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
6019     avio_read(pb, st->codecpar->extradata + 9, size - 9);
6020
6021     /* OpusSpecificBox is stored in big-endian, but OpusHead is
6022        little-endian; aside from the preceeding magic and version they're
6023        otherwise currently identical.  Data after output gain at offset 16
6024        doesn't need to be bytewapped. */
6025     pre_skip = AV_RB16(st->codecpar->extradata + 10);
6026     AV_WL16(st->codecpar->extradata + 10, pre_skip);
6027     AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
6028     AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
6029
6030     st->codecpar->initial_padding = pre_skip;
6031     st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
6032                                               (AVRational){1, 1000},
6033                                               (AVRational){1, 48000});
6034
6035     return 0;
6036 }
6037
6038 static const MOVParseTableEntry mov_default_parse_table[] = {
6039 { MKTAG('A','C','L','R'), mov_read_aclr },
6040 { MKTAG('A','P','R','G'), mov_read_avid },
6041 { MKTAG('A','A','L','P'), mov_read_avid },
6042 { MKTAG('A','R','E','S'), mov_read_ares },
6043 { MKTAG('a','v','s','s'), mov_read_avss },
6044 { MKTAG('c','h','p','l'), mov_read_chpl },
6045 { MKTAG('c','o','6','4'), mov_read_stco },
6046 { MKTAG('c','o','l','r'), mov_read_colr },
6047 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
6048 { MKTAG('d','i','n','f'), mov_read_default },
6049 { MKTAG('D','p','x','E'), mov_read_dpxe },
6050 { MKTAG('d','r','e','f'), mov_read_dref },
6051 { MKTAG('e','d','t','s'), mov_read_default },
6052 { MKTAG('e','l','s','t'), mov_read_elst },
6053 { MKTAG('e','n','d','a'), mov_read_enda },
6054 { MKTAG('f','i','e','l'), mov_read_fiel },
6055 { MKTAG('a','d','r','m'), mov_read_adrm },
6056 { MKTAG('f','t','y','p'), mov_read_ftyp },
6057 { MKTAG('g','l','b','l'), mov_read_glbl },
6058 { MKTAG('h','d','l','r'), mov_read_hdlr },
6059 { MKTAG('i','l','s','t'), mov_read_ilst },
6060 { MKTAG('j','p','2','h'), mov_read_jp2h },
6061 { MKTAG('m','d','a','t'), mov_read_mdat },
6062 { MKTAG('m','d','h','d'), mov_read_mdhd },
6063 { MKTAG('m','d','i','a'), mov_read_default },
6064 { MKTAG('m','e','t','a'), mov_read_meta },
6065 { MKTAG('m','i','n','f'), mov_read_default },
6066 { MKTAG('m','o','o','f'), mov_read_moof },
6067 { MKTAG('m','o','o','v'), mov_read_moov },
6068 { MKTAG('m','v','e','x'), mov_read_default },
6069 { MKTAG('m','v','h','d'), mov_read_mvhd },
6070 { MKTAG('S','M','I',' '), mov_read_svq3 },
6071 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
6072 { MKTAG('a','v','c','C'), mov_read_glbl },
6073 { MKTAG('p','a','s','p'), mov_read_pasp },
6074 { MKTAG('s','i','d','x'), mov_read_sidx },
6075 { MKTAG('s','t','b','l'), mov_read_default },
6076 { MKTAG('s','t','c','o'), mov_read_stco },
6077 { MKTAG('s','t','p','s'), mov_read_stps },
6078 { MKTAG('s','t','r','f'), mov_read_strf },
6079 { MKTAG('s','t','s','c'), mov_read_stsc },
6080 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
6081 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
6082 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
6083 { MKTAG('s','t','t','s'), mov_read_stts },
6084 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
6085 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
6086 { MKTAG('t','f','d','t'), mov_read_tfdt },
6087 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
6088 { MKTAG('t','r','a','k'), mov_read_trak },
6089 { MKTAG('t','r','a','f'), mov_read_default },
6090 { MKTAG('t','r','e','f'), mov_read_default },
6091 { MKTAG('t','m','c','d'), mov_read_tmcd },
6092 { MKTAG('c','h','a','p'), mov_read_chap },
6093 { MKTAG('t','r','e','x'), mov_read_trex },
6094 { MKTAG('t','r','u','n'), mov_read_trun },
6095 { MKTAG('u','d','t','a'), mov_read_default },
6096 { MKTAG('w','a','v','e'), mov_read_wave },
6097 { MKTAG('e','s','d','s'), mov_read_esds },
6098 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
6099 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
6100 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
6101 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
6102 { MKTAG('w','f','e','x'), mov_read_wfex },
6103 { MKTAG('c','m','o','v'), mov_read_cmov },
6104 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
6105 { MKTAG('d','v','c','1'), mov_read_dvc1 },
6106 { MKTAG('s','b','g','p'), mov_read_sbgp },
6107 { MKTAG('h','v','c','C'), mov_read_glbl },
6108 { MKTAG('u','u','i','d'), mov_read_uuid },
6109 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
6110 { MKTAG('f','r','e','e'), mov_read_free },
6111 { MKTAG('-','-','-','-'), mov_read_custom },
6112 { MKTAG('s','i','n','f'), mov_read_default },
6113 { MKTAG('f','r','m','a'), mov_read_frma },
6114 { MKTAG('s','e','n','c'), mov_read_senc },
6115 { MKTAG('s','a','i','z'), mov_read_saiz },
6116 { MKTAG('d','f','L','a'), mov_read_dfla },
6117 { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
6118 { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
6119 { MKTAG('d','O','p','s'), mov_read_dops },
6120 { MKTAG('S','m','D','m'), mov_read_smdm },
6121 { MKTAG('C','o','L','L'), mov_read_coll },
6122 { MKTAG('v','p','c','C'), mov_read_vpcc },
6123 { MKTAG('m','d','c','v'), mov_read_mdcv },
6124 { MKTAG('c','l','l','i'), mov_read_clli },
6125 { 0, NULL }
6126 };
6127
6128 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
6129 {
6130     int64_t total_size = 0;
6131     MOVAtom a;
6132     int i;
6133
6134     if (c->atom_depth > 10) {
6135         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
6136         return AVERROR_INVALIDDATA;
6137     }
6138     c->atom_depth ++;
6139
6140     if (atom.size < 0)
6141         atom.size = INT64_MAX;
6142     while (total_size <= atom.size - 8 && !avio_feof(pb)) {
6143         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
6144         a.size = atom.size;
6145         a.type=0;
6146         if (atom.size >= 8) {
6147             a.size = avio_rb32(pb);
6148             a.type = avio_rl32(pb);
6149             if (a.type == MKTAG('f','r','e','e') &&
6150                 a.size >= 8 &&
6151                 c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
6152                 c->moov_retry) {
6153                 uint8_t buf[8];
6154                 uint32_t *type = (uint32_t *)buf + 1;
6155                 if (avio_read(pb, buf, 8) != 8)
6156                     return AVERROR_INVALIDDATA;
6157                 avio_seek(pb, -8, SEEK_CUR);
6158                 if (*type == MKTAG('m','v','h','d') ||
6159                     *type == MKTAG('c','m','o','v')) {
6160                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
6161                     a.type = MKTAG('m','o','o','v');
6162                 }
6163             }
6164             if (atom.type != MKTAG('r','o','o','t') &&
6165                 atom.type != MKTAG('m','o','o','v'))
6166             {
6167                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
6168                 {
6169                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
6170                     avio_skip(pb, -8);
6171                     c->atom_depth --;
6172                     return 0;
6173                 }
6174             }
6175             total_size += 8;
6176             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
6177                 a.size = avio_rb64(pb) - 8;
6178                 total_size += 8;
6179             }
6180         }
6181         av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
6182                av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
6183         if (a.size == 0) {
6184             a.size = atom.size - total_size + 8;
6185         }
6186         a.size -= 8;
6187         if (a.size < 0)
6188             break;
6189         a.size = FFMIN(a.size, atom.size - total_size);
6190
6191         for (i = 0; mov_default_parse_table[i].type; i++)
6192             if (mov_default_parse_table[i].type == a.type) {
6193                 parse = mov_default_parse_table[i].parse;
6194                 break;
6195             }
6196
6197         // container is user data
6198         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
6199                        atom.type == MKTAG('i','l','s','t')))
6200             parse = mov_read_udta_string;
6201
6202         // Supports parsing the QuickTime Metadata Keys.
6203         // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
6204         if (!parse && c->found_hdlr_mdta &&
6205             atom.type == MKTAG('m','e','t','a') &&
6206             a.type == MKTAG('k','e','y','s')) {
6207             parse = mov_read_keys;
6208         }
6209
6210         if (!parse) { /* skip leaf atoms data */
6211             avio_skip(pb, a.size);
6212         } else {
6213             int64_t start_pos = avio_tell(pb);
6214             int64_t left;
6215             int err = parse(c, pb, a);
6216             if (err < 0) {
6217                 c->atom_depth --;
6218                 return err;
6219             }
6220             if (c->found_moov && c->found_mdat &&
6221                 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete) ||
6222                  start_pos + a.size == avio_size(pb))) {
6223                 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->frag_index.complete)
6224                     c->next_root_atom = start_pos + a.size;
6225                 c->atom_depth --;
6226                 return 0;
6227             }
6228             left = a.size - avio_tell(pb) + start_pos;
6229             if (left > 0) /* skip garbage at atom end */
6230                 avio_skip(pb, left);
6231             else if (left < 0) {
6232                 av_log(c->fc, AV_LOG_WARNING,
6233                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
6234                        (char*)&a.type, -left);
6235                 avio_seek(pb, left, SEEK_CUR);
6236             }
6237         }
6238
6239         total_size += a.size;
6240     }
6241
6242     if (total_size < atom.size && atom.size < 0x7ffff)
6243         avio_skip(pb, atom.size - total_size);
6244
6245     c->atom_depth --;
6246     return 0;
6247 }
6248
6249 static int mov_probe(AVProbeData *p)
6250 {
6251     int64_t offset;
6252     uint32_t tag;
6253     int score = 0;
6254     int moov_offset = -1;
6255
6256     /* check file header */
6257     offset = 0;
6258     for (;;) {
6259         /* ignore invalid offset */
6260         if ((offset + 8) > (unsigned int)p->buf_size)
6261             break;
6262         tag = AV_RL32(p->buf + offset + 4);
6263         switch(tag) {
6264         /* check for obvious tags */
6265         case MKTAG('m','o','o','v'):
6266             moov_offset = offset + 4;
6267         case MKTAG('m','d','a','t'):
6268         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
6269         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
6270         case MKTAG('f','t','y','p'):
6271             if (AV_RB32(p->buf+offset) < 8 &&
6272                 (AV_RB32(p->buf+offset) != 1 ||
6273                  offset + 12 > (unsigned int)p->buf_size ||
6274                  AV_RB64(p->buf+offset + 8) == 0)) {
6275                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6276             } else if (tag == MKTAG('f','t','y','p') &&
6277                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
6278                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
6279                     )) {
6280                 score = FFMAX(score, 5);
6281             } else {
6282                 score = AVPROBE_SCORE_MAX;
6283             }
6284             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6285             break;
6286         /* those are more common words, so rate then a bit less */
6287         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
6288         case MKTAG('w','i','d','e'):
6289         case MKTAG('f','r','e','e'):
6290         case MKTAG('j','u','n','k'):
6291         case MKTAG('p','i','c','t'):
6292             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
6293             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6294             break;
6295         case MKTAG(0x82,0x82,0x7f,0x7d):
6296         case MKTAG('s','k','i','p'):
6297         case MKTAG('u','u','i','d'):
6298         case MKTAG('p','r','f','l'):
6299             /* if we only find those cause probedata is too small at least rate them */
6300             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
6301             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6302             break;
6303         default:
6304             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
6305         }
6306     }
6307     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
6308         /* moov atom in the header - we should make sure that this is not a
6309          * MOV-packed MPEG-PS */
6310         offset = moov_offset;
6311
6312         while(offset < (p->buf_size - 16)){ /* Sufficient space */
6313                /* We found an actual hdlr atom */
6314             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
6315                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
6316                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
6317                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
6318                 /* We found a media handler reference atom describing an
6319                  * MPEG-PS-in-MOV, return a
6320                  * low score to force expanding the probe window until
6321                  * mpegps_probe finds what it needs */
6322                 return 5;
6323             }else
6324                 /* Keep looking */
6325                 offset+=2;
6326         }
6327     }
6328
6329     return score;
6330 }
6331
6332 // must be done after parsing all trak because there's no order requirement
6333 static void mov_read_chapters(AVFormatContext *s)
6334 {
6335     MOVContext *mov = s->priv_data;
6336     AVStream *st;
6337     MOVStreamContext *sc;
6338     int64_t cur_pos;
6339     int i, j;
6340     int chapter_track;
6341
6342     for (j = 0; j < mov->nb_chapter_tracks; j++) {
6343         chapter_track = mov->chapter_tracks[j];
6344         st = NULL;
6345         for (i = 0; i < s->nb_streams; i++)
6346             if (s->streams[i]->id == chapter_track) {
6347                 st = s->streams[i];
6348                 break;
6349             }
6350         if (!st) {
6351             av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
6352             continue;
6353         }
6354
6355         sc = st->priv_data;
6356         cur_pos = avio_tell(sc->pb);
6357
6358         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
6359             st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
6360             if (st->nb_index_entries) {
6361                 // Retrieve the first frame, if possible
6362                 AVPacket pkt;
6363                 AVIndexEntry *sample = &st->index_entries[0];
6364                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6365                     av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
6366                     goto finish;
6367                 }
6368
6369                 if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
6370                     goto finish;
6371
6372                 st->attached_pic              = pkt;
6373                 st->attached_pic.stream_index = st->index;
6374                 st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
6375             }
6376         } else {
6377             st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
6378             st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
6379             st->discard = AVDISCARD_ALL;
6380             for (i = 0; i < st->nb_index_entries; i++) {
6381                 AVIndexEntry *sample = &st->index_entries[i];
6382                 int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
6383                 uint8_t *title;
6384                 uint16_t ch;
6385                 int len, title_len;
6386
6387                 if (end < sample->timestamp) {
6388                     av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
6389                     end = AV_NOPTS_VALUE;
6390                 }
6391
6392                 if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
6393                     av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
6394                     goto finish;
6395                 }
6396
6397                 // the first two bytes are the length of the title
6398                 len = avio_rb16(sc->pb);
6399                 if (len > sample->size-2)
6400                     continue;
6401                 title_len = 2*len + 1;
6402                 if (!(title = av_mallocz(title_len)))
6403                     goto finish;
6404
6405                 // The samples could theoretically be in any encoding if there's an encd
6406                 // atom following, but in practice are only utf-8 or utf-16, distinguished
6407                 // instead by the presence of a BOM
6408                 if (!len) {
6409                     title[0] = 0;
6410                 } else {
6411                     ch = avio_rb16(sc->pb);
6412                     if (ch == 0xfeff)
6413                         avio_get_str16be(sc->pb, len, title, title_len);
6414                     else if (ch == 0xfffe)
6415                         avio_get_str16le(sc->pb, len, title, title_len);
6416                     else {
6417                         AV_WB16(title, ch);
6418                         if (len == 1 || len == 2)
6419                             title[len] = 0;
6420                         else
6421                             avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
6422                     }
6423                 }
6424
6425                 avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
6426                 av_freep(&title);
6427             }
6428         }
6429 finish:
6430         avio_seek(sc->pb, cur_pos, SEEK_SET);
6431     }
6432 }
6433
6434 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
6435                                              uint32_t value, int flags)
6436 {
6437     AVTimecode tc;
6438     char buf[AV_TIMECODE_STR_SIZE];
6439     AVRational rate = st->avg_frame_rate;
6440     int ret = av_timecode_init(&tc, rate, flags, 0, s);
6441     if (ret < 0)
6442         return ret;
6443     av_dict_set(&st->metadata, "timecode",
6444                 av_timecode_make_string(&tc, buf, value), 0);
6445     return 0;
6446 }
6447
6448 static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
6449 {
6450     MOVStreamContext *sc = st->priv_data;
6451     char buf[AV_TIMECODE_STR_SIZE];
6452     int64_t cur_pos = avio_tell(sc->pb);
6453     int hh, mm, ss, ff, drop;
6454
6455     if (!st->nb_index_entries)
6456         return -1;
6457
6458     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6459     avio_skip(s->pb, 13);
6460     hh = avio_r8(s->pb);
6461     mm = avio_r8(s->pb);
6462     ss = avio_r8(s->pb);
6463     drop = avio_r8(s->pb);
6464     ff = avio_r8(s->pb);
6465     snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
6466              hh, mm, ss, drop ? ';' : ':', ff);
6467     av_dict_set(&st->metadata, "timecode", buf, 0);
6468
6469     avio_seek(sc->pb, cur_pos, SEEK_SET);
6470     return 0;
6471 }
6472
6473 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
6474 {
6475     MOVStreamContext *sc = st->priv_data;
6476     int flags = 0;
6477     int64_t cur_pos = avio_tell(sc->pb);
6478     uint32_t value;
6479
6480     if (!st->nb_index_entries)
6481         return -1;
6482
6483     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
6484     value = avio_rb32(s->pb);
6485
6486     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
6487     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
6488     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
6489
6490     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
6491      * not the case) and thus assume "frame number format" instead of QT one.
6492      * No sample with tmcd track can be found with a QT timecode at the moment,
6493      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
6494      * format). */
6495     parse_timecode_in_framenum_format(s, st, value, flags);
6496
6497     avio_seek(sc->pb, cur_pos, SEEK_SET);
6498     return 0;
6499 }
6500
6501 static int mov_read_close(AVFormatContext *s)
6502 {
6503     MOVContext *mov = s->priv_data;
6504     int i, j;
6505
6506     for (i = 0; i < s->nb_streams; i++) {
6507         AVStream *st = s->streams[i];
6508         MOVStreamContext *sc = st->priv_data;
6509
6510         if (!sc)
6511             continue;
6512
6513         av_freep(&sc->ctts_data);
6514         for (j = 0; j < sc->drefs_count; j++) {
6515             av_freep(&sc->drefs[j].path);
6516             av_freep(&sc->drefs[j].dir);
6517         }
6518         av_freep(&sc->drefs);
6519
6520         sc->drefs_count = 0;
6521
6522         if (!sc->pb_is_copied)
6523             ff_format_io_close(s, &sc->pb);
6524
6525         sc->pb = NULL;
6526         av_freep(&sc->chunk_offsets);
6527         av_freep(&sc->stsc_data);
6528         av_freep(&sc->sample_sizes);
6529         av_freep(&sc->keyframes);
6530         av_freep(&sc->stts_data);
6531         av_freep(&sc->stps_data);
6532         av_freep(&sc->elst_data);
6533         av_freep(&sc->rap_group);
6534         av_freep(&sc->display_matrix);
6535         av_freep(&sc->index_ranges);
6536
6537         if (sc->extradata)
6538             for (j = 0; j < sc->stsd_count; j++)
6539                 av_free(sc->extradata[j]);
6540         av_freep(&sc->extradata);
6541         av_freep(&sc->extradata_size);
6542
6543         av_freep(&sc->cenc.auxiliary_info);
6544         av_freep(&sc->cenc.auxiliary_info_sizes);
6545         av_aes_ctr_free(sc->cenc.aes_ctr);
6546
6547         av_freep(&sc->stereo3d);
6548         av_freep(&sc->spherical);
6549         av_freep(&sc->mastering);
6550         av_freep(&sc->coll);
6551     }
6552
6553     if (mov->dv_demux) {
6554         avformat_free_context(mov->dv_fctx);
6555         mov->dv_fctx = NULL;
6556     }
6557
6558     if (mov->meta_keys) {
6559         for (i = 1; i < mov->meta_keys_count; i++) {
6560             av_freep(&mov->meta_keys[i]);
6561         }
6562         av_freep(&mov->meta_keys);
6563     }
6564
6565     av_freep(&mov->trex_data);
6566     av_freep(&mov->bitrates);
6567
6568     for (i = 0; i < mov->frag_index.nb_items; i++) {
6569         av_freep(&mov->frag_index.item[i].stream_info);
6570     }
6571     av_freep(&mov->frag_index.item);
6572
6573     av_freep(&mov->aes_decrypt);
6574     av_freep(&mov->chapter_tracks);
6575
6576     return 0;
6577 }
6578
6579 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
6580 {
6581     int i;
6582
6583     for (i = 0; i < s->nb_streams; i++) {
6584         AVStream *st = s->streams[i];
6585         MOVStreamContext *sc = st->priv_data;
6586
6587         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
6588             sc->timecode_track == tmcd_id)
6589             return 1;
6590     }
6591     return 0;
6592 }
6593
6594 /* look for a tmcd track not referenced by any video track, and export it globally */
6595 static void export_orphan_timecode(AVFormatContext *s)
6596 {
6597     int i;
6598
6599     for (i = 0; i < s->nb_streams; i++) {
6600         AVStream *st = s->streams[i];
6601
6602         if (st->codecpar->codec_tag  == MKTAG('t','m','c','d') &&
6603             !tmcd_is_referenced(s, i + 1)) {
6604             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
6605             if (tcr) {
6606                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
6607                 break;
6608             }
6609         }
6610     }
6611 }
6612
6613 static int read_tfra(MOVContext *mov, AVIOContext *f)
6614 {
6615     int version, fieldlength, i, j;
6616     int64_t pos = avio_tell(f);
6617     uint32_t size = avio_rb32(f);
6618     unsigned track_id, item_count;
6619
6620     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
6621         return 1;
6622     }
6623     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
6624
6625     version = avio_r8(f);
6626     avio_rb24(f);
6627     track_id = avio_rb32(f);
6628     fieldlength = avio_rb32(f);
6629     item_count = avio_rb32(f);
6630     for (i = 0; i < item_count; i++) {
6631         int64_t time, offset;
6632         int index;
6633         MOVFragmentStreamInfo * frag_stream_info;
6634
6635         if (avio_feof(f)) {
6636             return AVERROR_INVALIDDATA;
6637         }
6638
6639         if (version == 1) {
6640             time   = avio_rb64(f);
6641             offset = avio_rb64(f);
6642         } else {
6643             time   = avio_rb32(f);
6644             offset = avio_rb32(f);
6645         }
6646
6647         // The first sample of each stream in a fragment is always a random
6648         // access sample.  So it's entry in the tfra can be used as the
6649         // initial PTS of the fragment.
6650         index = update_frag_index(mov, offset);
6651         frag_stream_info = get_frag_stream_info(&mov->frag_index, index, track_id);
6652         if (frag_stream_info &&
6653             frag_stream_info->first_tfra_pts == AV_NOPTS_VALUE)
6654             frag_stream_info->first_tfra_pts = time;
6655
6656         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
6657             avio_r8(f);
6658         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
6659             avio_r8(f);
6660         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
6661             avio_r8(f);
6662     }
6663
6664     avio_seek(f, pos + size, SEEK_SET);
6665     return 0;
6666 }
6667
6668 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
6669 {
6670     int64_t stream_size = avio_size(f);
6671     int64_t original_pos = avio_tell(f);
6672     int64_t seek_ret;
6673     int32_t mfra_size;
6674     int ret = -1;
6675     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
6676         ret = seek_ret;
6677         goto fail;
6678     }
6679     mfra_size = avio_rb32(f);
6680     if (mfra_size < 0 || mfra_size > stream_size) {
6681         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
6682         goto fail;
6683     }
6684     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
6685         ret = seek_ret;
6686         goto fail;
6687     }
6688     if (avio_rb32(f) != mfra_size) {
6689         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
6690         goto fail;
6691     }
6692     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
6693         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
6694         goto fail;
6695     }
6696     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
6697     do {
6698         ret = read_tfra(c, f);
6699         if (ret < 0)
6700             goto fail;
6701     } while (!ret);
6702     ret = 0;
6703 fail:
6704     seek_ret = avio_seek(f, original_pos, SEEK_SET);
6705     if (seek_ret < 0) {
6706         av_log(c->fc, AV_LOG_ERROR,
6707                "failed to seek back after looking for mfra\n");
6708         ret = seek_ret;
6709     }
6710     return ret;
6711 }
6712
6713 static int mov_read_header(AVFormatContext *s)
6714 {
6715     MOVContext *mov = s->priv_data;
6716     AVIOContext *pb = s->pb;
6717     int j, err;
6718     MOVAtom atom = { AV_RL32("root") };
6719     int i;
6720
6721     if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
6722         av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
6723             mov->decryption_key_len, AES_CTR_KEY_SIZE);
6724         return AVERROR(EINVAL);
6725     }
6726
6727     mov->fc = s;
6728     mov->trak_index = -1;
6729     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
6730     if (pb->seekable & AVIO_SEEKABLE_NORMAL)
6731         atom.size = avio_size(pb);
6732     else
6733         atom.size = INT64_MAX;
6734
6735     /* check MOV header */
6736     do {
6737         if (mov->moov_retry)
6738             avio_seek(pb, 0, SEEK_SET);
6739         if ((err = mov_read_default(mov, pb, atom)) < 0) {
6740             av_log(s, AV_LOG_ERROR, "error reading header\n");
6741             mov_read_close(s);
6742             return err;
6743         }
6744     } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
6745     if (!mov->found_moov) {
6746         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
6747         mov_read_close(s);
6748         return AVERROR_INVALIDDATA;
6749     }
6750     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
6751
6752     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
6753         if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
6754             mov_read_chapters(s);
6755         for (i = 0; i < s->nb_streams; i++)
6756             if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
6757                 mov_read_timecode_track(s, s->streams[i]);
6758             } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
6759                 mov_read_rtmd_track(s, s->streams[i]);
6760             }
6761     }
6762
6763     /* copy timecode metadata from tmcd tracks to the related video streams */
6764     for (i = 0; i < s->nb_streams; i++) {
6765         AVStream *st = s->streams[i];
6766         MOVStreamContext *sc = st->priv_data;
6767         if (sc->timecode_track > 0) {
6768             AVDictionaryEntry *tcr;
6769             int tmcd_st_id = -1;
6770
6771             for (j = 0; j < s->nb_streams; j++)
6772                 if (s->streams[j]->id == sc->timecode_track)
6773                     tmcd_st_id = j;
6774
6775             if (tmcd_st_id < 0 || tmcd_st_id == i)
6776                 continue;
6777             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
6778             if (tcr)
6779                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
6780         }
6781     }
6782     export_orphan_timecode(s);
6783
6784     for (i = 0; i < s->nb_streams; i++) {
6785         AVStream *st = s->streams[i];
6786         MOVStreamContext *sc = st->priv_data;
6787         fix_timescale(mov, sc);
6788         if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
6789             st->skip_samples = sc->start_pad;
6790         }
6791         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
6792             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
6793                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
6794         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
6795             if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
6796                 st->codecpar->width  = sc->width;
6797                 st->codecpar->height = sc->height;
6798             }
6799             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
6800                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
6801                     return err;
6802             }
6803         }
6804         if (mov->handbrake_version &&
6805             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
6806             st->codecpar->codec_id == AV_CODEC_ID_MP3
6807         ) {
6808             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
6809             st->need_parsing = AVSTREAM_PARSE_FULL;
6810         }
6811     }
6812
6813     if (mov->trex_data) {
6814         for (i = 0; i < s->nb_streams; i++) {
6815             AVStream *st = s->streams[i];
6816             MOVStreamContext *sc = st->priv_data;
6817             if (st->duration > 0) {
6818                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6819                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6820                            sc->data_size, sc->time_scale);
6821                     mov_read_close(s);
6822                     return AVERROR_INVALIDDATA;
6823                 }
6824                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
6825             }
6826         }
6827     }
6828
6829     if (mov->use_mfra_for > 0) {
6830         for (i = 0; i < s->nb_streams; i++) {
6831             AVStream *st = s->streams[i];
6832             MOVStreamContext *sc = st->priv_data;
6833             if (sc->duration_for_fps > 0) {
6834                 if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
6835                     av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
6836                            sc->data_size, sc->time_scale);
6837                     mov_read_close(s);
6838                     return AVERROR_INVALIDDATA;
6839                 }
6840                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
6841                     sc->duration_for_fps;
6842             }
6843         }
6844     }
6845
6846     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
6847         if (mov->bitrates[i]) {
6848             s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
6849         }
6850     }
6851
6852     ff_rfps_calculate(s);
6853
6854     for (i = 0; i < s->nb_streams; i++) {
6855         AVStream *st = s->streams[i];
6856         MOVStreamContext *sc = st->priv_data;
6857
6858         switch (st->codecpar->codec_type) {
6859         case AVMEDIA_TYPE_AUDIO:
6860             err = ff_replaygain_export(st, s->metadata);
6861             if (err < 0) {
6862                 mov_read_close(s);
6863                 return err;
6864             }
6865             break;
6866         case AVMEDIA_TYPE_VIDEO:
6867             if (sc->display_matrix) {
6868                 err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
6869                                               sizeof(int32_t) * 9);
6870                 if (err < 0)
6871                     return err;
6872
6873                 sc->display_matrix = NULL;
6874             }
6875             if (sc->stereo3d) {
6876                 err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
6877                                               (uint8_t *)sc->stereo3d,
6878                                               sizeof(*sc->stereo3d));
6879                 if (err < 0)
6880                     return err;
6881
6882                 sc->stereo3d = NULL;
6883             }
6884             if (sc->spherical) {
6885                 err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
6886                                               (uint8_t *)sc->spherical,
6887                                               sc->spherical_size);
6888                 if (err < 0)
6889                     return err;
6890
6891                 sc->spherical = NULL;
6892             }
6893             if (sc->mastering) {
6894                 err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
6895                                               (uint8_t *)sc->mastering,
6896                                               sizeof(*sc->mastering));
6897                 if (err < 0)
6898                     return err;
6899
6900                 sc->mastering = NULL;
6901             }
6902             if (sc->coll) {
6903                 err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
6904                                               (uint8_t *)sc->coll,
6905                                               sc->coll_size);
6906                 if (err < 0)
6907                     return err;
6908
6909                 sc->coll = NULL;
6910             }
6911             break;
6912         }
6913     }
6914     ff_configure_buffers_for_index(s, AV_TIME_BASE);
6915
6916     for (i = 0; i < mov->frag_index.nb_items; i++)
6917         if (mov->frag_index.item[i].moof_offset <= mov->fragment.moof_offset)
6918             mov->frag_index.item[i].headers_read = 1;
6919
6920     return 0;
6921 }
6922
6923 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6924 {
6925     AVIndexEntry *sample = NULL;
6926     int64_t best_dts = INT64_MAX;
6927     int i;
6928     for (i = 0; i < s->nb_streams; i++) {
6929         AVStream *avst = s->streams[i];
6930         MOVStreamContext *msc = avst->priv_data;
6931         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
6932             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
6933             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
6934             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
6935             if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
6936                 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
6937                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
6938                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
6939                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
6940                 sample = current_sample;
6941                 best_dts = dts;
6942                 *st = avst;
6943             }
6944         }
6945     }
6946     return sample;
6947 }
6948
6949 static int should_retry(AVIOContext *pb, int error_code) {
6950     if (error_code == AVERROR_EOF || avio_feof(pb))
6951         return 0;
6952
6953     return 1;
6954 }
6955
6956 static int mov_switch_root(AVFormatContext *s, int64_t target, int index)
6957 {
6958     int ret;
6959     MOVContext *mov = s->priv_data;
6960
6961     if (index >= 0 && index < mov->frag_index.nb_items)
6962         target = mov->frag_index.item[index].moof_offset;
6963     if (avio_seek(s->pb, target, SEEK_SET) != target) {
6964         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
6965         return AVERROR_INVALIDDATA;
6966     }
6967
6968     mov->next_root_atom = 0;
6969     if (index < 0 || index >= mov->frag_index.nb_items)
6970         index = search_frag_moof_offset(&mov->frag_index, target);
6971     if (index < mov->frag_index.nb_items) {
6972         if (index + 1 < mov->frag_index.nb_items)
6973             mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
6974         if (mov->frag_index.item[index].headers_read)
6975             return 0;
6976         mov->frag_index.item[index].headers_read = 1;
6977     }
6978
6979     mov->found_mdat = 0;
6980
6981     ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
6982     if (ret < 0)
6983         return ret;
6984     if (avio_feof(s->pb))
6985         return AVERROR_EOF;
6986     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
6987
6988     return 1;
6989 }
6990
6991 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
6992 {
6993     uint8_t *side, *extradata;
6994     int extradata_size;
6995
6996     /* Save the current index. */
6997     sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
6998
6999     /* Notify the decoder that extradata changed. */
7000     extradata_size = sc->extradata_size[sc->last_stsd_index];
7001     extradata = sc->extradata[sc->last_stsd_index];
7002     if (extradata_size > 0 && extradata) {
7003         side = av_packet_new_side_data(pkt,
7004                                        AV_PKT_DATA_NEW_EXTRADATA,
7005                                        extradata_size);
7006         if (!side)
7007             return AVERROR(ENOMEM);
7008         memcpy(side, extradata, extradata_size);
7009     }
7010
7011     return 0;
7012 }
7013
7014 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
7015 {
7016     MOVContext *mov = s->priv_data;
7017     MOVStreamContext *sc;
7018     AVIndexEntry *sample;
7019     AVStream *st = NULL;
7020     int64_t current_index;
7021     int ret;
7022     mov->fc = s;
7023  retry:
7024     sample = mov_find_next_sample(s, &st);
7025     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
7026         if (!mov->next_root_atom)
7027             return AVERROR_EOF;
7028         if ((ret = mov_switch_root(s, mov->next_root_atom, -1)) < 0)
7029             return ret;
7030         goto retry;
7031     }
7032     sc = st->priv_data;
7033     /* must be done just before reading, to avoid infinite loop on sample */
7034     current_index = sc->current_index;
7035     mov_current_sample_inc(sc);
7036
7037     if (mov->next_root_atom) {
7038         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
7039         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
7040     }
7041
7042     if (st->discard != AVDISCARD_ALL) {
7043         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
7044         if (ret64 != sample->pos) {
7045             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
7046                    sc->ffindex, sample->pos);
7047             if (should_retry(sc->pb, ret64)) {
7048                 mov_current_sample_dec(sc);
7049             }
7050             return AVERROR_INVALIDDATA;
7051         }
7052
7053         if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
7054             av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
7055             goto retry;
7056         }
7057
7058         ret = av_get_packet(sc->pb, pkt, sample->size);
7059         if (ret < 0) {
7060             if (should_retry(sc->pb, ret)) {
7061                 mov_current_sample_dec(sc);
7062             }
7063             return ret;
7064         }
7065         if (sc->has_palette) {
7066             uint8_t *pal;
7067
7068             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
7069             if (!pal) {
7070                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
7071             } else {
7072                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
7073                 sc->has_palette = 0;
7074             }
7075         }
7076 #if CONFIG_DV_DEMUXER
7077         if (mov->dv_demux && sc->dv_audio_container) {
7078             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
7079             av_freep(&pkt->data);
7080             pkt->size = 0;
7081             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
7082             if (ret < 0)
7083                 return ret;
7084         }
7085 #endif
7086         if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
7087             if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
7088                 st->need_parsing = AVSTREAM_PARSE_FULL;
7089         }
7090     }
7091
7092     pkt->stream_index = sc->ffindex;
7093     pkt->dts = sample->timestamp;
7094     if (sample->flags & AVINDEX_DISCARD_FRAME) {
7095         pkt->flags |= AV_PKT_FLAG_DISCARD;
7096     }
7097     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
7098         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
7099         /* update ctts context */
7100         sc->ctts_sample++;
7101         if (sc->ctts_index < sc->ctts_count &&
7102             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
7103             sc->ctts_index++;
7104             sc->ctts_sample = 0;
7105         }
7106     } else {
7107         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
7108             st->index_entries[sc->current_sample].timestamp : st->duration;
7109         pkt->duration = next_dts - pkt->dts;
7110         pkt->pts = pkt->dts;
7111     }
7112     if (st->discard == AVDISCARD_ALL)
7113         goto retry;
7114     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
7115     pkt->pos = sample->pos;
7116
7117     /* Multiple stsd handling. */
7118     if (sc->stsc_data) {
7119         /* Keep track of the stsc index for the given sample, then check
7120         * if the stsd index is different from the last used one. */
7121         sc->stsc_sample++;
7122         if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
7123             mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
7124             sc->stsc_index++;
7125             sc->stsc_sample = 0;
7126         /* Do not check indexes after a switch. */
7127         } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
7128                    sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
7129                    sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
7130             ret = mov_change_extradata(sc, pkt);
7131             if (ret < 0)
7132                 return ret;
7133         }
7134     }
7135
7136     if (mov->aax_mode)
7137         aax_filter(pkt->data, pkt->size, mov);
7138
7139     if (sc->cenc.aes_ctr) {
7140         ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
7141         if (ret) {
7142             return ret;
7143         }
7144     }
7145
7146     return 0;
7147 }
7148
7149 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
7150 {
7151     MOVContext *mov = s->priv_data;
7152     int index;
7153
7154     if (!mov->frag_index.complete)
7155         return 0;
7156
7157     index = search_frag_timestamp(&mov->frag_index, st, timestamp);
7158     if (index < 0)
7159         index = 0;
7160     if (!mov->frag_index.item[index].headers_read)
7161         return mov_switch_root(s, -1, index);
7162     if (index + 1 < mov->frag_index.nb_items)
7163         mov->next_root_atom = mov->frag_index.item[index + 1].moof_offset;
7164
7165     return 0;
7166 }
7167
7168 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
7169 {
7170     MOVStreamContext *sc = st->priv_data;
7171     int sample, time_sample, ret;
7172     unsigned int i;
7173
7174     // Here we consider timestamp to be PTS, hence try to offset it so that we
7175     // can search over the DTS timeline.
7176     timestamp -= (sc->min_corrected_pts + sc->dts_shift);
7177
7178     ret = mov_seek_fragment(s, st, timestamp);
7179     if (ret < 0)
7180         return ret;
7181
7182     sample = av_index_search_timestamp(st, timestamp, flags);
7183     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
7184     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
7185         sample = 0;
7186     if (sample < 0) /* not sure what to do */
7187         return AVERROR_INVALIDDATA;
7188     mov_current_sample_set(sc, sample);
7189     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
7190     /* adjust ctts index */
7191     if (sc->ctts_data) {
7192         time_sample = 0;
7193         for (i = 0; i < sc->ctts_count; i++) {
7194             int next = time_sample + sc->ctts_data[i].count;
7195             if (next > sc->current_sample) {
7196                 sc->ctts_index = i;
7197                 sc->ctts_sample = sc->current_sample - time_sample;
7198                 break;
7199             }
7200             time_sample = next;
7201         }
7202     }
7203
7204     /* adjust stsd index */
7205     time_sample = 0;
7206     for (i = 0; i < sc->stsc_count; i++) {
7207         int64_t next = time_sample + mov_get_stsc_samples(sc, i);
7208         if (next > sc->current_sample) {
7209             sc->stsc_index = i;
7210             sc->stsc_sample = sc->current_sample - time_sample;
7211             break;
7212         }
7213         av_assert0(next == (int)next);
7214         time_sample = next;
7215     }
7216
7217     return sample;
7218 }
7219
7220 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
7221 {
7222     MOVContext *mc = s->priv_data;
7223     AVStream *st;
7224     int sample;
7225     int i;
7226
7227     if (stream_index >= s->nb_streams)
7228         return AVERROR_INVALIDDATA;
7229
7230     st = s->streams[stream_index];
7231     sample = mov_seek_stream(s, st, sample_time, flags);
7232     if (sample < 0)
7233         return sample;
7234
7235     if (mc->seek_individually) {
7236         /* adjust seek timestamp to found sample timestamp */
7237         int64_t seek_timestamp = st->index_entries[sample].timestamp;
7238
7239         for (i = 0; i < s->nb_streams; i++) {
7240             int64_t timestamp;
7241             MOVStreamContext *sc = s->streams[i]->priv_data;
7242             st = s->streams[i];
7243             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
7244
7245             if (stream_index == i)
7246                 continue;
7247
7248             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
7249             mov_seek_stream(s, st, timestamp, flags);
7250         }
7251     } else {
7252         for (i = 0; i < s->nb_streams; i++) {
7253             MOVStreamContext *sc;
7254             st = s->streams[i];
7255             sc = st->priv_data;
7256             mov_current_sample_set(sc, 0);
7257         }
7258         while (1) {
7259             MOVStreamContext *sc;
7260             AVIndexEntry *entry = mov_find_next_sample(s, &st);
7261             if (!entry)
7262                 return AVERROR_INVALIDDATA;
7263             sc = st->priv_data;
7264             if (sc->ffindex == stream_index && sc->current_sample == sample)
7265                 break;
7266             mov_current_sample_inc(sc);
7267         }
7268     }
7269     return 0;
7270 }
7271
7272 #define OFFSET(x) offsetof(MOVContext, x)
7273 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
7274 static const AVOption mov_options[] = {
7275     {"use_absolute_path",
7276         "allow using absolute path when opening alias, this is a possible security issue",
7277         OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
7278         0, 1, FLAGS},
7279     {"seek_streams_individually",
7280         "Seek each stream individually to the to the closest point",
7281         OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
7282         0, 1, FLAGS},
7283     {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
7284         0, 1, FLAGS},
7285     {"advanced_editlist",
7286         "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
7287         OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
7288         0, 1, FLAGS},
7289     {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
7290         0, 1, FLAGS},
7291     {"use_mfra_for",
7292         "use mfra for fragment timestamps",
7293         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
7294         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
7295         "use_mfra_for"},
7296     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
7297         FLAGS, "use_mfra_for" },
7298     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
7299         FLAGS, "use_mfra_for" },
7300     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
7301         FLAGS, "use_mfra_for" },
7302     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
7303         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7304     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
7305         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
7306     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
7307         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7308     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
7309         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
7310         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
7311         .flags = AV_OPT_FLAG_DECODING_PARAM },
7312     { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
7313     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
7314         {.i64 = 0}, 0, 1, FLAGS },
7315
7316     { NULL },
7317 };
7318
7319 static const AVClass mov_class = {
7320     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
7321     .item_name  = av_default_item_name,
7322     .option     = mov_options,
7323     .version    = LIBAVUTIL_VERSION_INT,
7324 };
7325
7326 AVInputFormat ff_mov_demuxer = {
7327     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
7328     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
7329     .priv_class     = &mov_class,
7330     .priv_data_size = sizeof(MOVContext),
7331     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
7332     .read_probe     = mov_probe,
7333     .read_header    = mov_read_header,
7334     .read_packet    = mov_read_packet,
7335     .read_close     = mov_read_close,
7336     .read_seek      = mov_read_seek,
7337     .flags          = AVFMT_NO_BYTE_SEEK,
7338 };