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