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