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