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