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