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