]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
os_support: Include all the necessary headers for the win32 open function
[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  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <limits.h>
24
25 //#define DEBUG
26 //#define MOV_EXPORT_ALL_METADATA
27
28 #include "libavutil/attributes.h"
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/dict.h"
35 #include "libavcodec/ac3tab.h"
36 #include "avformat.h"
37 #include "internal.h"
38 #include "avio_internal.h"
39 #include "riff.h"
40 #include "isom.h"
41 #include "libavcodec/get_bits.h"
42 #include "id3v1.h"
43 #include "mov_chan.h"
44
45 #if CONFIG_ZLIB
46 #include <zlib.h>
47 #endif
48
49 /*
50  * First version by Francois Revol revol@free.fr
51  * Seek function by Gael Chardon gael.dev@4now.net
52  */
53
54 #include "qtpalette.h"
55
56
57 #undef NDEBUG
58 #include <assert.h>
59
60 /* those functions parse an atom */
61 /* links atom IDs to parse functions */
62 typedef struct MOVParseTableEntry {
63     uint32_t type;
64     int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
65 } MOVParseTableEntry;
66
67 static const MOVParseTableEntry mov_default_parse_table[];
68
69 static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
70                                              unsigned len, const char *key)
71 {
72     char buf[16];
73
74     short current, total = 0;
75     avio_rb16(pb); // unknown
76     current = avio_rb16(pb);
77     if (len >= 6)
78         total = avio_rb16(pb);
79     if (!total)
80         snprintf(buf, sizeof(buf), "%d", current);
81     else
82         snprintf(buf, sizeof(buf), "%d/%d", current, total);
83     av_dict_set(&c->fc->metadata, key, buf, 0);
84
85     return 0;
86 }
87
88 static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
89                                             unsigned len, const char *key)
90 {
91     char buf[16];
92
93     /* bypass padding bytes */
94     avio_r8(pb);
95     avio_r8(pb);
96     avio_r8(pb);
97
98     snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
99     av_dict_set(&c->fc->metadata, key, buf, 0);
100
101     return 0;
102 }
103
104 static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
105                                         unsigned len, const char *key)
106 {
107     char buf[16];
108
109     snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
110     av_dict_set(&c->fc->metadata, key, buf, 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     char buf[20];
120
121     avio_r8(pb); // unknown
122
123     genre = avio_r8(pb);
124     if (genre < 1 || genre > ID3v1_GENRE_MAX)
125         return 0;
126     snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
127     av_dict_set(&c->fc->metadata, key, buf, 0);
128
129     return 0;
130 }
131
132 static const uint32_t mac_to_unicode[128] = {
133     0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
134     0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
135     0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
136     0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
137     0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
138     0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
139     0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
140     0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
141     0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
142     0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
143     0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
144     0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
145     0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
146     0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
147     0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
148     0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
149 };
150
151 static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
152                                char *dst, int dstlen)
153 {
154     char *p = dst;
155     char *end = dst+dstlen-1;
156     int i;
157
158     for (i = 0; i < len; i++) {
159         uint8_t t, c = avio_r8(pb);
160         if (c < 0x80 && p < end)
161             *p++ = c;
162         else
163             PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
164     }
165     *p = 0;
166     return p - dst;
167 }
168
169 static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
170 {
171 #ifdef MOV_EXPORT_ALL_METADATA
172     char tmp_key[5];
173 #endif
174     char str[1024], key2[16], language[4] = {0};
175     const char *key = NULL;
176     uint16_t langcode = 0;
177     uint32_t data_type = 0, str_size;
178     int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
179
180     switch (atom.type) {
181     case MKTAG(0xa9,'n','a','m'): key = "title";     break;
182     case MKTAG(0xa9,'a','u','t'):
183     case MKTAG(0xa9,'A','R','T'): key = "artist";    break;
184     case MKTAG( 'a','A','R','T'): key = "album_artist";    break;
185     case MKTAG(0xa9,'w','r','t'): key = "composer";  break;
186     case MKTAG( 'c','p','r','t'):
187     case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
188     case MKTAG(0xa9,'c','m','t'):
189     case MKTAG(0xa9,'i','n','f'): key = "comment";   break;
190     case MKTAG(0xa9,'a','l','b'): key = "album";     break;
191     case MKTAG(0xa9,'d','a','y'): key = "date";      break;
192     case MKTAG(0xa9,'g','e','n'): key = "genre";     break;
193     case MKTAG( 'g','n','r','e'): key = "genre";
194         parse = mov_metadata_gnre; break;
195     case MKTAG(0xa9,'t','o','o'):
196     case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;
197     case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;
198     case MKTAG( 'd','e','s','c'): key = "description";break;
199     case MKTAG( 'l','d','e','s'): key = "synopsis";  break;
200     case MKTAG( 't','v','s','h'): key = "show";      break;
201     case MKTAG( 't','v','e','n'): key = "episode_id";break;
202     case MKTAG( 't','v','n','n'): key = "network";   break;
203     case MKTAG( 't','r','k','n'): key = "track";
204         parse = mov_metadata_track_or_disc_number; break;
205     case MKTAG( 'd','i','s','k'): key = "disc";
206         parse = mov_metadata_track_or_disc_number; break;
207     case MKTAG( 't','v','e','s'): key = "episode_sort";
208         parse = mov_metadata_int8_bypass_padding; break;
209     case MKTAG( 't','v','s','n'): key = "season_number";
210         parse = mov_metadata_int8_bypass_padding; break;
211     case MKTAG( 's','t','i','k'): key = "media_type";
212         parse = mov_metadata_int8_no_padding; break;
213     case MKTAG( 'h','d','v','d'): key = "hd_video";
214         parse = mov_metadata_int8_no_padding; break;
215     case MKTAG( 'p','g','a','p'): key = "gapless_playback";
216         parse = mov_metadata_int8_no_padding; break;
217     }
218
219     if (c->itunes_metadata && atom.size > 8) {
220         int data_size = avio_rb32(pb);
221         int tag = avio_rl32(pb);
222         if (tag == MKTAG('d','a','t','a')) {
223             data_type = avio_rb32(pb); // type
224             avio_rb32(pb); // unknown
225             str_size = data_size - 16;
226             atom.size -= 16;
227         } else return 0;
228     } else if (atom.size > 4 && key && !c->itunes_metadata) {
229         str_size = avio_rb16(pb); // string length
230         langcode = avio_rb16(pb);
231         ff_mov_lang_to_iso639(langcode, language);
232         atom.size -= 4;
233     } else
234         str_size = atom.size;
235
236 #ifdef MOV_EXPORT_ALL_METADATA
237     if (!key) {
238         snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
239         key = tmp_key;
240     }
241 #endif
242
243     if (!key)
244         return 0;
245     if (atom.size < 0)
246         return AVERROR_INVALIDDATA;
247
248     str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
249
250     if (parse)
251         parse(c, pb, str_size, key);
252     else {
253         if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
254             mov_read_mac_string(c, pb, str_size, str, sizeof(str));
255         } else {
256             avio_read(pb, str, str_size);
257             str[str_size] = 0;
258         }
259         av_dict_set(&c->fc->metadata, key, str, 0);
260         if (*language && strcmp(language, "und")) {
261             snprintf(key2, sizeof(key2), "%s-%s", key, language);
262             av_dict_set(&c->fc->metadata, key2, str, 0);
263         }
264     }
265     av_dlog(c->fc, "lang \"%3s\" ", language);
266     av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
267             key, str, (char*)&atom.type, str_size, atom.size);
268
269     return 0;
270 }
271
272 static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
273 {
274     int64_t start;
275     int i, nb_chapters, str_len, version;
276     char str[256+1];
277
278     if ((atom.size -= 5) < 0)
279         return 0;
280
281     version = avio_r8(pb);
282     avio_rb24(pb);
283     if (version)
284         avio_rb32(pb); // ???
285     nb_chapters = avio_r8(pb);
286
287     for (i = 0; i < nb_chapters; i++) {
288         if (atom.size < 9)
289             return 0;
290
291         start = avio_rb64(pb);
292         str_len = avio_r8(pb);
293
294         if ((atom.size -= 9+str_len) < 0)
295             return 0;
296
297         avio_read(pb, str, str_len);
298         str[str_len] = 0;
299         avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
300     }
301     return 0;
302 }
303
304 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
305 {
306     int64_t total_size = 0;
307     MOVAtom a;
308     int i;
309
310     if (atom.size < 0)
311         atom.size = INT64_MAX;
312     while (total_size + 8 < atom.size && !pb->eof_reached) {
313         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
314         a.size = atom.size;
315         a.type=0;
316         if (atom.size >= 8) {
317             a.size = avio_rb32(pb);
318             a.type = avio_rl32(pb);
319         }
320         av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
321                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
322         total_size += 8;
323         if (a.size == 1) { /* 64 bit extended size */
324             a.size = avio_rb64(pb) - 8;
325             total_size += 8;
326         }
327         if (a.size == 0) {
328             a.size = atom.size - total_size;
329             if (a.size <= 8)
330                 break;
331         }
332         a.size -= 8;
333         if (a.size < 0)
334             break;
335         a.size = FFMIN(a.size, atom.size - total_size);
336
337         for (i = 0; mov_default_parse_table[i].type; i++)
338             if (mov_default_parse_table[i].type == a.type) {
339                 parse = mov_default_parse_table[i].parse;
340                 break;
341             }
342
343         // container is user data
344         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
345                        atom.type == MKTAG('i','l','s','t')))
346             parse = mov_read_udta_string;
347
348         if (!parse) { /* skip leaf atoms data */
349             avio_skip(pb, a.size);
350         } else {
351             int64_t start_pos = avio_tell(pb);
352             int64_t left;
353             int err = parse(c, pb, a);
354             if (err < 0)
355                 return err;
356             if (c->found_moov && c->found_mdat &&
357                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
358                  start_pos + a.size == avio_size(pb))) {
359                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
360                     c->next_root_atom = start_pos + a.size;
361                 return 0;
362             }
363             left = a.size - avio_tell(pb) + start_pos;
364             if (left > 0) /* skip garbage at atom end */
365                 avio_skip(pb, left);
366         }
367
368         total_size += a.size;
369     }
370
371     if (total_size < atom.size && atom.size < 0x7ffff)
372         avio_skip(pb, atom.size - total_size);
373
374     return 0;
375 }
376
377 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
378 {
379     AVStream *st;
380     MOVStreamContext *sc;
381     int entries, i, j;
382
383     if (c->fc->nb_streams < 1)
384         return 0;
385     st = c->fc->streams[c->fc->nb_streams-1];
386     sc = st->priv_data;
387
388     avio_rb32(pb); // version + flags
389     entries = avio_rb32(pb);
390     if (entries >= UINT_MAX / sizeof(*sc->drefs))
391         return AVERROR_INVALIDDATA;
392     av_free(sc->drefs);
393     sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
394     if (!sc->drefs)
395         return AVERROR(ENOMEM);
396     sc->drefs_count = entries;
397
398     for (i = 0; i < sc->drefs_count; i++) {
399         MOVDref *dref = &sc->drefs[i];
400         uint32_t size = avio_rb32(pb);
401         int64_t next = avio_tell(pb) + size - 4;
402
403         if (size < 12)
404             return AVERROR_INVALIDDATA;
405
406         dref->type = avio_rl32(pb);
407         avio_rb32(pb); // version + flags
408         av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
409
410         if (dref->type == MKTAG('a','l','i','s') && size > 150) {
411             /* macintosh alias record */
412             uint16_t volume_len, len;
413             int16_t type;
414
415             avio_skip(pb, 10);
416
417             volume_len = avio_r8(pb);
418             volume_len = FFMIN(volume_len, 27);
419             avio_read(pb, dref->volume, 27);
420             dref->volume[volume_len] = 0;
421             av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
422
423             avio_skip(pb, 12);
424
425             len = avio_r8(pb);
426             len = FFMIN(len, 63);
427             avio_read(pb, dref->filename, 63);
428             dref->filename[len] = 0;
429             av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
430
431             avio_skip(pb, 16);
432
433             /* read next level up_from_alias/down_to_target */
434             dref->nlvl_from = avio_rb16(pb);
435             dref->nlvl_to   = avio_rb16(pb);
436             av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
437                    dref->nlvl_from, dref->nlvl_to);
438
439             avio_skip(pb, 16);
440
441             for (type = 0; type != -1 && avio_tell(pb) < next; ) {
442                 type = avio_rb16(pb);
443                 len = avio_rb16(pb);
444                 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
445                 if (len&1)
446                     len += 1;
447                 if (type == 2) { // absolute path
448                     av_free(dref->path);
449                     dref->path = av_mallocz(len+1);
450                     if (!dref->path)
451                         return AVERROR(ENOMEM);
452                     avio_read(pb, dref->path, len);
453                     if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
454                         len -= volume_len;
455                         memmove(dref->path, dref->path+volume_len, len);
456                         dref->path[len] = 0;
457                     }
458                     for (j = 0; j < len; j++)
459                         if (dref->path[j] == ':')
460                             dref->path[j] = '/';
461                     av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
462                 } else if (type == 0) { // directory name
463                     av_free(dref->dir);
464                     dref->dir = av_malloc(len+1);
465                     if (!dref->dir)
466                         return AVERROR(ENOMEM);
467                     avio_read(pb, dref->dir, len);
468                     dref->dir[len] = 0;
469                     for (j = 0; j < len; j++)
470                         if (dref->dir[j] == ':')
471                             dref->dir[j] = '/';
472                     av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
473                 } else
474                     avio_skip(pb, len);
475             }
476         }
477         avio_seek(pb, next, SEEK_SET);
478     }
479     return 0;
480 }
481
482 static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
483 {
484     AVStream *st;
485     uint32_t type;
486     uint32_t av_unused ctype;
487
488     if (c->fc->nb_streams < 1) // meta before first trak
489         return 0;
490
491     st = c->fc->streams[c->fc->nb_streams-1];
492
493     avio_r8(pb); /* version */
494     avio_rb24(pb); /* flags */
495
496     /* component type */
497     ctype = avio_rl32(pb);
498     type = avio_rl32(pb); /* component subtype */
499
500     av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
501     av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
502
503     if     (type == MKTAG('v','i','d','e'))
504         st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
505     else if (type == MKTAG('s','o','u','n'))
506         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
507     else if (type == MKTAG('m','1','a',' '))
508         st->codec->codec_id = CODEC_ID_MP2;
509     else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
510         st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
511
512     avio_rb32(pb); /* component  manufacture */
513     avio_rb32(pb); /* component flags */
514     avio_rb32(pb); /* component flags mask */
515
516     return 0;
517 }
518
519 int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
520 {
521     AVStream *st;
522     int tag;
523
524     if (fc->nb_streams < 1)
525         return 0;
526     st = fc->streams[fc->nb_streams-1];
527
528     avio_rb32(pb); /* version + flags */
529     ff_mp4_read_descr(fc, pb, &tag);
530     if (tag == MP4ESDescrTag) {
531         ff_mp4_parse_es_descr(pb, NULL);
532     } else
533         avio_rb16(pb); /* ID */
534
535     ff_mp4_read_descr(fc, pb, &tag);
536     if (tag == MP4DecConfigDescrTag)
537         ff_mp4_read_dec_config_descr(fc, st, pb);
538     return 0;
539 }
540
541 static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
542 {
543     return ff_mov_read_esds(c->fc, pb, atom);
544 }
545
546 static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
547 {
548     AVStream *st;
549     int ac3info, acmod, lfeon, bsmod;
550
551     if (c->fc->nb_streams < 1)
552         return 0;
553     st = c->fc->streams[c->fc->nb_streams-1];
554
555     ac3info = avio_rb24(pb);
556     bsmod = (ac3info >> 14) & 0x7;
557     acmod = (ac3info >> 11) & 0x7;
558     lfeon = (ac3info >> 10) & 0x1;
559     st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
560     st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
561     if (lfeon)
562         st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
563     st->codec->audio_service_type = bsmod;
564     if (st->codec->channels > 1 && bsmod == 0x7)
565         st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
566
567     return 0;
568 }
569
570 static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
571 {
572     AVStream *st;
573     int eac3info, acmod, lfeon, bsmod;
574
575     if (c->fc->nb_streams < 1)
576         return 0;
577     st = c->fc->streams[c->fc->nb_streams-1];
578
579     /* No need to parse fields for additional independent substreams and its
580      * associated dependent substreams since libavcodec's E-AC-3 decoder
581      * does not support them yet. */
582     avio_rb16(pb); /* data_rate and num_ind_sub */
583     eac3info = avio_rb24(pb);
584     bsmod = (eac3info >> 12) & 0x1f;
585     acmod = (eac3info >>  9) & 0x7;
586     lfeon = (eac3info >>  8) & 0x1;
587     st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
588     if (lfeon)
589         st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
590     st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
591     st->codec->audio_service_type = bsmod;
592     if (st->codec->channels > 1 && bsmod == 0x7)
593         st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
594
595     return 0;
596 }
597
598 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
599 {
600     AVStream *st;
601     uint8_t av_unused version;
602     uint32_t av_unused flags;
603     uint32_t layout_tag, bitmap, num_descr, label_mask;
604     int i;
605
606     if (c->fc->nb_streams < 1)
607         return 0;
608     st = c->fc->streams[c->fc->nb_streams-1];
609
610     if (atom.size < 16)
611         return 0;
612
613     version = avio_r8(pb);
614     flags   = avio_rb24(pb);
615
616     layout_tag = avio_rb32(pb);
617     bitmap     = avio_rb32(pb);
618     num_descr  = avio_rb32(pb);
619
620     if (atom.size < 16ULL + num_descr * 20ULL)
621         return 0;
622
623     av_dlog(c->fc, "chan: size=%ld version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
624             atom.size, version, flags, layout_tag, bitmap, num_descr);
625
626     label_mask = 0;
627     for (i = 0; i < num_descr; i++) {
628         uint32_t label;
629         label     = avio_rb32(pb);          // mChannelLabel
630         avio_rb32(pb);                      // mChannelFlags
631         avio_rl32(pb);                      // mCoordinates[0]
632         avio_rl32(pb);                      // mCoordinates[1]
633         avio_rl32(pb);                      // mCoordinates[2]
634         if (layout_tag == 0) {
635             uint32_t mask_incr = ff_mov_get_channel_label(label);
636             if (mask_incr == 0) {
637                 label_mask = 0;
638                 break;
639             }
640             label_mask |= mask_incr;
641         }
642     }
643     if (layout_tag == 0)
644         st->codec->channel_layout = label_mask;
645     else
646         st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
647
648     return 0;
649 }
650
651 static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
652 {
653     AVStream *st;
654
655     if (c->fc->nb_streams < 1)
656         return 0;
657     st = c->fc->streams[c->fc->nb_streams-1];
658
659     ff_get_wav_header(pb, st->codec, atom.size);
660
661     return 0;
662 }
663
664 static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
665 {
666     const int num = avio_rb32(pb);
667     const int den = avio_rb32(pb);
668     AVStream *st;
669
670     if (c->fc->nb_streams < 1)
671         return 0;
672     st = c->fc->streams[c->fc->nb_streams-1];
673
674     if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
675         (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
676         av_log(c->fc, AV_LOG_WARNING,
677                "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
678                st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
679                num, den);
680     } else if (den != 0) {
681         st->sample_aspect_ratio.num = num;
682         st->sample_aspect_ratio.den = den;
683     }
684     return 0;
685 }
686
687 /* this atom contains actual media data */
688 static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
689 {
690     if (atom.size == 0) /* wrong one (MP4) */
691         return 0;
692     c->found_mdat=1;
693     return 0; /* now go for moov */
694 }
695
696 /* read major brand, minor version and compatible brands and store them as metadata */
697 static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
698 {
699     uint32_t minor_ver;
700     int comp_brand_size;
701     char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
702     char* comp_brands_str;
703     uint8_t type[5] = {0};
704
705     avio_read(pb, type, 4);
706     if (strcmp(type, "qt  "))
707         c->isom = 1;
708     av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
709     av_dict_set(&c->fc->metadata, "major_brand", type, 0);
710     minor_ver = avio_rb32(pb); /* minor version */
711     snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
712     av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
713
714     comp_brand_size = atom.size - 8;
715     if (comp_brand_size < 0)
716         return AVERROR_INVALIDDATA;
717     comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
718     if (!comp_brands_str)
719         return AVERROR(ENOMEM);
720     avio_read(pb, comp_brands_str, comp_brand_size);
721     comp_brands_str[comp_brand_size] = 0;
722     av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
723     av_freep(&comp_brands_str);
724
725     return 0;
726 }
727
728 /* this atom should contain all header atoms */
729 static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
730 {
731     int ret;
732
733     if ((ret = mov_read_default(c, pb, atom)) < 0)
734         return ret;
735     /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
736     /* so we don't parse the whole file if over a network */
737     c->found_moov=1;
738     return 0; /* now go for mdat */
739 }
740
741 static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
742 {
743     c->fragment.moof_offset = avio_tell(pb) - 8;
744     av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
745     return mov_read_default(c, pb, atom);
746 }
747
748 static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
749 {
750     char buffer[32];
751     if (time) {
752         struct tm *ptm;
753         time -= 2082844800;  /* seconds between 1904-01-01 and Epoch */
754         ptm = gmtime(&time);
755         if (!ptm) return;
756         strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
757         av_dict_set(metadata, "creation_time", buffer, 0);
758     }
759 }
760
761 static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
762 {
763     AVStream *st;
764     MOVStreamContext *sc;
765     int version;
766     char language[4] = {0};
767     unsigned lang;
768     time_t creation_time;
769
770     if (c->fc->nb_streams < 1)
771         return 0;
772     st = c->fc->streams[c->fc->nb_streams-1];
773     sc = st->priv_data;
774
775     version = avio_r8(pb);
776     if (version > 1) {
777         av_log_ask_for_sample(c, "unsupported version %d\n", version);
778         return AVERROR_PATCHWELCOME;
779     }
780     avio_rb24(pb); /* flags */
781     if (version == 1) {
782         creation_time = avio_rb64(pb);
783         avio_rb64(pb);
784     } else {
785         creation_time = avio_rb32(pb);
786         avio_rb32(pb); /* modification time */
787     }
788     mov_metadata_creation_time(&st->metadata, creation_time);
789
790     sc->time_scale = avio_rb32(pb);
791     st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
792
793     lang = avio_rb16(pb); /* language */
794     if (ff_mov_lang_to_iso639(lang, language))
795         av_dict_set(&st->metadata, "language", language, 0);
796     avio_rb16(pb); /* quality */
797
798     return 0;
799 }
800
801 static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
802 {
803     time_t creation_time;
804     int version = avio_r8(pb); /* version */
805     avio_rb24(pb); /* flags */
806
807     if (version == 1) {
808         creation_time = avio_rb64(pb);
809         avio_rb64(pb);
810     } else {
811         creation_time = avio_rb32(pb);
812         avio_rb32(pb); /* modification time */
813     }
814     mov_metadata_creation_time(&c->fc->metadata, creation_time);
815     c->time_scale = avio_rb32(pb); /* time scale */
816
817     av_dlog(c->fc, "time scale = %i\n", c->time_scale);
818
819     c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
820     avio_rb32(pb); /* preferred scale */
821
822     avio_rb16(pb); /* preferred volume */
823
824     avio_skip(pb, 10); /* reserved */
825
826     avio_skip(pb, 36); /* display matrix */
827
828     avio_rb32(pb); /* preview time */
829     avio_rb32(pb); /* preview duration */
830     avio_rb32(pb); /* poster time */
831     avio_rb32(pb); /* selection time */
832     avio_rb32(pb); /* selection duration */
833     avio_rb32(pb); /* current time */
834     avio_rb32(pb); /* next track ID */
835
836     return 0;
837 }
838
839 static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
840 {
841     AVStream *st;
842
843     if (c->fc->nb_streams < 1)
844         return 0;
845     st = c->fc->streams[c->fc->nb_streams-1];
846
847     if ((uint64_t)atom.size > (1<<30))
848         return AVERROR_INVALIDDATA;
849
850     // currently SVQ3 decoder expect full STSD header - so let's fake it
851     // this should be fixed and just SMI header should be passed
852     av_free(st->codec->extradata);
853     st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
854     if (!st->codec->extradata)
855         return AVERROR(ENOMEM);
856     st->codec->extradata_size = 0x5a + atom.size;
857     memcpy(st->codec->extradata, "SVQ3", 4); // fake
858     avio_read(pb, st->codec->extradata + 0x5a, atom.size);
859     av_dlog(c->fc, "Reading SMI %"PRId64"  %s\n", atom.size, st->codec->extradata + 0x5a);
860     return 0;
861 }
862
863 static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
864 {
865     AVStream *st;
866     int little_endian;
867
868     if (c->fc->nb_streams < 1)
869         return 0;
870     st = c->fc->streams[c->fc->nb_streams-1];
871
872     little_endian = avio_rb16(pb);
873     av_dlog(c->fc, "enda %d\n", little_endian);
874     if (little_endian == 1) {
875         switch (st->codec->codec_id) {
876         case CODEC_ID_PCM_S24BE:
877             st->codec->codec_id = CODEC_ID_PCM_S24LE;
878             break;
879         case CODEC_ID_PCM_S32BE:
880             st->codec->codec_id = CODEC_ID_PCM_S32LE;
881             break;
882         case CODEC_ID_PCM_F32BE:
883             st->codec->codec_id = CODEC_ID_PCM_F32LE;
884             break;
885         case CODEC_ID_PCM_F64BE:
886             st->codec->codec_id = CODEC_ID_PCM_F64LE;
887             break;
888         default:
889             break;
890         }
891     }
892     return 0;
893 }
894
895 static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
896 {
897     AVStream *st;
898     unsigned mov_field_order;
899     enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
900
901     if (c->fc->nb_streams < 1) // will happen with jp2 files
902         return 0;
903     st = c->fc->streams[c->fc->nb_streams-1];
904     if (atom.size < 2)
905         return AVERROR_INVALIDDATA;
906     mov_field_order = avio_rb16(pb);
907     if ((mov_field_order & 0xFF00) == 0x0100)
908         decoded_field_order = AV_FIELD_PROGRESSIVE;
909     else if ((mov_field_order & 0xFF00) == 0x0200) {
910         switch (mov_field_order & 0xFF) {
911         case 0x01: decoded_field_order = AV_FIELD_TT;
912                    break;
913         case 0x06: decoded_field_order = AV_FIELD_BB;
914                    break;
915         case 0x09: decoded_field_order = AV_FIELD_TB;
916                    break;
917         case 0x0E: decoded_field_order = AV_FIELD_BT;
918                    break;
919         }
920     }
921     if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
922         av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
923     }
924     st->codec->field_order = decoded_field_order;
925
926     return 0;
927 }
928
929 /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
930 static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
931 {
932     AVStream *st;
933     uint64_t size;
934     uint8_t *buf;
935
936     if (c->fc->nb_streams < 1) // will happen with jp2 files
937         return 0;
938     st= c->fc->streams[c->fc->nb_streams-1];
939     size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
940     if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
941         return AVERROR_INVALIDDATA;
942     buf= av_realloc(st->codec->extradata, size);
943     if (!buf)
944         return AVERROR(ENOMEM);
945     st->codec->extradata= buf;
946     buf+= st->codec->extradata_size;
947     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
948     AV_WB32(       buf    , atom.size + 8);
949     AV_WL32(       buf + 4, atom.type);
950     avio_read(pb, buf + 8, atom.size);
951     return 0;
952 }
953
954 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
955 {
956     AVStream *st;
957
958     if (c->fc->nb_streams < 1)
959         return 0;
960     st = c->fc->streams[c->fc->nb_streams-1];
961
962     if ((uint64_t)atom.size > (1<<30))
963         return AVERROR_INVALIDDATA;
964
965     if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
966         // pass all frma atom to codec, needed at least for QDMC and QDM2
967         av_free(st->codec->extradata);
968         st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
969         if (!st->codec->extradata)
970             return AVERROR(ENOMEM);
971         st->codec->extradata_size = atom.size;
972         avio_read(pb, st->codec->extradata, atom.size);
973     } else if (atom.size > 8) { /* to read frma, esds atoms */
974         int ret;
975         if ((ret = mov_read_default(c, pb, atom)) < 0)
976             return ret;
977     } else
978         avio_skip(pb, atom.size);
979     return 0;
980 }
981
982 /**
983  * This function reads atom content and puts data in extradata without tag
984  * nor size unlike mov_read_extradata.
985  */
986 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
987 {
988     AVStream *st;
989
990     if (c->fc->nb_streams < 1)
991         return 0;
992     st = c->fc->streams[c->fc->nb_streams-1];
993
994     if ((uint64_t)atom.size > (1<<30))
995         return AVERROR_INVALIDDATA;
996
997     if (atom.size >= 10) {
998         // Broken files created by legacy versions of libavformat will
999         // wrap a whole fiel atom inside of a glbl atom.
1000         unsigned size = avio_rb32(pb);
1001         unsigned type = avio_rl32(pb);
1002         avio_seek(pb, -8, SEEK_CUR);
1003         if (type == MKTAG('f','i','e','l') && size == atom.size)
1004             return mov_read_default(c, pb, atom);
1005     }
1006     av_free(st->codec->extradata);
1007     st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
1008     if (!st->codec->extradata)
1009         return AVERROR(ENOMEM);
1010     st->codec->extradata_size = atom.size;
1011     avio_read(pb, st->codec->extradata, atom.size);
1012     return 0;
1013 }
1014
1015 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1016 {
1017     AVStream *st;
1018     uint8_t profile_level;
1019
1020     if (c->fc->nb_streams < 1)
1021         return 0;
1022     st = c->fc->streams[c->fc->nb_streams-1];
1023
1024     if (atom.size >= (1<<28) || atom.size < 7)
1025         return AVERROR_INVALIDDATA;
1026
1027     profile_level = avio_r8(pb);
1028     if ((profile_level & 0xf0) != 0xc0)
1029         return 0;
1030
1031     av_free(st->codec->extradata);
1032     st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
1033     if (!st->codec->extradata)
1034         return AVERROR(ENOMEM);
1035     st->codec->extradata_size = atom.size - 7;
1036     avio_seek(pb, 6, SEEK_CUR);
1037     avio_read(pb, st->codec->extradata, st->codec->extradata_size);
1038     return 0;
1039 }
1040
1041 /**
1042  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1043  * but can have extradata appended at the end after the 40 bytes belonging
1044  * to the struct.
1045  */
1046 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1047 {
1048     AVStream *st;
1049
1050     if (c->fc->nb_streams < 1)
1051         return 0;
1052     if (atom.size <= 40)
1053         return 0;
1054     st = c->fc->streams[c->fc->nb_streams-1];
1055
1056     if ((uint64_t)atom.size > (1<<30))
1057         return AVERROR_INVALIDDATA;
1058
1059     av_free(st->codec->extradata);
1060     st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
1061     if (!st->codec->extradata)
1062         return AVERROR(ENOMEM);
1063     st->codec->extradata_size = atom.size - 40;
1064     avio_skip(pb, 40);
1065     avio_read(pb, st->codec->extradata, atom.size - 40);
1066     return 0;
1067 }
1068
1069 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1070 {
1071     AVStream *st;
1072     MOVStreamContext *sc;
1073     unsigned int i, entries;
1074
1075     if (c->fc->nb_streams < 1)
1076         return 0;
1077     st = c->fc->streams[c->fc->nb_streams-1];
1078     sc = st->priv_data;
1079
1080     avio_r8(pb); /* version */
1081     avio_rb24(pb); /* flags */
1082
1083     entries = avio_rb32(pb);
1084
1085     if (!entries)
1086         return 0;
1087     if (entries >= UINT_MAX/sizeof(int64_t))
1088         return AVERROR_INVALIDDATA;
1089
1090     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
1091     if (!sc->chunk_offsets)
1092         return AVERROR(ENOMEM);
1093     sc->chunk_count = entries;
1094
1095     if      (atom.type == MKTAG('s','t','c','o'))
1096         for (i=0; i<entries; i++)
1097             sc->chunk_offsets[i] = avio_rb32(pb);
1098     else if (atom.type == MKTAG('c','o','6','4'))
1099         for (i=0; i<entries; i++)
1100             sc->chunk_offsets[i] = avio_rb64(pb);
1101     else
1102         return AVERROR_INVALIDDATA;
1103
1104     return 0;
1105 }
1106
1107 /**
1108  * Compute codec id for 'lpcm' tag.
1109  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1110  */
1111 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1112 {
1113     if (flags & 1) { // floating point
1114         if (flags & 2) { // big endian
1115             if      (bps == 32) return CODEC_ID_PCM_F32BE;
1116             else if (bps == 64) return CODEC_ID_PCM_F64BE;
1117         } else {
1118             if      (bps == 32) return CODEC_ID_PCM_F32LE;
1119             else if (bps == 64) return CODEC_ID_PCM_F64LE;
1120         }
1121     } else {
1122         if (flags & 2) {
1123             if      (bps == 8)
1124                 // signed integer
1125                 if (flags & 4)  return CODEC_ID_PCM_S8;
1126                 else            return CODEC_ID_PCM_U8;
1127             else if (bps == 16) return CODEC_ID_PCM_S16BE;
1128             else if (bps == 24) return CODEC_ID_PCM_S24BE;
1129             else if (bps == 32) return CODEC_ID_PCM_S32BE;
1130         } else {
1131             if      (bps == 8)
1132                 if (flags & 4)  return CODEC_ID_PCM_S8;
1133                 else            return CODEC_ID_PCM_U8;
1134             else if (bps == 16) return CODEC_ID_PCM_S16LE;
1135             else if (bps == 24) return CODEC_ID_PCM_S24LE;
1136             else if (bps == 32) return CODEC_ID_PCM_S32LE;
1137         }
1138     }
1139     return CODEC_ID_NONE;
1140 }
1141
1142 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1143 {
1144     AVStream *st;
1145     MOVStreamContext *sc;
1146     int j, pseudo_stream_id;
1147
1148     if (c->fc->nb_streams < 1)
1149         return 0;
1150     st = c->fc->streams[c->fc->nb_streams-1];
1151     sc = st->priv_data;
1152
1153     for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
1154         //Parsing Sample description table
1155         enum CodecID id;
1156         int dref_id = 1;
1157         MOVAtom a = { AV_RL32("stsd") };
1158         int64_t start_pos = avio_tell(pb);
1159         int size = avio_rb32(pb); /* size */
1160         uint32_t format = avio_rl32(pb); /* data format */
1161
1162         if (size >= 16) {
1163             avio_rb32(pb); /* reserved */
1164             avio_rb16(pb); /* reserved */
1165             dref_id = avio_rb16(pb);
1166         }
1167
1168         if (st->codec->codec_tag &&
1169             st->codec->codec_tag != format &&
1170             (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1171                                    : st->codec->codec_tag != MKTAG('j','p','e','g'))
1172            ){
1173             /* Multiple fourcc, we skip JPEG. This is not correct, we should
1174              * export it as a separate AVStream but this needs a few changes
1175              * in the MOV demuxer, patch welcome. */
1176         multiple_stsd:
1177             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1178             avio_skip(pb, size - (avio_tell(pb) - start_pos));
1179             continue;
1180         }
1181         /* we cannot demux concatenated h264 streams because of different extradata */
1182         if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1183             goto multiple_stsd;
1184         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1185         sc->dref_id= dref_id;
1186
1187         st->codec->codec_tag = format;
1188         id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1189         if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1190             id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1191
1192         if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1193             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1194         } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1195                    format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1196             id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1197             if (id <= 0)
1198                 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1199             if (id > 0)
1200                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1201             else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
1202                 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1203                 if (id > 0)
1204                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1205             }
1206         }
1207
1208         av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1209                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1210                 (format >> 24) & 0xff, st->codec->codec_type);
1211
1212         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1213             unsigned int color_depth, len;
1214             int color_greyscale;
1215             int color_table_id;
1216
1217             st->codec->codec_id = id;
1218             avio_rb16(pb); /* version */
1219             avio_rb16(pb); /* revision level */
1220             avio_rb32(pb); /* vendor */
1221             avio_rb32(pb); /* temporal quality */
1222             avio_rb32(pb); /* spatial quality */
1223
1224             st->codec->width = avio_rb16(pb); /* width */
1225             st->codec->height = avio_rb16(pb); /* height */
1226
1227             avio_rb32(pb); /* horiz resolution */
1228             avio_rb32(pb); /* vert resolution */
1229             avio_rb32(pb); /* data size, always 0 */
1230             avio_rb16(pb); /* frames per samples */
1231
1232             len = avio_r8(pb); /* codec name, pascal string */
1233             if (len > 31)
1234                 len = 31;
1235             mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1236             if (len < 31)
1237                 avio_skip(pb, 31 - len);
1238             /* codec_tag YV12 triggers an UV swap in rawdec.c */
1239             if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1240                 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1241
1242             st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1243             color_table_id = avio_rb16(pb); /* colortable id */
1244             av_dlog(c->fc, "depth %d, ctab id %d\n",
1245                    st->codec->bits_per_coded_sample, color_table_id);
1246             /* figure out the palette situation */
1247             color_depth = st->codec->bits_per_coded_sample & 0x1F;
1248             color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1249
1250             /* if the depth is 2, 4, or 8 bpp, file is palettized */
1251             if ((color_depth == 2) || (color_depth == 4) ||
1252                 (color_depth == 8)) {
1253                 /* for palette traversal */
1254                 unsigned int color_start, color_count, color_end;
1255                 unsigned char r, g, b;
1256
1257                 if (color_greyscale) {
1258                     int color_index, color_dec;
1259                     /* compute the greyscale palette */
1260                     st->codec->bits_per_coded_sample = color_depth;
1261                     color_count = 1 << color_depth;
1262                     color_index = 255;
1263                     color_dec = 256 / (color_count - 1);
1264                     for (j = 0; j < color_count; j++) {
1265                         r = g = b = color_index;
1266                         sc->palette[j] =
1267                             (r << 16) | (g << 8) | (b);
1268                         color_index -= color_dec;
1269                         if (color_index < 0)
1270                             color_index = 0;
1271                     }
1272                 } else if (color_table_id) {
1273                     const uint8_t *color_table;
1274                     /* if flag bit 3 is set, use the default palette */
1275                     color_count = 1 << color_depth;
1276                     if (color_depth == 2)
1277                         color_table = ff_qt_default_palette_4;
1278                     else if (color_depth == 4)
1279                         color_table = ff_qt_default_palette_16;
1280                     else
1281                         color_table = ff_qt_default_palette_256;
1282
1283                     for (j = 0; j < color_count; j++) {
1284                         r = color_table[j * 3 + 0];
1285                         g = color_table[j * 3 + 1];
1286                         b = color_table[j * 3 + 2];
1287                         sc->palette[j] =
1288                             (r << 16) | (g << 8) | (b);
1289                     }
1290                 } else {
1291                     /* load the palette from the file */
1292                     color_start = avio_rb32(pb);
1293                     color_count = avio_rb16(pb);
1294                     color_end = avio_rb16(pb);
1295                     if ((color_start <= 255) &&
1296                         (color_end <= 255)) {
1297                         for (j = color_start; j <= color_end; j++) {
1298                             /* each R, G, or B component is 16 bits;
1299                              * only use the top 8 bits; skip alpha bytes
1300                              * up front */
1301                             avio_r8(pb);
1302                             avio_r8(pb);
1303                             r = avio_r8(pb);
1304                             avio_r8(pb);
1305                             g = avio_r8(pb);
1306                             avio_r8(pb);
1307                             b = avio_r8(pb);
1308                             avio_r8(pb);
1309                             sc->palette[j] =
1310                                 (r << 16) | (g << 8) | (b);
1311                         }
1312                     }
1313                 }
1314                 sc->has_palette = 1;
1315             }
1316         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1317             int bits_per_sample, flags;
1318             uint16_t version = avio_rb16(pb);
1319
1320             st->codec->codec_id = id;
1321             avio_rb16(pb); /* revision level */
1322             avio_rb32(pb); /* vendor */
1323
1324             st->codec->channels = avio_rb16(pb);             /* channel count */
1325             av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1326             st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */
1327
1328             sc->audio_cid = avio_rb16(pb);
1329             avio_rb16(pb); /* packet size = 0 */
1330
1331             st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1332
1333             //Read QT version 1 fields. In version 0 these do not exist.
1334             av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1335             if (!c->isom) {
1336                 if (version==1) {
1337                     sc->samples_per_frame = avio_rb32(pb);
1338                     avio_rb32(pb); /* bytes per packet */
1339                     sc->bytes_per_frame = avio_rb32(pb);
1340                     avio_rb32(pb); /* bytes per sample */
1341                 } else if (version==2) {
1342                     avio_rb32(pb); /* sizeof struct only */
1343                     st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1344                     st->codec->channels = avio_rb32(pb);
1345                     avio_rb32(pb); /* always 0x7F000000 */
1346                     st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1347                     flags = avio_rb32(pb); /* lpcm format specific flag */
1348                     sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1349                     sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1350                     if (format == MKTAG('l','p','c','m'))
1351                         st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1352                 }
1353             }
1354
1355             switch (st->codec->codec_id) {
1356             case CODEC_ID_PCM_S8:
1357             case CODEC_ID_PCM_U8:
1358                 if (st->codec->bits_per_coded_sample == 16)
1359                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
1360                 break;
1361             case CODEC_ID_PCM_S16LE:
1362             case CODEC_ID_PCM_S16BE:
1363                 if (st->codec->bits_per_coded_sample == 8)
1364                     st->codec->codec_id = CODEC_ID_PCM_S8;
1365                 else if (st->codec->bits_per_coded_sample == 24)
1366                     st->codec->codec_id =
1367                         st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1368                         CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1369                 break;
1370             /* set values for old format before stsd version 1 appeared */
1371             case CODEC_ID_MACE3:
1372                 sc->samples_per_frame = 6;
1373                 sc->bytes_per_frame = 2*st->codec->channels;
1374                 break;
1375             case CODEC_ID_MACE6:
1376                 sc->samples_per_frame = 6;
1377                 sc->bytes_per_frame = 1*st->codec->channels;
1378                 break;
1379             case CODEC_ID_ADPCM_IMA_QT:
1380                 sc->samples_per_frame = 64;
1381                 sc->bytes_per_frame = 34*st->codec->channels;
1382                 break;
1383             case CODEC_ID_GSM:
1384                 sc->samples_per_frame = 160;
1385                 sc->bytes_per_frame = 33;
1386                 break;
1387             default:
1388                 break;
1389             }
1390
1391             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1392             if (bits_per_sample) {
1393                 st->codec->bits_per_coded_sample = bits_per_sample;
1394                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1395             }
1396         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1397             // ttxt stsd contains display flags, justification, background
1398             // color, fonts, and default styles, so fake an atom to read it
1399             MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1400             if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1401                 mov_read_glbl(c, pb, fake_atom);
1402             st->codec->codec_id= id;
1403             st->codec->width = sc->width;
1404             st->codec->height = sc->height;
1405         } else {
1406             /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1407             avio_skip(pb, size - (avio_tell(pb) - start_pos));
1408         }
1409         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1410         a.size = size - (avio_tell(pb) - start_pos);
1411         if (a.size > 8) {
1412             int ret;
1413             if ((ret = mov_read_default(c, pb, a)) < 0)
1414                 return ret;
1415         } else if (a.size > 0)
1416             avio_skip(pb, a.size);
1417     }
1418
1419     if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1420         st->codec->sample_rate= sc->time_scale;
1421
1422     /* special codec parameters handling */
1423     switch (st->codec->codec_id) {
1424 #if CONFIG_DV_DEMUXER
1425     case CODEC_ID_DVAUDIO:
1426         c->dv_fctx = avformat_alloc_context();
1427         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1428         if (!c->dv_demux) {
1429             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1430             return AVERROR(ENOMEM);
1431         }
1432         sc->dv_audio_container = 1;
1433         st->codec->codec_id = CODEC_ID_PCM_S16LE;
1434         break;
1435 #endif
1436     /* no ifdef since parameters are always those */
1437     case CODEC_ID_QCELP:
1438         // force sample rate for qcelp when not stored in mov
1439         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1440             st->codec->sample_rate = 8000;
1441         st->codec->channels= 1; /* really needed */
1442         break;
1443     case CODEC_ID_AMR_NB:
1444         st->codec->channels= 1; /* really needed */
1445         /* force sample rate for amr, stsd in 3gp does not store sample rate */
1446         st->codec->sample_rate = 8000;
1447         break;
1448     case CODEC_ID_AMR_WB:
1449         st->codec->channels    = 1;
1450         st->codec->sample_rate = 16000;
1451         break;
1452     case CODEC_ID_MP2:
1453     case CODEC_ID_MP3:
1454         st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1455         st->need_parsing = AVSTREAM_PARSE_FULL;
1456         break;
1457     case CODEC_ID_GSM:
1458     case CODEC_ID_ADPCM_MS:
1459     case CODEC_ID_ADPCM_IMA_WAV:
1460     case CODEC_ID_ILBC:
1461         st->codec->block_align = sc->bytes_per_frame;
1462         break;
1463     case CODEC_ID_ALAC:
1464         if (st->codec->extradata_size == 36) {
1465             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1466             st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1467         }
1468         break;
1469     case CODEC_ID_VC1:
1470         st->need_parsing = AVSTREAM_PARSE_FULL;
1471         break;
1472     default:
1473         break;
1474     }
1475
1476     return 0;
1477 }
1478
1479 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1480 {
1481     int entries;
1482
1483     avio_r8(pb); /* version */
1484     avio_rb24(pb); /* flags */
1485     entries = avio_rb32(pb);
1486
1487     return ff_mov_read_stsd_entries(c, pb, entries);
1488 }
1489
1490 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1491 {
1492     AVStream *st;
1493     MOVStreamContext *sc;
1494     unsigned int i, entries;
1495
1496     if (c->fc->nb_streams < 1)
1497         return 0;
1498     st = c->fc->streams[c->fc->nb_streams-1];
1499     sc = st->priv_data;
1500
1501     avio_r8(pb); /* version */
1502     avio_rb24(pb); /* flags */
1503
1504     entries = avio_rb32(pb);
1505
1506     av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1507
1508     if (!entries)
1509         return 0;
1510     if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1511         return AVERROR_INVALIDDATA;
1512     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1513     if (!sc->stsc_data)
1514         return AVERROR(ENOMEM);
1515     sc->stsc_count = entries;
1516
1517     for (i=0; i<entries; i++) {
1518         sc->stsc_data[i].first = avio_rb32(pb);
1519         sc->stsc_data[i].count = avio_rb32(pb);
1520         sc->stsc_data[i].id = avio_rb32(pb);
1521     }
1522     return 0;
1523 }
1524
1525 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1526 {
1527     AVStream *st;
1528     MOVStreamContext *sc;
1529     unsigned i, entries;
1530
1531     if (c->fc->nb_streams < 1)
1532         return 0;
1533     st = c->fc->streams[c->fc->nb_streams-1];
1534     sc = st->priv_data;
1535
1536     avio_rb32(pb); // version + flags
1537
1538     entries = avio_rb32(pb);
1539     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1540         return AVERROR_INVALIDDATA;
1541     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1542     if (!sc->stps_data)
1543         return AVERROR(ENOMEM);
1544     sc->stps_count = entries;
1545
1546     for (i = 0; i < entries; i++) {
1547         sc->stps_data[i] = avio_rb32(pb);
1548         //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1549     }
1550
1551     return 0;
1552 }
1553
1554 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1555 {
1556     AVStream *st;
1557     MOVStreamContext *sc;
1558     unsigned int i, entries;
1559
1560     if (c->fc->nb_streams < 1)
1561         return 0;
1562     st = c->fc->streams[c->fc->nb_streams-1];
1563     sc = st->priv_data;
1564
1565     avio_r8(pb); /* version */
1566     avio_rb24(pb); /* flags */
1567
1568     entries = avio_rb32(pb);
1569
1570     av_dlog(c->fc, "keyframe_count = %d\n", entries);
1571
1572     if (!entries)
1573     {
1574         sc->keyframe_absent = 1;
1575         return 0;
1576     }
1577     if (entries >= UINT_MAX / sizeof(int))
1578         return AVERROR_INVALIDDATA;
1579     sc->keyframes = av_malloc(entries * sizeof(int));
1580     if (!sc->keyframes)
1581         return AVERROR(ENOMEM);
1582     sc->keyframe_count = entries;
1583
1584     for (i=0; i<entries; i++) {
1585         sc->keyframes[i] = avio_rb32(pb);
1586         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1587     }
1588     return 0;
1589 }
1590
1591 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1592 {
1593     AVStream *st;
1594     MOVStreamContext *sc;
1595     unsigned int i, entries, sample_size, field_size, num_bytes;
1596     GetBitContext gb;
1597     unsigned char* buf;
1598
1599     if (c->fc->nb_streams < 1)
1600         return 0;
1601     st = c->fc->streams[c->fc->nb_streams-1];
1602     sc = st->priv_data;
1603
1604     avio_r8(pb); /* version */
1605     avio_rb24(pb); /* flags */
1606
1607     if (atom.type == MKTAG('s','t','s','z')) {
1608         sample_size = avio_rb32(pb);
1609         if (!sc->sample_size) /* do not overwrite value computed in stsd */
1610             sc->sample_size = sample_size;
1611         field_size = 32;
1612     } else {
1613         sample_size = 0;
1614         avio_rb24(pb); /* reserved */
1615         field_size = avio_r8(pb);
1616     }
1617     entries = avio_rb32(pb);
1618
1619     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1620
1621     sc->sample_count = entries;
1622     if (sample_size)
1623         return 0;
1624
1625     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1626         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1627         return AVERROR_INVALIDDATA;
1628     }
1629
1630     if (!entries)
1631         return 0;
1632     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1633         return AVERROR_INVALIDDATA;
1634     sc->sample_sizes = av_malloc(entries * sizeof(int));
1635     if (!sc->sample_sizes)
1636         return AVERROR(ENOMEM);
1637
1638     num_bytes = (entries*field_size+4)>>3;
1639
1640     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1641     if (!buf) {
1642         av_freep(&sc->sample_sizes);
1643         return AVERROR(ENOMEM);
1644     }
1645
1646     if (avio_read(pb, buf, num_bytes) < num_bytes) {
1647         av_freep(&sc->sample_sizes);
1648         av_free(buf);
1649         return AVERROR_INVALIDDATA;
1650     }
1651
1652     init_get_bits(&gb, buf, 8*num_bytes);
1653
1654     for (i = 0; i < entries; i++) {
1655         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1656         sc->data_size += sc->sample_sizes[i];
1657     }
1658
1659     av_free(buf);
1660     return 0;
1661 }
1662
1663 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1664 {
1665     AVStream *st;
1666     MOVStreamContext *sc;
1667     unsigned int i, entries;
1668     int64_t duration=0;
1669     int64_t total_sample_count=0;
1670
1671     if (c->fc->nb_streams < 1)
1672         return 0;
1673     st = c->fc->streams[c->fc->nb_streams-1];
1674     sc = st->priv_data;
1675
1676     avio_r8(pb); /* version */
1677     avio_rb24(pb); /* flags */
1678     entries = avio_rb32(pb);
1679
1680     av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1681             c->fc->nb_streams-1, entries);
1682
1683     if (!entries)
1684         return 0;
1685     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1686         return AVERROR(EINVAL);
1687
1688     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1689     if (!sc->stts_data)
1690         return AVERROR(ENOMEM);
1691
1692     sc->stts_count = entries;
1693
1694     for (i=0; i<entries; i++) {
1695         int sample_duration;
1696         int sample_count;
1697
1698         sample_count=avio_rb32(pb);
1699         sample_duration = avio_rb32(pb);
1700         sc->stts_data[i].count= sample_count;
1701         sc->stts_data[i].duration= sample_duration;
1702
1703         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1704                 sample_count, sample_duration);
1705
1706         duration+=(int64_t)sample_duration*sample_count;
1707         total_sample_count+=sample_count;
1708     }
1709
1710     st->nb_frames= total_sample_count;
1711     if (duration)
1712         st->duration= duration;
1713     sc->track_end = duration;
1714     return 0;
1715 }
1716
1717 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1718 {
1719     AVStream *st;
1720     MOVStreamContext *sc;
1721     unsigned int i, entries;
1722
1723     if (c->fc->nb_streams < 1)
1724         return 0;
1725     st = c->fc->streams[c->fc->nb_streams-1];
1726     sc = st->priv_data;
1727
1728     avio_r8(pb); /* version */
1729     avio_rb24(pb); /* flags */
1730     entries = avio_rb32(pb);
1731
1732     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1733
1734     if (!entries)
1735         return 0;
1736     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1737         return AVERROR_INVALIDDATA;
1738     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1739     if (!sc->ctts_data)
1740         return AVERROR(ENOMEM);
1741     sc->ctts_count = entries;
1742
1743     for (i=0; i<entries; i++) {
1744         int count    =avio_rb32(pb);
1745         int duration =avio_rb32(pb);
1746
1747         sc->ctts_data[i].count   = count;
1748         sc->ctts_data[i].duration= duration;
1749         if (duration < 0)
1750             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1751     }
1752
1753     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1754
1755     return 0;
1756 }
1757
1758 static void mov_build_index(MOVContext *mov, AVStream *st)
1759 {
1760     MOVStreamContext *sc = st->priv_data;
1761     int64_t current_offset;
1762     int64_t current_dts = 0;
1763     unsigned int stts_index = 0;
1764     unsigned int stsc_index = 0;
1765     unsigned int stss_index = 0;
1766     unsigned int stps_index = 0;
1767     unsigned int i, j;
1768     uint64_t stream_size = 0;
1769     AVIndexEntry *mem;
1770
1771     /* adjust first dts according to edit list */
1772     if (sc->time_offset && mov->time_scale > 0) {
1773         if (sc->time_offset < 0)
1774             sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1775         current_dts = -sc->time_offset;
1776         if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
1777             sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1778             /* more than 16 frames delay, dts are likely wrong
1779                this happens with files created by iMovie */
1780             sc->wrong_dts = 1;
1781             st->codec->has_b_frames = 1;
1782         }
1783     }
1784
1785     /* only use old uncompressed audio chunk demuxing when stts specifies it */
1786     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1787           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1788         unsigned int current_sample = 0;
1789         unsigned int stts_sample = 0;
1790         unsigned int sample_size;
1791         unsigned int distance = 0;
1792         int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1793
1794         current_dts -= sc->dts_shift;
1795
1796         if (!sc->sample_count)
1797             return;
1798         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1799             return;
1800         mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1801         if (!mem)
1802             return;
1803         st->index_entries = mem;
1804         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1805
1806         for (i = 0; i < sc->chunk_count; i++) {
1807             current_offset = sc->chunk_offsets[i];
1808             while (stsc_index + 1 < sc->stsc_count &&
1809                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1810                 stsc_index++;
1811             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1812                 int keyframe = 0;
1813                 if (current_sample >= sc->sample_count) {
1814                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1815                     return;
1816                 }
1817
1818                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1819                     keyframe = 1;
1820                     if (stss_index + 1 < sc->keyframe_count)
1821                         stss_index++;
1822                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1823                     keyframe = 1;
1824                     if (stps_index + 1 < sc->stps_count)
1825                         stps_index++;
1826                 }
1827                 if (keyframe)
1828                     distance = 0;
1829                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1830                 if (sc->pseudo_stream_id == -1 ||
1831                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1832                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1833                     e->pos = current_offset;
1834                     e->timestamp = current_dts;
1835                     e->size = sample_size;
1836                     e->min_distance = distance;
1837                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1838                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1839                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1840                             current_offset, current_dts, sample_size, distance, keyframe);
1841                 }
1842
1843                 current_offset += sample_size;
1844                 stream_size += sample_size;
1845                 current_dts += sc->stts_data[stts_index].duration;
1846                 distance++;
1847                 stts_sample++;
1848                 current_sample++;
1849                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1850                     stts_sample = 0;
1851                     stts_index++;
1852                 }
1853             }
1854         }
1855         if (st->duration > 0)
1856             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1857     } else {
1858         unsigned chunk_samples, total = 0;
1859
1860         // compute total chunk count
1861         for (i = 0; i < sc->stsc_count; i++) {
1862             unsigned count, chunk_count;
1863
1864             chunk_samples = sc->stsc_data[i].count;
1865             if (i != sc->stsc_count - 1 &&
1866                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1867                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1868                 return;
1869             }
1870
1871             if (sc->samples_per_frame >= 160) { // gsm
1872                 count = chunk_samples / sc->samples_per_frame;
1873             } else if (sc->samples_per_frame > 1) {
1874                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1875                 count = (chunk_samples+samples-1) / samples;
1876             } else {
1877                 count = (chunk_samples+1023) / 1024;
1878             }
1879
1880             if (i < sc->stsc_count - 1)
1881                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1882             else
1883                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1884             total += chunk_count * count;
1885         }
1886
1887         av_dlog(mov->fc, "chunk count %d\n", total);
1888         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1889             return;
1890         mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1891         if (!mem)
1892             return;
1893         st->index_entries = mem;
1894         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1895
1896         // populate index
1897         for (i = 0; i < sc->chunk_count; i++) {
1898             current_offset = sc->chunk_offsets[i];
1899             if (stsc_index + 1 < sc->stsc_count &&
1900                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1901                 stsc_index++;
1902             chunk_samples = sc->stsc_data[stsc_index].count;
1903
1904             while (chunk_samples > 0) {
1905                 AVIndexEntry *e;
1906                 unsigned size, samples;
1907
1908                 if (sc->samples_per_frame >= 160) { // gsm
1909                     samples = sc->samples_per_frame;
1910                     size = sc->bytes_per_frame;
1911                 } else {
1912                     if (sc->samples_per_frame > 1) {
1913                         samples = FFMIN((1024 / sc->samples_per_frame)*
1914                                         sc->samples_per_frame, chunk_samples);
1915                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1916                     } else {
1917                         samples = FFMIN(1024, chunk_samples);
1918                         size = samples * sc->sample_size;
1919                     }
1920                 }
1921
1922                 if (st->nb_index_entries >= total) {
1923                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1924                     return;
1925                 }
1926                 e = &st->index_entries[st->nb_index_entries++];
1927                 e->pos = current_offset;
1928                 e->timestamp = current_dts;
1929                 e->size = size;
1930                 e->min_distance = 0;
1931                 e->flags = AVINDEX_KEYFRAME;
1932                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1933                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1934                         size, samples);
1935
1936                 current_offset += size;
1937                 current_dts += samples;
1938                 chunk_samples -= samples;
1939             }
1940         }
1941     }
1942 }
1943
1944 static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
1945                          AVIOInterruptCB *int_cb)
1946 {
1947     /* try relative path, we do not try the absolute because it can leak information about our
1948        system to an attacker */
1949     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1950         char filename[1024];
1951         char *src_path;
1952         int i, l;
1953
1954         /* find a source dir */
1955         src_path = strrchr(src, '/');
1956         if (src_path)
1957             src_path++;
1958         else
1959             src_path = src;
1960
1961         /* find a next level down to target */
1962         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1963             if (ref->path[l] == '/') {
1964                 if (i == ref->nlvl_to - 1)
1965                     break;
1966                 else
1967                     i++;
1968             }
1969
1970         /* compose filename if next level down to target was found */
1971         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
1972             memcpy(filename, src, src_path - src);
1973             filename[src_path - src] = 0;
1974
1975             for (i = 1; i < ref->nlvl_from; i++)
1976                 av_strlcat(filename, "../", 1024);
1977
1978             av_strlcat(filename, ref->path + l + 1, 1024);
1979
1980             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
1981                 return 0;
1982         }
1983     }
1984
1985     return AVERROR(ENOENT);
1986 }
1987
1988 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1989 {
1990     AVStream *st;
1991     MOVStreamContext *sc;
1992     int ret;
1993
1994     st = avformat_new_stream(c->fc, NULL);
1995     if (!st) return AVERROR(ENOMEM);
1996     st->id = c->fc->nb_streams;
1997     sc = av_mallocz(sizeof(MOVStreamContext));
1998     if (!sc) return AVERROR(ENOMEM);
1999
2000     st->priv_data = sc;
2001     st->codec->codec_type = AVMEDIA_TYPE_DATA;
2002     sc->ffindex = st->index;
2003
2004     if ((ret = mov_read_default(c, pb, atom)) < 0)
2005         return ret;
2006
2007     /* sanity checks */
2008     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2009                             (!sc->sample_size && !sc->sample_count))) {
2010         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2011                st->index);
2012         return 0;
2013     }
2014
2015     if (sc->time_scale <= 0) {
2016         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2017         sc->time_scale = c->time_scale;
2018         if (sc->time_scale <= 0)
2019             sc->time_scale = 1;
2020     }
2021
2022     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2023
2024     mov_build_index(c, st);
2025
2026     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2027         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2028         if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
2029             av_log(c->fc, AV_LOG_ERROR,
2030                    "stream %d, error opening alias: path='%s', dir='%s', "
2031                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2032                    st->index, dref->path, dref->dir, dref->filename,
2033                    dref->volume, dref->nlvl_from, dref->nlvl_to);
2034     } else
2035         sc->pb = c->fc->pb;
2036
2037     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2038         if (!st->sample_aspect_ratio.num &&
2039             (st->codec->width != sc->width || st->codec->height != sc->height)) {
2040             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2041                                              ((double)st->codec->width * sc->height), INT_MAX);
2042         }
2043
2044         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2045                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2046
2047         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2048             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2049                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2050     }
2051
2052     switch (st->codec->codec_id) {
2053 #if CONFIG_H261_DECODER
2054     case CODEC_ID_H261:
2055 #endif
2056 #if CONFIG_H263_DECODER
2057     case CODEC_ID_H263:
2058 #endif
2059 #if CONFIG_MPEG4_DECODER
2060     case CODEC_ID_MPEG4:
2061 #endif
2062         st->codec->width = 0; /* let decoder init width/height */
2063         st->codec->height= 0;
2064         break;
2065     }
2066
2067     /* Do not need those anymore. */
2068     av_freep(&sc->chunk_offsets);
2069     av_freep(&sc->stsc_data);
2070     av_freep(&sc->sample_sizes);
2071     av_freep(&sc->keyframes);
2072     av_freep(&sc->stts_data);
2073     av_freep(&sc->stps_data);
2074
2075     return 0;
2076 }
2077
2078 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2079 {
2080     int ret;
2081     c->itunes_metadata = 1;
2082     ret = mov_read_default(c, pb, atom);
2083     c->itunes_metadata = 0;
2084     return ret;
2085 }
2086
2087 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2088 {
2089     while (atom.size > 8) {
2090         uint32_t tag = avio_rl32(pb);
2091         atom.size -= 4;
2092         if (tag == MKTAG('h','d','l','r')) {
2093             avio_seek(pb, -8, SEEK_CUR);
2094             atom.size += 8;
2095             return mov_read_default(c, pb, atom);
2096         }
2097     }
2098     return 0;
2099 }
2100
2101 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2102 {
2103     int i;
2104     int width;
2105     int height;
2106     int64_t disp_transform[2];
2107     int display_matrix[3][2];
2108     AVStream *st;
2109     MOVStreamContext *sc;
2110     int version;
2111
2112     if (c->fc->nb_streams < 1)
2113         return 0;
2114     st = c->fc->streams[c->fc->nb_streams-1];
2115     sc = st->priv_data;
2116
2117     version = avio_r8(pb);
2118     avio_rb24(pb); /* flags */
2119     /*
2120     MOV_TRACK_ENABLED 0x0001
2121     MOV_TRACK_IN_MOVIE 0x0002
2122     MOV_TRACK_IN_PREVIEW 0x0004
2123     MOV_TRACK_IN_POSTER 0x0008
2124     */
2125
2126     if (version == 1) {
2127         avio_rb64(pb);
2128         avio_rb64(pb);
2129     } else {
2130         avio_rb32(pb); /* creation time */
2131         avio_rb32(pb); /* modification time */
2132     }
2133     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2134     avio_rb32(pb); /* reserved */
2135
2136     /* highlevel (considering edits) duration in movie timebase */
2137     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2138     avio_rb32(pb); /* reserved */
2139     avio_rb32(pb); /* reserved */
2140
2141     avio_rb16(pb); /* layer */
2142     avio_rb16(pb); /* alternate group */
2143     avio_rb16(pb); /* volume */
2144     avio_rb16(pb); /* reserved */
2145
2146     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2147     // they're kept in fixed point format through all calculations
2148     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2149     for (i = 0; i < 3; i++) {
2150         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
2151         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
2152         avio_rb32(pb);           // 2.30 fixed point (not used)
2153     }
2154
2155     width = avio_rb32(pb);       // 16.16 fixed point track width
2156     height = avio_rb32(pb);      // 16.16 fixed point track height
2157     sc->width = width >> 16;
2158     sc->height = height >> 16;
2159
2160     // transform the display width/height according to the matrix
2161     // skip this if the display matrix is the default identity matrix
2162     // or if it is rotating the picture, ex iPhone 3GS
2163     // to keep the same scale, use [width height 1<<16]
2164     if (width && height &&
2165         ((display_matrix[0][0] != 65536  ||
2166           display_matrix[1][1] != 65536) &&
2167          !display_matrix[0][1] &&
2168          !display_matrix[1][0] &&
2169          !display_matrix[2][0] && !display_matrix[2][1])) {
2170         for (i = 0; i < 2; i++)
2171             disp_transform[i] =
2172                 (int64_t)  width  * display_matrix[0][i] +
2173                 (int64_t)  height * display_matrix[1][i] +
2174                 ((int64_t) display_matrix[2][i] << 16);
2175
2176         //sample aspect ratio is new width/height divided by old width/height
2177         st->sample_aspect_ratio = av_d2q(
2178             ((double) disp_transform[0] * height) /
2179             ((double) disp_transform[1] * width), INT_MAX);
2180     }
2181     return 0;
2182 }
2183
2184 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2185 {
2186     MOVFragment *frag = &c->fragment;
2187     MOVTrackExt *trex = NULL;
2188     int flags, track_id, i;
2189
2190     avio_r8(pb); /* version */
2191     flags = avio_rb24(pb);
2192
2193     track_id = avio_rb32(pb);
2194     if (!track_id)
2195         return AVERROR_INVALIDDATA;
2196     frag->track_id = track_id;
2197     for (i = 0; i < c->trex_count; i++)
2198         if (c->trex_data[i].track_id == frag->track_id) {
2199             trex = &c->trex_data[i];
2200             break;
2201         }
2202     if (!trex) {
2203         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2204         return AVERROR_INVALIDDATA;
2205     }
2206
2207     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2208                              avio_rb64(pb) : frag->moof_offset;
2209     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2210
2211     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2212                      avio_rb32(pb) : trex->duration;
2213     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
2214                      avio_rb32(pb) : trex->size;
2215     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
2216                      avio_rb32(pb) : trex->flags;
2217     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2218     return 0;
2219 }
2220
2221 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2222 {
2223     c->chapter_track = avio_rb32(pb);
2224     return 0;
2225 }
2226
2227 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2228 {
2229     MOVTrackExt *trex;
2230
2231     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2232         return AVERROR_INVALIDDATA;
2233     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2234     if (!trex)
2235         return AVERROR(ENOMEM);
2236     c->trex_data = trex;
2237     trex = &c->trex_data[c->trex_count++];
2238     avio_r8(pb); /* version */
2239     avio_rb24(pb); /* flags */
2240     trex->track_id = avio_rb32(pb);
2241     trex->stsd_id  = avio_rb32(pb);
2242     trex->duration = avio_rb32(pb);
2243     trex->size     = avio_rb32(pb);
2244     trex->flags    = avio_rb32(pb);
2245     return 0;
2246 }
2247
2248 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2249 {
2250     MOVFragment *frag = &c->fragment;
2251     AVStream *st = NULL;
2252     MOVStreamContext *sc;
2253     MOVStts *ctts_data;
2254     uint64_t offset;
2255     int64_t dts;
2256     int data_offset = 0;
2257     unsigned entries, first_sample_flags = frag->flags;
2258     int flags, distance, i, found_keyframe = 0;
2259
2260     for (i = 0; i < c->fc->nb_streams; i++) {
2261         if (c->fc->streams[i]->id == frag->track_id) {
2262             st = c->fc->streams[i];
2263             break;
2264         }
2265     }
2266     if (!st) {
2267         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2268         return AVERROR_INVALIDDATA;
2269     }
2270     sc = st->priv_data;
2271     if (sc->pseudo_stream_id+1 != frag->stsd_id)
2272         return 0;
2273     avio_r8(pb); /* version */
2274     flags = avio_rb24(pb);
2275     entries = avio_rb32(pb);
2276     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2277
2278     /* Always assume the presence of composition time offsets.
2279      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2280      *  1) in the initial movie, there are no samples.
2281      *  2) in the first movie fragment, there is only one sample without composition time offset.
2282      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
2283     if (!sc->ctts_count && sc->sample_count)
2284     {
2285         /* Complement ctts table if moov atom doesn't have ctts atom. */
2286         ctts_data = av_malloc(sizeof(*sc->ctts_data));
2287         if (!ctts_data)
2288             return AVERROR(ENOMEM);
2289         sc->ctts_data = ctts_data;
2290         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2291         sc->ctts_data[sc->ctts_count].duration = 0;
2292         sc->ctts_count++;
2293     }
2294     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2295         return AVERROR_INVALIDDATA;
2296     ctts_data = av_realloc(sc->ctts_data,
2297                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2298     if (!ctts_data)
2299         return AVERROR(ENOMEM);
2300     sc->ctts_data = ctts_data;
2301
2302     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
2303     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2304     dts    = sc->track_end - sc->time_offset;
2305     offset = frag->base_data_offset + data_offset;
2306     distance = 0;
2307     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2308     for (i = 0; i < entries; i++) {
2309         unsigned sample_size = frag->size;
2310         int sample_flags = i ? frag->flags : first_sample_flags;
2311         unsigned sample_duration = frag->duration;
2312         int keyframe = 0;
2313
2314         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2315         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
2316         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
2317         sc->ctts_data[sc->ctts_count].count = 1;
2318         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2319                                                   avio_rb32(pb) : 0;
2320         sc->ctts_count++;
2321         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2322             keyframe = 1;
2323         else if (!found_keyframe)
2324             keyframe = found_keyframe =
2325                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2326                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2327         if (keyframe)
2328             distance = 0;
2329         av_add_index_entry(st, offset, dts, sample_size, distance,
2330                            keyframe ? AVINDEX_KEYFRAME : 0);
2331         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2332                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2333                 offset, dts, sample_size, distance, keyframe);
2334         distance++;
2335         dts += sample_duration;
2336         offset += sample_size;
2337         sc->data_size += sample_size;
2338     }
2339     frag->moof_offset = offset;
2340     st->duration = sc->track_end = dts + sc->time_offset;
2341     return 0;
2342 }
2343
2344 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2345 /* like the files created with Adobe Premiere 5.0, for samples see */
2346 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2347 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2348 {
2349     int err;
2350
2351     if (atom.size < 8)
2352         return 0; /* continue */
2353     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2354         avio_skip(pb, atom.size - 4);
2355         return 0;
2356     }
2357     atom.type = avio_rl32(pb);
2358     atom.size -= 8;
2359     if (atom.type != MKTAG('m','d','a','t')) {
2360         avio_skip(pb, atom.size);
2361         return 0;
2362     }
2363     err = mov_read_mdat(c, pb, atom);
2364     return err;
2365 }
2366
2367 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2368 {
2369 #if CONFIG_ZLIB
2370     AVIOContext ctx;
2371     uint8_t *cmov_data;
2372     uint8_t *moov_data; /* uncompressed data */
2373     long cmov_len, moov_len;
2374     int ret = -1;
2375
2376     avio_rb32(pb); /* dcom atom */
2377     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2378         return AVERROR_INVALIDDATA;
2379     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2380         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2381         return AVERROR_INVALIDDATA;
2382     }
2383     avio_rb32(pb); /* cmvd atom */
2384     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2385         return AVERROR_INVALIDDATA;
2386     moov_len = avio_rb32(pb); /* uncompressed size */
2387     cmov_len = atom.size - 6 * 4;
2388
2389     cmov_data = av_malloc(cmov_len);
2390     if (!cmov_data)
2391         return AVERROR(ENOMEM);
2392     moov_data = av_malloc(moov_len);
2393     if (!moov_data) {
2394         av_free(cmov_data);
2395         return AVERROR(ENOMEM);
2396     }
2397     avio_read(pb, cmov_data, cmov_len);
2398     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2399         goto free_and_return;
2400     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2401         goto free_and_return;
2402     atom.type = MKTAG('m','o','o','v');
2403     atom.size = moov_len;
2404     ret = mov_read_default(c, &ctx, atom);
2405 free_and_return:
2406     av_free(moov_data);
2407     av_free(cmov_data);
2408     return ret;
2409 #else
2410     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2411     return AVERROR(ENOSYS);
2412 #endif
2413 }
2414
2415 /* edit list atom */
2416 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2417 {
2418     MOVStreamContext *sc;
2419     int i, edit_count, version;
2420
2421     if (c->fc->nb_streams < 1)
2422         return 0;
2423     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2424
2425     version = avio_r8(pb); /* version */
2426     avio_rb24(pb); /* flags */
2427     edit_count = avio_rb32(pb); /* entries */
2428
2429     if ((uint64_t)edit_count*12+8 > atom.size)
2430         return AVERROR_INVALIDDATA;
2431
2432     for (i=0; i<edit_count; i++){
2433         int64_t time;
2434         int64_t duration;
2435         if (version == 1) {
2436             duration = avio_rb64(pb);
2437             time     = avio_rb64(pb);
2438         } else {
2439             duration = avio_rb32(pb); /* segment duration */
2440             time     = (int32_t)avio_rb32(pb); /* media time */
2441         }
2442         avio_rb32(pb); /* Media rate */
2443         if (i == 0 && time >= -1) {
2444             sc->time_offset = time != -1 ? time : -duration;
2445         }
2446     }
2447
2448     if (edit_count > 1)
2449         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2450                "a/v desync might occur, patch welcome\n");
2451
2452     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2453     return 0;
2454 }
2455
2456 static const MOVParseTableEntry mov_default_parse_table[] = {
2457 { MKTAG('a','v','s','s'), mov_read_extradata },
2458 { MKTAG('c','h','p','l'), mov_read_chpl },
2459 { MKTAG('c','o','6','4'), mov_read_stco },
2460 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2461 { MKTAG('d','i','n','f'), mov_read_default },
2462 { MKTAG('d','r','e','f'), mov_read_dref },
2463 { MKTAG('e','d','t','s'), mov_read_default },
2464 { MKTAG('e','l','s','t'), mov_read_elst },
2465 { MKTAG('e','n','d','a'), mov_read_enda },
2466 { MKTAG('f','i','e','l'), mov_read_fiel },
2467 { MKTAG('f','t','y','p'), mov_read_ftyp },
2468 { MKTAG('g','l','b','l'), mov_read_glbl },
2469 { MKTAG('h','d','l','r'), mov_read_hdlr },
2470 { MKTAG('i','l','s','t'), mov_read_ilst },
2471 { MKTAG('j','p','2','h'), mov_read_extradata },
2472 { MKTAG('m','d','a','t'), mov_read_mdat },
2473 { MKTAG('m','d','h','d'), mov_read_mdhd },
2474 { MKTAG('m','d','i','a'), mov_read_default },
2475 { MKTAG('m','e','t','a'), mov_read_meta },
2476 { MKTAG('m','i','n','f'), mov_read_default },
2477 { MKTAG('m','o','o','f'), mov_read_moof },
2478 { MKTAG('m','o','o','v'), mov_read_moov },
2479 { MKTAG('m','v','e','x'), mov_read_default },
2480 { MKTAG('m','v','h','d'), mov_read_mvhd },
2481 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2482 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2483 { MKTAG('a','v','c','C'), mov_read_glbl },
2484 { MKTAG('p','a','s','p'), mov_read_pasp },
2485 { MKTAG('s','t','b','l'), mov_read_default },
2486 { MKTAG('s','t','c','o'), mov_read_stco },
2487 { MKTAG('s','t','p','s'), mov_read_stps },
2488 { MKTAG('s','t','r','f'), mov_read_strf },
2489 { MKTAG('s','t','s','c'), mov_read_stsc },
2490 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2491 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2492 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2493 { MKTAG('s','t','t','s'), mov_read_stts },
2494 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2495 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2496 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2497 { MKTAG('t','r','a','k'), mov_read_trak },
2498 { MKTAG('t','r','a','f'), mov_read_default },
2499 { MKTAG('t','r','e','f'), mov_read_default },
2500 { MKTAG('c','h','a','p'), mov_read_chap },
2501 { MKTAG('t','r','e','x'), mov_read_trex },
2502 { MKTAG('t','r','u','n'), mov_read_trun },
2503 { MKTAG('u','d','t','a'), mov_read_default },
2504 { MKTAG('w','a','v','e'), mov_read_wave },
2505 { MKTAG('e','s','d','s'), mov_read_esds },
2506 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2507 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2508 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2509 { MKTAG('w','f','e','x'), mov_read_wfex },
2510 { MKTAG('c','m','o','v'), mov_read_cmov },
2511 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2512 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2513 { 0, NULL }
2514 };
2515
2516 static int mov_probe(AVProbeData *p)
2517 {
2518     unsigned int offset;
2519     uint32_t tag;
2520     int score = 0;
2521
2522     /* check file header */
2523     offset = 0;
2524     for (;;) {
2525         /* ignore invalid offset */
2526         if ((offset + 8) > (unsigned int)p->buf_size)
2527             return score;
2528         tag = AV_RL32(p->buf + offset + 4);
2529         switch(tag) {
2530         /* check for obvious tags */
2531         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2532         case MKTAG('m','o','o','v'):
2533         case MKTAG('m','d','a','t'):
2534         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2535         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2536         case MKTAG('f','t','y','p'):
2537             return AVPROBE_SCORE_MAX;
2538         /* those are more common words, so rate then a bit less */
2539         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2540         case MKTAG('w','i','d','e'):
2541         case MKTAG('f','r','e','e'):
2542         case MKTAG('j','u','n','k'):
2543         case MKTAG('p','i','c','t'):
2544             return AVPROBE_SCORE_MAX - 5;
2545         case MKTAG(0x82,0x82,0x7f,0x7d):
2546         case MKTAG('s','k','i','p'):
2547         case MKTAG('u','u','i','d'):
2548         case MKTAG('p','r','f','l'):
2549             offset = AV_RB32(p->buf+offset) + offset;
2550             /* if we only find those cause probedata is too small at least rate them */
2551             score = AVPROBE_SCORE_MAX - 50;
2552             break;
2553         default:
2554             /* unrecognized tag */
2555             return score;
2556         }
2557     }
2558 }
2559
2560 // must be done after parsing all trak because there's no order requirement
2561 static void mov_read_chapters(AVFormatContext *s)
2562 {
2563     MOVContext *mov = s->priv_data;
2564     AVStream *st = NULL;
2565     MOVStreamContext *sc;
2566     int64_t cur_pos;
2567     int i;
2568
2569     for (i = 0; i < s->nb_streams; i++)
2570         if (s->streams[i]->id == mov->chapter_track) {
2571             st = s->streams[i];
2572             break;
2573         }
2574     if (!st) {
2575         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2576         return;
2577     }
2578
2579     st->discard = AVDISCARD_ALL;
2580     sc = st->priv_data;
2581     cur_pos = avio_tell(sc->pb);
2582
2583     for (i = 0; i < st->nb_index_entries; i++) {
2584         AVIndexEntry *sample = &st->index_entries[i];
2585         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2586         uint8_t *title;
2587         uint16_t ch;
2588         int len, title_len;
2589
2590         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2591             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2592             goto finish;
2593         }
2594
2595         // the first two bytes are the length of the title
2596         len = avio_rb16(sc->pb);
2597         if (len > sample->size-2)
2598             continue;
2599         title_len = 2*len + 1;
2600         if (!(title = av_mallocz(title_len)))
2601             goto finish;
2602
2603         // The samples could theoretically be in any encoding if there's an encd
2604         // atom following, but in practice are only utf-8 or utf-16, distinguished
2605         // instead by the presence of a BOM
2606         if (!len) {
2607             title[0] = 0;
2608         } else {
2609             ch = avio_rb16(sc->pb);
2610             if (ch == 0xfeff)
2611                 avio_get_str16be(sc->pb, len, title, title_len);
2612             else if (ch == 0xfffe)
2613                 avio_get_str16le(sc->pb, len, title, title_len);
2614             else {
2615                 AV_WB16(title, ch);
2616                 if (len == 1 || len == 2)
2617                     title[len] = 0;
2618                 else
2619                     avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
2620             }
2621         }
2622
2623         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2624         av_freep(&title);
2625     }
2626 finish:
2627     avio_seek(sc->pb, cur_pos, SEEK_SET);
2628 }
2629
2630 static int mov_read_close(AVFormatContext *s)
2631 {
2632     MOVContext *mov = s->priv_data;
2633     int i, j;
2634
2635     for (i = 0; i < s->nb_streams; i++) {
2636         AVStream *st = s->streams[i];
2637         MOVStreamContext *sc = st->priv_data;
2638
2639         av_freep(&sc->ctts_data);
2640         for (j = 0; j < sc->drefs_count; j++) {
2641             av_freep(&sc->drefs[j].path);
2642             av_freep(&sc->drefs[j].dir);
2643         }
2644         av_freep(&sc->drefs);
2645         if (sc->pb && sc->pb != s->pb)
2646             avio_close(sc->pb);
2647     }
2648
2649     if (mov->dv_demux) {
2650         for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2651             av_freep(&mov->dv_fctx->streams[i]->codec);
2652             av_freep(&mov->dv_fctx->streams[i]);
2653         }
2654         av_freep(&mov->dv_fctx);
2655         av_freep(&mov->dv_demux);
2656     }
2657
2658     av_freep(&mov->trex_data);
2659
2660     return 0;
2661 }
2662
2663 static int mov_read_header(AVFormatContext *s)
2664 {
2665     MOVContext *mov = s->priv_data;
2666     AVIOContext *pb = s->pb;
2667     int err;
2668     MOVAtom atom = { AV_RL32("root") };
2669
2670     mov->fc = s;
2671     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2672     if (pb->seekable)
2673         atom.size = avio_size(pb);
2674     else
2675         atom.size = INT64_MAX;
2676
2677     /* check MOV header */
2678     if ((err = mov_read_default(mov, pb, atom)) < 0) {
2679         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2680         mov_read_close(s);
2681         return err;
2682     }
2683     if (!mov->found_moov) {
2684         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2685         mov_read_close(s);
2686         return AVERROR_INVALIDDATA;
2687     }
2688     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2689
2690     if (pb->seekable && mov->chapter_track > 0)
2691         mov_read_chapters(s);
2692
2693     if (mov->trex_data) {
2694         int i;
2695         for (i = 0; i < s->nb_streams; i++) {
2696             AVStream *st = s->streams[i];
2697             MOVStreamContext *sc = st->priv_data;
2698             if (st->duration)
2699                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2700         }
2701     }
2702
2703     return 0;
2704 }
2705
2706 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2707 {
2708     AVIndexEntry *sample = NULL;
2709     int64_t best_dts = INT64_MAX;
2710     int i;
2711     for (i = 0; i < s->nb_streams; i++) {
2712         AVStream *avst = s->streams[i];
2713         MOVStreamContext *msc = avst->priv_data;
2714         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2715             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2716             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2717             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2718             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2719                 (s->pb->seekable &&
2720                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2721                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2722                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2723                 sample = current_sample;
2724                 best_dts = dts;
2725                 *st = avst;
2726             }
2727         }
2728     }
2729     return sample;
2730 }
2731
2732 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2733 {
2734     MOVContext *mov = s->priv_data;
2735     MOVStreamContext *sc;
2736     AVIndexEntry *sample;
2737     AVStream *st = NULL;
2738     int ret;
2739  retry:
2740     sample = mov_find_next_sample(s, &st);
2741     if (!sample) {
2742         mov->found_mdat = 0;
2743         if (!mov->next_root_atom)
2744             return AVERROR_EOF;
2745         avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2746         mov->next_root_atom = 0;
2747         if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2748             s->pb->eof_reached)
2749             return AVERROR_EOF;
2750         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2751         goto retry;
2752     }
2753     sc = st->priv_data;
2754     /* must be done just before reading, to avoid infinite loop on sample */
2755     sc->current_sample++;
2756
2757     if (st->discard != AVDISCARD_ALL) {
2758         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2759             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2760                    sc->ffindex, sample->pos);
2761             return AVERROR_INVALIDDATA;
2762         }
2763         ret = av_get_packet(sc->pb, pkt, sample->size);
2764         if (ret < 0)
2765             return ret;
2766         if (sc->has_palette) {
2767             uint8_t *pal;
2768
2769             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2770             if (!pal) {
2771                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2772             } else {
2773                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2774                 sc->has_palette = 0;
2775             }
2776         }
2777 #if CONFIG_DV_DEMUXER
2778         if (mov->dv_demux && sc->dv_audio_container) {
2779             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2780             av_free(pkt->data);
2781             pkt->size = 0;
2782             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2783             if (ret < 0)
2784                 return ret;
2785         }
2786 #endif
2787     }
2788
2789     pkt->stream_index = sc->ffindex;
2790     pkt->dts = sample->timestamp;
2791     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2792         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2793         /* update ctts context */
2794         sc->ctts_sample++;
2795         if (sc->ctts_index < sc->ctts_count &&
2796             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2797             sc->ctts_index++;
2798             sc->ctts_sample = 0;
2799         }
2800         if (sc->wrong_dts)
2801             pkt->dts = AV_NOPTS_VALUE;
2802     } else {
2803         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2804             st->index_entries[sc->current_sample].timestamp : st->duration;
2805         pkt->duration = next_dts - pkt->dts;
2806         pkt->pts = pkt->dts;
2807     }
2808     if (st->discard == AVDISCARD_ALL)
2809         goto retry;
2810     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2811     pkt->pos = sample->pos;
2812     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2813             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2814     return 0;
2815 }
2816
2817 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2818 {
2819     MOVStreamContext *sc = st->priv_data;
2820     int sample, time_sample;
2821     int i;
2822
2823     sample = av_index_search_timestamp(st, timestamp, flags);
2824     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2825     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2826         sample = 0;
2827     if (sample < 0) /* not sure what to do */
2828         return AVERROR_INVALIDDATA;
2829     sc->current_sample = sample;
2830     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2831     /* adjust ctts index */
2832     if (sc->ctts_data) {
2833         time_sample = 0;
2834         for (i = 0; i < sc->ctts_count; i++) {
2835             int next = time_sample + sc->ctts_data[i].count;
2836             if (next > sc->current_sample) {
2837                 sc->ctts_index = i;
2838                 sc->ctts_sample = sc->current_sample - time_sample;
2839                 break;
2840             }
2841             time_sample = next;
2842         }
2843     }
2844     return sample;
2845 }
2846
2847 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2848 {
2849     AVStream *st;
2850     int64_t seek_timestamp, timestamp;
2851     int sample;
2852     int i;
2853
2854     if (stream_index >= s->nb_streams)
2855         return AVERROR_INVALIDDATA;
2856     if (sample_time < 0)
2857         sample_time = 0;
2858
2859     st = s->streams[stream_index];
2860     sample = mov_seek_stream(s, st, sample_time, flags);
2861     if (sample < 0)
2862         return sample;
2863
2864     /* adjust seek timestamp to found sample timestamp */
2865     seek_timestamp = st->index_entries[sample].timestamp;
2866
2867     for (i = 0; i < s->nb_streams; i++) {
2868         st = s->streams[i];
2869         if (stream_index == i)
2870             continue;
2871
2872         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2873         mov_seek_stream(s, st, timestamp, flags);
2874     }
2875     return 0;
2876 }
2877
2878 AVInputFormat ff_mov_demuxer = {
2879     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
2880     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2881     .priv_data_size = sizeof(MOVContext),
2882     .read_probe     = mov_probe,
2883     .read_header    = mov_read_header,
2884     .read_packet    = mov_read_packet,
2885     .read_close     = mov_read_close,
2886     .read_seek      = mov_read_seek,
2887 };