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