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