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