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