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