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