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