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