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