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