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