OSDN Git Service

Merge remote-tracking branch 'qatar/master'
[coroid/ffmpeg_saccubus.git] / 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 {
761     AVStream *st;
762     uint64_t size;
763     uint8_t *buf;
764
765     if (c->fc->nb_streams < 1) // will happen with jp2 files
766         return 0;
767     st= c->fc->streams[c->fc->nb_streams-1];
768     size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
769     if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
770         return -1;
771     buf= av_realloc(st->codec->extradata, size);
772     if(!buf)
773         return -1;
774     st->codec->extradata= buf;
775     buf+= st->codec->extradata_size;
776     st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
777     AV_WB32(       buf    , atom.size + 8);
778     AV_WL32(       buf + 4, atom.type);
779     avio_read(pb, buf + 8, atom.size);
780     return 0;
781 }
782
783 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
784 {
785     AVStream *st;
786
787     if (c->fc->nb_streams < 1)
788         return 0;
789     st = c->fc->streams[c->fc->nb_streams-1];
790
791     if((uint64_t)atom.size > (1<<30))
792         return -1;
793
794     if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
795         // pass all frma atom to codec, needed at least for QDMC and QDM2
796         av_free(st->codec->extradata);
797         st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
798         if (!st->codec->extradata)
799             return AVERROR(ENOMEM);
800         st->codec->extradata_size = atom.size;
801         avio_read(pb, st->codec->extradata, atom.size);
802     } else if (atom.size > 8) { /* to read frma, esds atoms */
803         if (mov_read_default(c, pb, atom) < 0)
804             return -1;
805     } else
806         avio_skip(pb, atom.size);
807     return 0;
808 }
809
810 /**
811  * This function reads atom content and puts data in extradata without tag
812  * nor size unlike mov_read_extradata.
813  */
814 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
815 {
816     AVStream *st;
817
818     if (c->fc->nb_streams < 1)
819         return 0;
820     st = c->fc->streams[c->fc->nb_streams-1];
821
822     if((uint64_t)atom.size > (1<<30))
823         return -1;
824
825     av_free(st->codec->extradata);
826     st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
827     if (!st->codec->extradata)
828         return AVERROR(ENOMEM);
829     st->codec->extradata_size = atom.size;
830     avio_read(pb, st->codec->extradata, atom.size);
831     return 0;
832 }
833
834 /**
835  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
836  * but can have extradata appended at the end after the 40 bytes belonging
837  * to the struct.
838  */
839 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
840 {
841     AVStream *st;
842
843     if (c->fc->nb_streams < 1)
844         return 0;
845     if (atom.size <= 40)
846         return 0;
847     st = c->fc->streams[c->fc->nb_streams-1];
848
849     if((uint64_t)atom.size > (1<<30))
850         return -1;
851
852     av_free(st->codec->extradata);
853     st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
854     if (!st->codec->extradata)
855         return AVERROR(ENOMEM);
856     st->codec->extradata_size = atom.size - 40;
857     avio_skip(pb, 40);
858     avio_read(pb, st->codec->extradata, atom.size - 40);
859     return 0;
860 }
861
862 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
863 {
864     AVStream *st;
865     MOVStreamContext *sc;
866     unsigned int i, entries;
867
868     if (c->fc->nb_streams < 1)
869         return 0;
870     st = c->fc->streams[c->fc->nb_streams-1];
871     sc = st->priv_data;
872
873     avio_r8(pb); /* version */
874     avio_rb24(pb); /* flags */
875
876     entries = avio_rb32(pb);
877
878     if(entries >= UINT_MAX/sizeof(int64_t))
879         return -1;
880
881     sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
882     if (!sc->chunk_offsets)
883         return AVERROR(ENOMEM);
884     sc->chunk_count = entries;
885
886     if      (atom.type == MKTAG('s','t','c','o'))
887         for(i=0; i<entries; i++)
888             sc->chunk_offsets[i] = avio_rb32(pb);
889     else if (atom.type == MKTAG('c','o','6','4'))
890         for(i=0; i<entries; i++)
891             sc->chunk_offsets[i] = avio_rb64(pb);
892     else
893         return -1;
894
895     return 0;
896 }
897
898 /**
899  * Compute codec id for 'lpcm' tag.
900  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
901  */
902 enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
903 {
904     if (flags & 1) { // floating point
905         if (flags & 2) { // big endian
906             if      (bps == 32) return CODEC_ID_PCM_F32BE;
907             else if (bps == 64) return CODEC_ID_PCM_F64BE;
908         } else {
909             if      (bps == 32) return CODEC_ID_PCM_F32LE;
910             else if (bps == 64) return CODEC_ID_PCM_F64LE;
911         }
912     } else {
913         if (flags & 2) {
914             if      (bps == 8)
915                 // signed integer
916                 if (flags & 4)  return CODEC_ID_PCM_S8;
917                 else            return CODEC_ID_PCM_U8;
918             else if (bps == 16) return CODEC_ID_PCM_S16BE;
919             else if (bps == 24) return CODEC_ID_PCM_S24BE;
920             else if (bps == 32) return CODEC_ID_PCM_S32BE;
921         } else {
922             if      (bps == 8)
923                 if (flags & 4)  return CODEC_ID_PCM_S8;
924                 else            return CODEC_ID_PCM_U8;
925             else if (bps == 16) return CODEC_ID_PCM_S16LE;
926             else if (bps == 24) return CODEC_ID_PCM_S24LE;
927             else if (bps == 32) return CODEC_ID_PCM_S32LE;
928         }
929     }
930     return CODEC_ID_NONE;
931 }
932
933 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
934 {
935     AVStream *st;
936     MOVStreamContext *sc;
937     int j, pseudo_stream_id;
938
939     if (c->fc->nb_streams < 1)
940         return 0;
941     st = c->fc->streams[c->fc->nb_streams-1];
942     sc = st->priv_data;
943
944     for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
945         //Parsing Sample description table
946         enum CodecID id;
947         int dref_id = 1;
948         MOVAtom a = { AV_RL32("stsd") };
949         int64_t start_pos = avio_tell(pb);
950         int size = avio_rb32(pb); /* size */
951         uint32_t format = avio_rl32(pb); /* data format */
952
953         if (size >= 16) {
954             avio_rb32(pb); /* reserved */
955             avio_rb16(pb); /* reserved */
956             dref_id = avio_rb16(pb);
957         }
958
959         if (st->codec->codec_tag &&
960             st->codec->codec_tag != format &&
961             (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
962                                    : st->codec->codec_tag != MKTAG('j','p','e','g'))
963            ){
964             /* Multiple fourcc, we skip JPEG. This is not correct, we should
965              * export it as a separate AVStream but this needs a few changes
966              * in the MOV demuxer, patch welcome. */
967         multiple_stsd:
968             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
969             avio_skip(pb, size - (avio_tell(pb) - start_pos));
970             continue;
971         }
972         /* we cannot demux concatenated h264 streams because of different extradata */
973         if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
974             goto multiple_stsd;
975         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
976         sc->dref_id= dref_id;
977
978         st->codec->codec_tag = format;
979         id = ff_codec_get_id(codec_movaudio_tags, format);
980         if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
981             id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
982
983         if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
984             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
985         } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
986                    format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
987             id = ff_codec_get_id(codec_movvideo_tags, format);
988             if (id <= 0)
989                 id = ff_codec_get_id(ff_codec_bmp_tags, format);
990             if (id > 0)
991                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
992             else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
993                 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
994                 if(id > 0)
995                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
996             }
997         }
998
999         av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
1000                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1001                 (format >> 24) & 0xff, st->codec->codec_type);
1002
1003         if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1004             unsigned int color_depth, len;
1005             int color_greyscale;
1006
1007             st->codec->codec_id = id;
1008             avio_rb16(pb); /* version */
1009             avio_rb16(pb); /* revision level */
1010             avio_rb32(pb); /* vendor */
1011             avio_rb32(pb); /* temporal quality */
1012             avio_rb32(pb); /* spatial quality */
1013
1014             st->codec->width = avio_rb16(pb); /* width */
1015             st->codec->height = avio_rb16(pb); /* height */
1016
1017             avio_rb32(pb); /* horiz resolution */
1018             avio_rb32(pb); /* vert resolution */
1019             avio_rb32(pb); /* data size, always 0 */
1020             avio_rb16(pb); /* frames per samples */
1021
1022             len = avio_r8(pb); /* codec name, pascal string */
1023             if (len > 31)
1024                 len = 31;
1025             mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1026             if (len < 31)
1027                 avio_skip(pb, 31 - len);
1028             /* codec_tag YV12 triggers an UV swap in rawdec.c */
1029             if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1030                 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1031
1032             st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1033             st->codec->color_table_id = avio_rb16(pb); /* colortable id */
1034             av_dlog(c->fc, "depth %d, ctab id %d\n",
1035                    st->codec->bits_per_coded_sample, st->codec->color_table_id);
1036             /* figure out the palette situation */
1037             color_depth = st->codec->bits_per_coded_sample & 0x1F;
1038             color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1039
1040             /* if the depth is 2, 4, or 8 bpp, file is palettized */
1041             if ((color_depth == 2) || (color_depth == 4) ||
1042                 (color_depth == 8)) {
1043                 /* for palette traversal */
1044                 unsigned int color_start, color_count, color_end;
1045                 unsigned char r, g, b;
1046
1047                 if (color_greyscale) {
1048                     int color_index, color_dec;
1049                     /* compute the greyscale palette */
1050                     st->codec->bits_per_coded_sample = color_depth;
1051                     color_count = 1 << color_depth;
1052                     color_index = 255;
1053                     color_dec = 256 / (color_count - 1);
1054                     for (j = 0; j < color_count; j++) {
1055                         r = g = b = color_index;
1056                         sc->palette[j] =
1057                             (r << 16) | (g << 8) | (b);
1058                         color_index -= color_dec;
1059                         if (color_index < 0)
1060                             color_index = 0;
1061                     }
1062                 } else if (st->codec->color_table_id) {
1063                     const uint8_t *color_table;
1064                     /* if flag bit 3 is set, use the default palette */
1065                     color_count = 1 << color_depth;
1066                     if (color_depth == 2)
1067                         color_table = ff_qt_default_palette_4;
1068                     else if (color_depth == 4)
1069                         color_table = ff_qt_default_palette_16;
1070                     else
1071                         color_table = ff_qt_default_palette_256;
1072
1073                     for (j = 0; j < color_count; j++) {
1074                         r = color_table[j * 3 + 0];
1075                         g = color_table[j * 3 + 1];
1076                         b = color_table[j * 3 + 2];
1077                         sc->palette[j] =
1078                             (r << 16) | (g << 8) | (b);
1079                     }
1080                 } else {
1081                     /* load the palette from the file */
1082                     color_start = avio_rb32(pb);
1083                     color_count = avio_rb16(pb);
1084                     color_end = avio_rb16(pb);
1085                     if ((color_start <= 255) &&
1086                         (color_end <= 255)) {
1087                         for (j = color_start; j <= color_end; j++) {
1088                             /* each R, G, or B component is 16 bits;
1089                              * only use the top 8 bits; skip alpha bytes
1090                              * up front */
1091                             avio_r8(pb);
1092                             avio_r8(pb);
1093                             r = avio_r8(pb);
1094                             avio_r8(pb);
1095                             g = avio_r8(pb);
1096                             avio_r8(pb);
1097                             b = avio_r8(pb);
1098                             avio_r8(pb);
1099                             sc->palette[j] =
1100                                 (r << 16) | (g << 8) | (b);
1101                         }
1102                     }
1103                 }
1104                 sc->has_palette = 1;
1105             }
1106         } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1107             int bits_per_sample, flags;
1108             uint16_t version = avio_rb16(pb);
1109
1110             st->codec->codec_id = id;
1111             avio_rb16(pb); /* revision level */
1112             avio_rb32(pb); /* vendor */
1113
1114             st->codec->channels = avio_rb16(pb);             /* channel count */
1115             av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1116             st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */
1117
1118             sc->audio_cid = avio_rb16(pb);
1119             avio_rb16(pb); /* packet size = 0 */
1120
1121             st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1122
1123             //Read QT version 1 fields. In version 0 these do not exist.
1124             av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1125             if(!c->isom) {
1126                 if(version==1) {
1127                     sc->samples_per_frame = avio_rb32(pb);
1128                     avio_rb32(pb); /* bytes per packet */
1129                     sc->bytes_per_frame = avio_rb32(pb);
1130                     avio_rb32(pb); /* bytes per sample */
1131                 } else if(version==2) {
1132                     avio_rb32(pb); /* sizeof struct only */
1133                     st->codec->sample_rate = av_int2dbl(avio_rb64(pb)); /* float 64 */
1134                     st->codec->channels = avio_rb32(pb);
1135                     avio_rb32(pb); /* always 0x7F000000 */
1136                     st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1137                     flags = avio_rb32(pb); /* lpcm format specific flag */
1138                     sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1139                     sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1140                     if (format == MKTAG('l','p','c','m'))
1141                         st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1142                 }
1143             }
1144
1145             switch (st->codec->codec_id) {
1146             case CODEC_ID_PCM_S8:
1147             case CODEC_ID_PCM_U8:
1148                 if (st->codec->bits_per_coded_sample == 16)
1149                     st->codec->codec_id = CODEC_ID_PCM_S16BE;
1150                 break;
1151             case CODEC_ID_PCM_S16LE:
1152             case CODEC_ID_PCM_S16BE:
1153                 if (st->codec->bits_per_coded_sample == 8)
1154                     st->codec->codec_id = CODEC_ID_PCM_S8;
1155                 else if (st->codec->bits_per_coded_sample == 24)
1156                     st->codec->codec_id =
1157                         st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1158                         CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
1159                 break;
1160             /* set values for old format before stsd version 1 appeared */
1161             case CODEC_ID_MACE3:
1162                 sc->samples_per_frame = 6;
1163                 sc->bytes_per_frame = 2*st->codec->channels;
1164                 break;
1165             case CODEC_ID_MACE6:
1166                 sc->samples_per_frame = 6;
1167                 sc->bytes_per_frame = 1*st->codec->channels;
1168                 break;
1169             case CODEC_ID_ADPCM_IMA_QT:
1170                 sc->samples_per_frame = 64;
1171                 sc->bytes_per_frame = 34*st->codec->channels;
1172                 break;
1173             case CODEC_ID_GSM:
1174                 sc->samples_per_frame = 160;
1175                 sc->bytes_per_frame = 33;
1176                 break;
1177             default:
1178                 break;
1179             }
1180
1181             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1182             if (bits_per_sample) {
1183                 st->codec->bits_per_coded_sample = bits_per_sample;
1184                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1185             }
1186         } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1187             // ttxt stsd contains display flags, justification, background
1188             // color, fonts, and default styles, so fake an atom to read it
1189             MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1190             if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1191                 mov_read_glbl(c, pb, fake_atom);
1192             st->codec->codec_id= id;
1193             st->codec->width = sc->width;
1194             st->codec->height = sc->height;
1195         } else {
1196             if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1197                 int val;
1198                 avio_rb32(pb);       /* reserved */
1199                 val = avio_rb32(pb); /* flags */
1200                 if (val & 1)
1201                     st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1202                 avio_rb32(pb);
1203                 avio_rb32(pb);
1204                 st->codec->time_base.den = get_byte(pb);
1205                 st->codec->time_base.num = 1;
1206             }
1207             /* other codec type, just skip (rtp, mp4s, ...) */
1208             avio_skip(pb, size - (avio_tell(pb) - start_pos));
1209         }
1210         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1211         a.size = size - (avio_tell(pb) - start_pos);
1212         if (a.size > 8) {
1213             if (mov_read_default(c, pb, a) < 0)
1214                 return -1;
1215         } else if (a.size > 0)
1216             avio_skip(pb, a.size);
1217     }
1218
1219     if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1220         st->codec->sample_rate= sc->time_scale;
1221
1222     /* special codec parameters handling */
1223     switch (st->codec->codec_id) {
1224 #if CONFIG_DV_DEMUXER
1225     case CODEC_ID_DVAUDIO:
1226         c->dv_fctx = avformat_alloc_context();
1227         c->dv_demux = dv_init_demux(c->dv_fctx);
1228         if (!c->dv_demux) {
1229             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1230             return -1;
1231         }
1232         sc->dv_audio_container = 1;
1233         st->codec->codec_id = CODEC_ID_PCM_S16LE;
1234         break;
1235 #endif
1236     /* no ifdef since parameters are always those */
1237     case CODEC_ID_QCELP:
1238         // force sample rate for qcelp when not stored in mov
1239         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1240             st->codec->sample_rate = 8000;
1241         st->codec->frame_size= 160;
1242         st->codec->channels= 1; /* really needed */
1243         break;
1244     case CODEC_ID_AMR_NB:
1245     case CODEC_ID_AMR_WB:
1246         st->codec->frame_size= sc->samples_per_frame;
1247         st->codec->channels= 1; /* really needed */
1248         /* force sample rate for amr, stsd in 3gp does not store sample rate */
1249         if (st->codec->codec_id == CODEC_ID_AMR_NB)
1250             st->codec->sample_rate = 8000;
1251         else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1252             st->codec->sample_rate = 16000;
1253         break;
1254     case CODEC_ID_MP2:
1255     case CODEC_ID_MP3:
1256         st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1257         st->need_parsing = AVSTREAM_PARSE_FULL;
1258         break;
1259     case CODEC_ID_GSM:
1260     case CODEC_ID_ADPCM_MS:
1261     case CODEC_ID_ADPCM_IMA_WAV:
1262         st->codec->frame_size = sc->samples_per_frame;
1263         st->codec->block_align = sc->bytes_per_frame;
1264         break;
1265     case CODEC_ID_ALAC:
1266         if (st->codec->extradata_size == 36) {
1267             st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1268             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1269             st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1270         }
1271         break;
1272     default:
1273         break;
1274     }
1275
1276     return 0;
1277 }
1278
1279 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1280 {
1281     int entries;
1282
1283     avio_r8(pb); /* version */
1284     avio_rb24(pb); /* flags */
1285     entries = avio_rb32(pb);
1286
1287     return ff_mov_read_stsd_entries(c, pb, entries);
1288 }
1289
1290 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1291 {
1292     AVStream *st;
1293     MOVStreamContext *sc;
1294     unsigned int i, entries;
1295
1296     if (c->fc->nb_streams < 1)
1297         return 0;
1298     st = c->fc->streams[c->fc->nb_streams-1];
1299     sc = st->priv_data;
1300
1301     avio_r8(pb); /* version */
1302     avio_rb24(pb); /* flags */
1303
1304     entries = avio_rb32(pb);
1305
1306     av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1307
1308     if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1309         return -1;
1310     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1311     if (!sc->stsc_data)
1312         return AVERROR(ENOMEM);
1313     sc->stsc_count = entries;
1314
1315     for(i=0; i<entries; i++) {
1316         sc->stsc_data[i].first = avio_rb32(pb);
1317         sc->stsc_data[i].count = avio_rb32(pb);
1318         sc->stsc_data[i].id = avio_rb32(pb);
1319     }
1320     return 0;
1321 }
1322
1323 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1324 {
1325     AVStream *st;
1326     MOVStreamContext *sc;
1327     unsigned i, entries;
1328
1329     if (c->fc->nb_streams < 1)
1330         return 0;
1331     st = c->fc->streams[c->fc->nb_streams-1];
1332     sc = st->priv_data;
1333
1334     avio_rb32(pb); // version + flags
1335
1336     entries = avio_rb32(pb);
1337     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1338         return -1;
1339     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1340     if (!sc->stps_data)
1341         return AVERROR(ENOMEM);
1342     sc->stps_count = entries;
1343
1344     for (i = 0; i < entries; i++) {
1345         sc->stps_data[i] = avio_rb32(pb);
1346         //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1347     }
1348
1349     return 0;
1350 }
1351
1352 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1353 {
1354     AVStream *st;
1355     MOVStreamContext *sc;
1356     unsigned int i, entries;
1357
1358     if (c->fc->nb_streams < 1)
1359         return 0;
1360     st = c->fc->streams[c->fc->nb_streams-1];
1361     sc = st->priv_data;
1362
1363     avio_r8(pb); /* version */
1364     avio_rb24(pb); /* flags */
1365
1366     entries = avio_rb32(pb);
1367
1368     av_dlog(c->fc, "keyframe_count = %d\n", entries);
1369
1370     if(entries >= UINT_MAX / sizeof(int))
1371         return -1;
1372     sc->keyframes = av_malloc(entries * sizeof(int));
1373     if (!sc->keyframes)
1374         return AVERROR(ENOMEM);
1375     sc->keyframe_count = entries;
1376
1377     for(i=0; i<entries; i++) {
1378         sc->keyframes[i] = avio_rb32(pb);
1379         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1380     }
1381     return 0;
1382 }
1383
1384 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1385 {
1386     AVStream *st;
1387     MOVStreamContext *sc;
1388     unsigned int i, entries, sample_size, field_size, num_bytes;
1389     GetBitContext gb;
1390     unsigned char* buf;
1391
1392     if (c->fc->nb_streams < 1)
1393         return 0;
1394     st = c->fc->streams[c->fc->nb_streams-1];
1395     sc = st->priv_data;
1396
1397     avio_r8(pb); /* version */
1398     avio_rb24(pb); /* flags */
1399
1400     if (atom.type == MKTAG('s','t','s','z')) {
1401         sample_size = avio_rb32(pb);
1402         if (!sc->sample_size) /* do not overwrite value computed in stsd */
1403             sc->sample_size = sample_size;
1404         field_size = 32;
1405     } else {
1406         sample_size = 0;
1407         avio_rb24(pb); /* reserved */
1408         field_size = avio_r8(pb);
1409     }
1410     entries = avio_rb32(pb);
1411
1412     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1413
1414     sc->sample_count = entries;
1415     if (sample_size)
1416         return 0;
1417
1418     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1419         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1420         return -1;
1421     }
1422
1423     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1424         return -1;
1425     sc->sample_sizes = av_malloc(entries * sizeof(int));
1426     if (!sc->sample_sizes)
1427         return AVERROR(ENOMEM);
1428
1429     num_bytes = (entries*field_size+4)>>3;
1430
1431     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1432     if (!buf) {
1433         av_freep(&sc->sample_sizes);
1434         return AVERROR(ENOMEM);
1435     }
1436
1437     if (avio_read(pb, buf, num_bytes) < num_bytes) {
1438         av_freep(&sc->sample_sizes);
1439         av_free(buf);
1440         return -1;
1441     }
1442
1443     init_get_bits(&gb, buf, 8*num_bytes);
1444
1445     for(i=0; i<entries; i++)
1446         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1447
1448     av_free(buf);
1449     return 0;
1450 }
1451
1452 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1453 {
1454     AVStream *st;
1455     MOVStreamContext *sc;
1456     unsigned int i, entries;
1457     int64_t duration=0;
1458     int64_t total_sample_count=0;
1459
1460     if (c->fc->nb_streams < 1)
1461         return 0;
1462     st = c->fc->streams[c->fc->nb_streams-1];
1463     sc = st->priv_data;
1464
1465     avio_r8(pb); /* version */
1466     avio_rb24(pb); /* flags */
1467     entries = avio_rb32(pb);
1468
1469     av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1470
1471     if(entries >= UINT_MAX / sizeof(*sc->stts_data))
1472         return -1;
1473     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1474     if (!sc->stts_data)
1475         return AVERROR(ENOMEM);
1476     sc->stts_count = entries;
1477
1478     for(i=0; i<entries; i++) {
1479         int sample_duration;
1480         int sample_count;
1481
1482         sample_count=avio_rb32(pb);
1483         sample_duration = avio_rb32(pb);
1484         /* sample_duration < 0 is invalid based on the spec */
1485         if (sample_duration < 0) {
1486             av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d", sample_duration);
1487             sample_duration = 1;
1488         }
1489         sc->stts_data[i].count= sample_count;
1490         sc->stts_data[i].duration= sample_duration;
1491
1492         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1493
1494         duration+=(int64_t)sample_duration*sample_count;
1495         total_sample_count+=sample_count;
1496     }
1497
1498     st->nb_frames= total_sample_count;
1499     if(duration)
1500         st->duration= duration;
1501     return 0;
1502 }
1503
1504 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1505 {
1506     AVStream *st;
1507     MOVStreamContext *sc;
1508     unsigned int i, entries;
1509
1510     if (c->fc->nb_streams < 1)
1511         return 0;
1512     st = c->fc->streams[c->fc->nb_streams-1];
1513     sc = st->priv_data;
1514
1515     avio_r8(pb); /* version */
1516     avio_rb24(pb); /* flags */
1517     entries = avio_rb32(pb);
1518
1519     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1520
1521     if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
1522         return -1;
1523     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1524     if (!sc->ctts_data)
1525         return AVERROR(ENOMEM);
1526     sc->ctts_count = entries;
1527
1528     for(i=0; i<entries; i++) {
1529         int count    =avio_rb32(pb);
1530         int duration =avio_rb32(pb);
1531
1532         sc->ctts_data[i].count   = count;
1533         sc->ctts_data[i].duration= duration;
1534         if (duration < 0 && i+1<entries)
1535             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1536     }
1537
1538     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1539
1540     return 0;
1541 }
1542
1543 static void mov_build_index(MOVContext *mov, AVStream *st)
1544 {
1545     MOVStreamContext *sc = st->priv_data;
1546     int64_t current_offset;
1547     int64_t current_dts = 0;
1548     unsigned int stts_index = 0;
1549     unsigned int stsc_index = 0;
1550     unsigned int stss_index = 0;
1551     unsigned int stps_index = 0;
1552     unsigned int i, j;
1553     uint64_t stream_size = 0;
1554
1555     /* adjust first dts according to edit list */
1556     if (sc->time_offset && mov->time_scale > 0) {
1557         if (sc->time_offset < 0)
1558             sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
1559         current_dts = -sc->time_offset;
1560         if (sc->ctts_data && sc->stts_data &&
1561             sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1562             /* more than 16 frames delay, dts are likely wrong
1563                this happens with files created by iMovie */
1564             sc->wrong_dts = 1;
1565             st->codec->has_b_frames = 1;
1566         }
1567     }
1568
1569     /* only use old uncompressed audio chunk demuxing when stts specifies it */
1570     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1571           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1572         unsigned int current_sample = 0;
1573         unsigned int stts_sample = 0;
1574         unsigned int sample_size;
1575         unsigned int distance = 0;
1576         int key_off = sc->keyframes && sc->keyframes[0] == 1;
1577
1578         current_dts -= sc->dts_shift;
1579
1580         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
1581             return;
1582         st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
1583         if (!st->index_entries)
1584             return;
1585         st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
1586
1587         for (i = 0; i < sc->chunk_count; i++) {
1588             current_offset = sc->chunk_offsets[i];
1589             while (stsc_index + 1 < sc->stsc_count &&
1590                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1591                 stsc_index++;
1592             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1593                 int keyframe = 0;
1594                 if (current_sample >= sc->sample_count) {
1595                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1596                     return;
1597                 }
1598
1599                 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1600                     keyframe = 1;
1601                     if (stss_index + 1 < sc->keyframe_count)
1602                         stss_index++;
1603                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1604                     keyframe = 1;
1605                     if (stps_index + 1 < sc->stps_count)
1606                         stps_index++;
1607                 }
1608                 if (keyframe)
1609                     distance = 0;
1610                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
1611                 if(sc->pseudo_stream_id == -1 ||
1612                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1613                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1614                     e->pos = current_offset;
1615                     e->timestamp = current_dts;
1616                     e->size = sample_size;
1617                     e->min_distance = distance;
1618                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1619                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1620                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1621                             current_offset, current_dts, sample_size, distance, keyframe);
1622                 }
1623
1624                 current_offset += sample_size;
1625                 stream_size += sample_size;
1626                 current_dts += sc->stts_data[stts_index].duration;
1627                 distance++;
1628                 stts_sample++;
1629                 current_sample++;
1630                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1631                     stts_sample = 0;
1632                     stts_index++;
1633                 }
1634             }
1635         }
1636         if (st->duration > 0)
1637             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1638     } else {
1639         unsigned chunk_samples, total = 0;
1640
1641         // compute total chunk count
1642         for (i = 0; i < sc->stsc_count; i++) {
1643             unsigned count, chunk_count;
1644
1645             chunk_samples = sc->stsc_data[i].count;
1646             if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1647                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1648                 return;
1649             }
1650
1651             if (sc->samples_per_frame >= 160) { // gsm
1652                 count = chunk_samples / sc->samples_per_frame;
1653             } else if (sc->samples_per_frame > 1) {
1654                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1655                 count = (chunk_samples+samples-1) / samples;
1656             } else {
1657                 count = (chunk_samples+1023) / 1024;
1658             }
1659
1660             if (i < sc->stsc_count - 1)
1661                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1662             else
1663                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1664             total += chunk_count * count;
1665         }
1666
1667         av_dlog(mov->fc, "chunk count %d\n", total);
1668         if (total >= UINT_MAX / sizeof(*st->index_entries))
1669             return;
1670         st->index_entries = av_malloc(total*sizeof(*st->index_entries));
1671         if (!st->index_entries)
1672             return;
1673         st->index_entries_allocated_size = total*sizeof(*st->index_entries);
1674
1675         // populate index
1676         for (i = 0; i < sc->chunk_count; i++) {
1677             current_offset = sc->chunk_offsets[i];
1678             if (stsc_index + 1 < sc->stsc_count &&
1679                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1680                 stsc_index++;
1681             chunk_samples = sc->stsc_data[stsc_index].count;
1682
1683             while (chunk_samples > 0) {
1684                 AVIndexEntry *e;
1685                 unsigned size, samples;
1686
1687                 if (sc->samples_per_frame >= 160) { // gsm
1688                     samples = sc->samples_per_frame;
1689                     size = sc->bytes_per_frame;
1690                 } else {
1691                     if (sc->samples_per_frame > 1) {
1692                         samples = FFMIN((1024 / sc->samples_per_frame)*
1693                                         sc->samples_per_frame, chunk_samples);
1694                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1695                     } else {
1696                         samples = FFMIN(1024, chunk_samples);
1697                         size = samples * sc->sample_size;
1698                     }
1699                 }
1700
1701                 if (st->nb_index_entries >= total) {
1702                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
1703                     return;
1704                 }
1705                 e = &st->index_entries[st->nb_index_entries++];
1706                 e->pos = current_offset;
1707                 e->timestamp = current_dts;
1708                 e->size = size;
1709                 e->min_distance = 0;
1710                 e->flags = AVINDEX_KEYFRAME;
1711                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1712                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
1713                         size, samples);
1714
1715                 current_offset += size;
1716                 current_dts += samples;
1717                 chunk_samples -= samples;
1718             }
1719         }
1720     }
1721 }
1722
1723 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref)
1724 {
1725     /* try relative path, we do not try the absolute because it can leak information about our
1726        system to an attacker */
1727     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
1728         char filename[1024];
1729         const char *src_path;
1730         int i, l;
1731
1732         /* find a source dir */
1733         src_path = strrchr(src, '/');
1734         if (src_path)
1735             src_path++;
1736         else
1737             src_path = src;
1738
1739         /* find a next level down to target */
1740         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
1741             if (ref->path[l] == '/') {
1742                 if (i == ref->nlvl_to - 1)
1743                     break;
1744                 else
1745                     i++;
1746             }
1747
1748         /* compose filename if next level down to target was found */
1749         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
1750             memcpy(filename, src, src_path - src);
1751             filename[src_path - src] = 0;
1752
1753             for (i = 1; i < ref->nlvl_from; i++)
1754                 av_strlcat(filename, "../", 1024);
1755
1756             av_strlcat(filename, ref->path + l + 1, 1024);
1757
1758             if (!avio_open(pb, filename, AVIO_FLAG_READ))
1759                 return 0;
1760         }
1761     }
1762
1763     return AVERROR(ENOENT);
1764 }
1765
1766 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1767 {
1768     AVStream *st;
1769     MOVStreamContext *sc;
1770     int ret;
1771
1772     st = av_new_stream(c->fc, c->fc->nb_streams);
1773     if (!st) return AVERROR(ENOMEM);
1774     sc = av_mallocz(sizeof(MOVStreamContext));
1775     if (!sc) return AVERROR(ENOMEM);
1776
1777     st->priv_data = sc;
1778     st->codec->codec_type = AVMEDIA_TYPE_DATA;
1779     sc->ffindex = st->index;
1780
1781     if ((ret = mov_read_default(c, pb, atom)) < 0)
1782         return ret;
1783
1784     /* sanity checks */
1785     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1786                             (!sc->sample_size && !sc->sample_count))) {
1787         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1788                st->index);
1789         return 0;
1790     }
1791
1792     if (sc->time_scale <= 0) {
1793         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
1794         sc->time_scale = c->time_scale;
1795         if (sc->time_scale <= 0)
1796             sc->time_scale = 1;
1797     }
1798
1799     av_set_pts_info(st, 64, 1, sc->time_scale);
1800
1801     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1802         !st->codec->frame_size && sc->stts_count == 1) {
1803         st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1804                                            st->codec->sample_rate, sc->time_scale);
1805         av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
1806     }
1807
1808     mov_build_index(c, st);
1809
1810     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1811         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
1812         if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
1813             av_log(c->fc, AV_LOG_ERROR,
1814                    "stream %d, error opening alias: path='%s', dir='%s', "
1815                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
1816                    st->index, dref->path, dref->dir, dref->filename,
1817                    dref->volume, dref->nlvl_from, dref->nlvl_to);
1818     } else
1819         sc->pb = c->fc->pb;
1820
1821     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1822         if (!st->sample_aspect_ratio.num &&
1823             (st->codec->width != sc->width || st->codec->height != sc->height)) {
1824             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
1825                                              ((double)st->codec->width * sc->height), INT_MAX);
1826         }
1827
1828         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
1829                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
1830
1831         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
1832             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
1833                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
1834     }
1835
1836     switch (st->codec->codec_id) {
1837 #if CONFIG_H261_DECODER
1838     case CODEC_ID_H261:
1839 #endif
1840 #if CONFIG_H263_DECODER
1841     case CODEC_ID_H263:
1842 #endif
1843 #if CONFIG_H264_DECODER
1844     case CODEC_ID_H264:
1845 #endif
1846 #if CONFIG_MPEG4_DECODER
1847     case CODEC_ID_MPEG4:
1848 #endif
1849         st->codec->width = 0; /* let decoder init width/height */
1850         st->codec->height= 0;
1851         break;
1852     }
1853
1854     /* Do not need those anymore. */
1855     av_freep(&sc->chunk_offsets);
1856     av_freep(&sc->stsc_data);
1857     av_freep(&sc->sample_sizes);
1858     av_freep(&sc->keyframes);
1859     av_freep(&sc->stts_data);
1860     av_freep(&sc->stps_data);
1861
1862     return 0;
1863 }
1864
1865 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1866 {
1867     int ret;
1868     c->itunes_metadata = 1;
1869     ret = mov_read_default(c, pb, atom);
1870     c->itunes_metadata = 0;
1871     return ret;
1872 }
1873
1874 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1875 {
1876     while (atom.size > 8) {
1877         uint32_t tag = avio_rl32(pb);
1878         atom.size -= 4;
1879         if (tag == MKTAG('h','d','l','r')) {
1880             avio_seek(pb, -8, SEEK_CUR);
1881             atom.size += 8;
1882             return mov_read_default(c, pb, atom);
1883         }
1884     }
1885     return 0;
1886 }
1887
1888 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1889 {
1890     int i;
1891     int width;
1892     int height;
1893     int64_t disp_transform[2];
1894     int display_matrix[3][2];
1895     AVStream *st;
1896     MOVStreamContext *sc;
1897     int version;
1898
1899     if (c->fc->nb_streams < 1)
1900         return 0;
1901     st = c->fc->streams[c->fc->nb_streams-1];
1902     sc = st->priv_data;
1903
1904     version = avio_r8(pb);
1905     avio_rb24(pb); /* flags */
1906     /*
1907     MOV_TRACK_ENABLED 0x0001
1908     MOV_TRACK_IN_MOVIE 0x0002
1909     MOV_TRACK_IN_PREVIEW 0x0004
1910     MOV_TRACK_IN_POSTER 0x0008
1911     */
1912
1913     if (version == 1) {
1914         avio_rb64(pb);
1915         avio_rb64(pb);
1916     } else {
1917         avio_rb32(pb); /* creation time */
1918         avio_rb32(pb); /* modification time */
1919     }
1920     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
1921     avio_rb32(pb); /* reserved */
1922
1923     /* highlevel (considering edits) duration in movie timebase */
1924     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
1925     avio_rb32(pb); /* reserved */
1926     avio_rb32(pb); /* reserved */
1927
1928     avio_rb16(pb); /* layer */
1929     avio_rb16(pb); /* alternate group */
1930     avio_rb16(pb); /* volume */
1931     avio_rb16(pb); /* reserved */
1932
1933     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1934     // they're kept in fixed point format through all calculations
1935     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1936     for (i = 0; i < 3; i++) {
1937         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
1938         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
1939         avio_rb32(pb);           // 2.30 fixed point (not used)
1940     }
1941
1942     width = avio_rb32(pb);       // 16.16 fixed point track width
1943     height = avio_rb32(pb);      // 16.16 fixed point track height
1944     sc->width = width >> 16;
1945     sc->height = height >> 16;
1946
1947     if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
1948          av_dict_set(&st->metadata, "rotate", "180", 0);
1949     }
1950
1951     // transform the display width/height according to the matrix
1952     // skip this if the display matrix is the default identity matrix
1953     // or if it is rotating the picture, ex iPhone 3GS
1954     // to keep the same scale, use [width height 1<<16]
1955     if (width && height &&
1956         ((display_matrix[0][0] != 65536  ||
1957           display_matrix[1][1] != 65536) &&
1958          !display_matrix[0][1] &&
1959          !display_matrix[1][0] &&
1960          !display_matrix[2][0] && !display_matrix[2][1])) {
1961         for (i = 0; i < 2; i++)
1962             disp_transform[i] =
1963                 (int64_t)  width  * display_matrix[0][i] +
1964                 (int64_t)  height * display_matrix[1][i] +
1965                 ((int64_t) display_matrix[2][i] << 16);
1966
1967         //sample aspect ratio is new width/height divided by old width/height
1968         st->sample_aspect_ratio = av_d2q(
1969             ((double) disp_transform[0] * height) /
1970             ((double) disp_transform[1] * width), INT_MAX);
1971     }
1972     return 0;
1973 }
1974
1975 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1976 {
1977     MOVFragment *frag = &c->fragment;
1978     MOVTrackExt *trex = NULL;
1979     int flags, track_id, i;
1980
1981     avio_r8(pb); /* version */
1982     flags = avio_rb24(pb);
1983
1984     track_id = avio_rb32(pb);
1985     if (!track_id)
1986         return -1;
1987     frag->track_id = track_id;
1988     for (i = 0; i < c->trex_count; i++)
1989         if (c->trex_data[i].track_id == frag->track_id) {
1990             trex = &c->trex_data[i];
1991             break;
1992         }
1993     if (!trex) {
1994         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1995         return -1;
1996     }
1997
1998     if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
1999     else              frag->base_data_offset = frag->moof_offset;
2000     if (flags & 0x02) frag->stsd_id          = avio_rb32(pb);
2001     else              frag->stsd_id          = trex->stsd_id;
2002
2003     frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
2004     frag->size     = flags & 0x10 ? avio_rb32(pb) : trex->size;
2005     frag->flags    = flags & 0x20 ? avio_rb32(pb) : trex->flags;
2006     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2007     return 0;
2008 }
2009
2010 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2011 {
2012     c->chapter_track = avio_rb32(pb);
2013     return 0;
2014 }
2015
2016 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2017 {
2018     MOVTrackExt *trex;
2019
2020     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2021         return -1;
2022     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2023     if (!trex)
2024         return AVERROR(ENOMEM);
2025     c->trex_data = trex;
2026     trex = &c->trex_data[c->trex_count++];
2027     avio_r8(pb); /* version */
2028     avio_rb24(pb); /* flags */
2029     trex->track_id = avio_rb32(pb);
2030     trex->stsd_id  = avio_rb32(pb);
2031     trex->duration = avio_rb32(pb);
2032     trex->size     = avio_rb32(pb);
2033     trex->flags    = avio_rb32(pb);
2034     return 0;
2035 }
2036
2037 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2038 {
2039     MOVFragment *frag = &c->fragment;
2040     AVStream *st = NULL;
2041     MOVStreamContext *sc;
2042     MOVStts *ctts_data;
2043     uint64_t offset;
2044     int64_t dts;
2045     int data_offset = 0;
2046     unsigned entries, first_sample_flags = frag->flags;
2047     int flags, distance, i;
2048
2049     for (i = 0; i < c->fc->nb_streams; i++) {
2050         if (c->fc->streams[i]->id == frag->track_id) {
2051             st = c->fc->streams[i];
2052             break;
2053         }
2054     }
2055     if (!st) {
2056         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2057         return -1;
2058     }
2059     sc = st->priv_data;
2060     if (sc->pseudo_stream_id+1 != frag->stsd_id)
2061         return 0;
2062     avio_r8(pb); /* version */
2063     flags = avio_rb24(pb);
2064     entries = avio_rb32(pb);
2065     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2066
2067     /* Always assume the presence of composition time offsets.
2068      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2069      *  1) in the initial movie, there are no samples.
2070      *  2) in the first movie fragment, there is only one sample without composition time offset.
2071      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
2072     if (!sc->ctts_count && sc->sample_count)
2073     {
2074         /* Complement ctts table if moov atom doesn't have ctts atom. */
2075         ctts_data = av_malloc(sizeof(*sc->ctts_data));
2076         if (!ctts_data)
2077             return AVERROR(ENOMEM);
2078         sc->ctts_data = ctts_data;
2079         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2080         sc->ctts_data[sc->ctts_count].duration = 0;
2081         sc->ctts_count++;
2082     }
2083     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2084         return -1;
2085     ctts_data = av_realloc(sc->ctts_data,
2086                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2087     if (!ctts_data)
2088         return AVERROR(ENOMEM);
2089     sc->ctts_data = ctts_data;
2090
2091     if (flags & 0x001) data_offset        = avio_rb32(pb);
2092     if (flags & 0x004) first_sample_flags = avio_rb32(pb);
2093     dts = st->duration - sc->time_offset;
2094     offset = frag->base_data_offset + data_offset;
2095     distance = 0;
2096     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2097     for (i = 0; i < entries; i++) {
2098         unsigned sample_size = frag->size;
2099         int sample_flags = i ? frag->flags : first_sample_flags;
2100         unsigned sample_duration = frag->duration;
2101         int keyframe;
2102
2103         if (flags & 0x100) sample_duration = avio_rb32(pb);
2104         if (flags & 0x200) sample_size     = avio_rb32(pb);
2105         if (flags & 0x400) sample_flags    = avio_rb32(pb);
2106         sc->ctts_data[sc->ctts_count].count = 1;
2107         sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
2108         sc->ctts_count++;
2109         if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
2110              (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
2111             distance = 0;
2112         av_add_index_entry(st, offset, dts, sample_size, distance,
2113                            keyframe ? AVINDEX_KEYFRAME : 0);
2114         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2115                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2116                 offset, dts, sample_size, distance, keyframe);
2117         distance++;
2118         dts += sample_duration;
2119         offset += sample_size;
2120     }
2121     frag->moof_offset = offset;
2122     st->duration = dts + sc->time_offset;
2123     return 0;
2124 }
2125
2126 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2127 /* like the files created with Adobe Premiere 5.0, for samples see */
2128 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2129 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2130 {
2131     int err;
2132
2133     if (atom.size < 8)
2134         return 0; /* continue */
2135     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2136         avio_skip(pb, atom.size - 4);
2137         return 0;
2138     }
2139     atom.type = avio_rl32(pb);
2140     atom.size -= 8;
2141     if (atom.type != MKTAG('m','d','a','t')) {
2142         avio_skip(pb, atom.size);
2143         return 0;
2144     }
2145     err = mov_read_mdat(c, pb, atom);
2146     return err;
2147 }
2148
2149 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2150 {
2151 #if CONFIG_ZLIB
2152     AVIOContext ctx;
2153     uint8_t *cmov_data;
2154     uint8_t *moov_data; /* uncompressed data */
2155     long cmov_len, moov_len;
2156     int ret = -1;
2157
2158     avio_rb32(pb); /* dcom atom */
2159     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2160         return -1;
2161     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2162         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2163         return -1;
2164     }
2165     avio_rb32(pb); /* cmvd atom */
2166     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2167         return -1;
2168     moov_len = avio_rb32(pb); /* uncompressed size */
2169     cmov_len = atom.size - 6 * 4;
2170
2171     cmov_data = av_malloc(cmov_len);
2172     if (!cmov_data)
2173         return AVERROR(ENOMEM);
2174     moov_data = av_malloc(moov_len);
2175     if (!moov_data) {
2176         av_free(cmov_data);
2177         return AVERROR(ENOMEM);
2178     }
2179     avio_read(pb, cmov_data, cmov_len);
2180     if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2181         goto free_and_return;
2182     if(ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2183         goto free_and_return;
2184     atom.type = MKTAG('m','o','o','v');
2185     atom.size = moov_len;
2186     ret = mov_read_default(c, &ctx, atom);
2187 free_and_return:
2188     av_free(moov_data);
2189     av_free(cmov_data);
2190     return ret;
2191 #else
2192     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2193     return -1;
2194 #endif
2195 }
2196
2197 /* edit list atom */
2198 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2199 {
2200     MOVStreamContext *sc;
2201     int i, edit_count, version;
2202
2203     if (c->fc->nb_streams < 1)
2204         return 0;
2205     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2206
2207     version = avio_r8(pb); /* version */
2208     avio_rb24(pb); /* flags */
2209     edit_count = avio_rb32(pb); /* entries */
2210
2211     if((uint64_t)edit_count*12+8 > atom.size)
2212         return -1;
2213
2214     for(i=0; i<edit_count; i++){
2215         int64_t time;
2216         int64_t duration;
2217         if (version == 1) {
2218             duration = avio_rb64(pb);
2219             time     = avio_rb64(pb);
2220         } else {
2221             duration = avio_rb32(pb); /* segment duration */
2222             time     = (int32_t)avio_rb32(pb); /* media time */
2223         }
2224         avio_rb32(pb); /* Media rate */
2225         if (i == 0 && time >= -1) {
2226             sc->time_offset = time != -1 ? time : -duration;
2227         }
2228     }
2229
2230     if(edit_count > 1)
2231         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2232                "a/v desync might occur, patch welcome\n");
2233
2234     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2235     return 0;
2236 }
2237
2238 static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2239 {
2240     if (atom.size < 16)
2241         return AVERROR_INVALIDDATA;
2242     avio_skip(pb, 4);
2243     ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2244     return 0;
2245 }
2246
2247 static const MOVParseTableEntry mov_default_parse_table[] = {
2248 { MKTAG('a','v','s','s'), mov_read_extradata },
2249 { MKTAG('c','h','p','l'), mov_read_chpl },
2250 { MKTAG('c','o','6','4'), mov_read_stco },
2251 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2252 { MKTAG('d','i','n','f'), mov_read_default },
2253 { MKTAG('d','r','e','f'), mov_read_dref },
2254 { MKTAG('e','d','t','s'), mov_read_default },
2255 { MKTAG('e','l','s','t'), mov_read_elst },
2256 { MKTAG('e','n','d','a'), mov_read_enda },
2257 { MKTAG('f','i','e','l'), mov_read_extradata },
2258 { MKTAG('f','t','y','p'), mov_read_ftyp },
2259 { MKTAG('g','l','b','l'), mov_read_glbl },
2260 { MKTAG('h','d','l','r'), mov_read_hdlr },
2261 { MKTAG('i','l','s','t'), mov_read_ilst },
2262 { MKTAG('j','p','2','h'), mov_read_extradata },
2263 { MKTAG('m','d','a','t'), mov_read_mdat },
2264 { MKTAG('m','d','h','d'), mov_read_mdhd },
2265 { MKTAG('m','d','i','a'), mov_read_default },
2266 { MKTAG('m','e','t','a'), mov_read_meta },
2267 { MKTAG('m','i','n','f'), mov_read_default },
2268 { MKTAG('m','o','o','f'), mov_read_moof },
2269 { MKTAG('m','o','o','v'), mov_read_moov },
2270 { MKTAG('m','v','e','x'), mov_read_default },
2271 { MKTAG('m','v','h','d'), mov_read_mvhd },
2272 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2273 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
2274 { MKTAG('a','v','c','C'), mov_read_glbl },
2275 { MKTAG('p','a','s','p'), mov_read_pasp },
2276 { MKTAG('s','t','b','l'), mov_read_default },
2277 { MKTAG('s','t','c','o'), mov_read_stco },
2278 { MKTAG('s','t','p','s'), mov_read_stps },
2279 { MKTAG('s','t','r','f'), mov_read_strf },
2280 { MKTAG('s','t','s','c'), mov_read_stsc },
2281 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2282 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2283 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2284 { MKTAG('s','t','t','s'), mov_read_stts },
2285 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2286 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2287 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2288 { MKTAG('t','r','a','k'), mov_read_trak },
2289 { MKTAG('t','r','a','f'), mov_read_default },
2290 { MKTAG('t','r','e','f'), mov_read_default },
2291 { MKTAG('c','h','a','p'), mov_read_chap },
2292 { MKTAG('t','r','e','x'), mov_read_trex },
2293 { MKTAG('t','r','u','n'), mov_read_trun },
2294 { MKTAG('u','d','t','a'), mov_read_default },
2295 { MKTAG('w','a','v','e'), mov_read_wave },
2296 { MKTAG('e','s','d','s'), mov_read_esds },
2297 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2298 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2299 { MKTAG('w','f','e','x'), mov_read_wfex },
2300 { MKTAG('c','m','o','v'), mov_read_cmov },
2301 { MKTAG('c','h','a','n'), mov_read_chan },
2302 { 0, NULL }
2303 };
2304
2305 static int mov_probe(AVProbeData *p)
2306 {
2307     unsigned int offset;
2308     uint32_t tag;
2309     int score = 0;
2310
2311     /* check file header */
2312     offset = 0;
2313     for(;;) {
2314         /* ignore invalid offset */
2315         if ((offset + 8) > (unsigned int)p->buf_size)
2316             return score;
2317         tag = AV_RL32(p->buf + offset + 4);
2318         switch(tag) {
2319         /* check for obvious tags */
2320         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2321         case MKTAG('m','o','o','v'):
2322         case MKTAG('m','d','a','t'):
2323         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2324         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2325         case MKTAG('f','t','y','p'):
2326             return AVPROBE_SCORE_MAX;
2327         /* those are more common words, so rate then a bit less */
2328         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2329         case MKTAG('w','i','d','e'):
2330         case MKTAG('f','r','e','e'):
2331         case MKTAG('j','u','n','k'):
2332         case MKTAG('p','i','c','t'):
2333             return AVPROBE_SCORE_MAX - 5;
2334         case MKTAG(0x82,0x82,0x7f,0x7d):
2335         case MKTAG('s','k','i','p'):
2336         case MKTAG('u','u','i','d'):
2337         case MKTAG('p','r','f','l'):
2338             offset = AV_RB32(p->buf+offset) + offset;
2339             /* if we only find those cause probedata is too small at least rate them */
2340             score = AVPROBE_SCORE_MAX - 50;
2341             break;
2342         default:
2343             /* unrecognized tag */
2344             return score;
2345         }
2346     }
2347 }
2348
2349 // must be done after parsing all trak because there's no order requirement
2350 static void mov_read_chapters(AVFormatContext *s)
2351 {
2352     MOVContext *mov = s->priv_data;
2353     AVStream *st = NULL;
2354     MOVStreamContext *sc;
2355     int64_t cur_pos;
2356     int i;
2357
2358     for (i = 0; i < s->nb_streams; i++)
2359         if (s->streams[i]->id == mov->chapter_track) {
2360             st = s->streams[i];
2361             break;
2362         }
2363     if (!st) {
2364         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2365         return;
2366     }
2367
2368     st->discard = AVDISCARD_ALL;
2369     sc = st->priv_data;
2370     cur_pos = avio_tell(sc->pb);
2371
2372     for (i = 0; i < st->nb_index_entries; i++) {
2373         AVIndexEntry *sample = &st->index_entries[i];
2374         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2375         uint8_t *title;
2376         uint16_t ch;
2377         int len, title_len;
2378
2379         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2380             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2381             goto finish;
2382         }
2383
2384         // the first two bytes are the length of the title
2385         len = avio_rb16(sc->pb);
2386         if (len > sample->size-2)
2387             continue;
2388         title_len = 2*len + 1;
2389         if (!(title = av_mallocz(title_len)))
2390             goto finish;
2391
2392         // The samples could theoretically be in any encoding if there's an encd
2393         // atom following, but in practice are only utf-8 or utf-16, distinguished
2394         // instead by the presence of a BOM
2395         ch = avio_rb16(sc->pb);
2396         if (ch == 0xfeff)
2397             avio_get_str16be(sc->pb, len, title, title_len);
2398         else if (ch == 0xfffe)
2399             avio_get_str16le(sc->pb, len, title, title_len);
2400         else {
2401             AV_WB16(title, ch);
2402             get_strz(sc->pb, title + 2, len - 1);
2403         }
2404
2405         ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2406         av_freep(&title);
2407     }
2408 finish:
2409     avio_seek(sc->pb, cur_pos, SEEK_SET);
2410 }
2411
2412 static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
2413 {
2414     MOVContext *mov = s->priv_data;
2415     AVIOContext *pb = s->pb;
2416     int err;
2417     MOVAtom atom = { AV_RL32("root") };
2418
2419     mov->fc = s;
2420     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2421     if(pb->seekable)
2422         atom.size = avio_size(pb);
2423     else
2424         atom.size = INT64_MAX;
2425
2426     /* check MOV header */
2427     if ((err = mov_read_default(mov, pb, atom)) < 0) {
2428         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2429         return err;
2430     }
2431     if (!mov->found_moov) {
2432         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2433         return -1;
2434     }
2435     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2436
2437     if (pb->seekable && mov->chapter_track > 0)
2438         mov_read_chapters(s);
2439
2440     return 0;
2441 }
2442
2443 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2444 {
2445     AVIndexEntry *sample = NULL;
2446     int64_t best_dts = INT64_MAX;
2447     int i;
2448     for (i = 0; i < s->nb_streams; i++) {
2449         AVStream *avst = s->streams[i];
2450         MOVStreamContext *msc = avst->priv_data;
2451         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2452             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2453             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2454             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2455             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2456                 (s->pb->seekable &&
2457                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2458                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2459                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2460                 sample = current_sample;
2461                 best_dts = dts;
2462                 *st = avst;
2463             }
2464         }
2465     }
2466     return sample;
2467 }
2468
2469 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2470 {
2471     MOVContext *mov = s->priv_data;
2472     MOVStreamContext *sc;
2473     AVIndexEntry *sample;
2474     AVStream *st = NULL;
2475     int ret;
2476  retry:
2477     sample = mov_find_next_sample(s, &st);
2478     if (!sample) {
2479         mov->found_mdat = 0;
2480         if (s->pb->seekable||
2481             mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2482             url_feof(s->pb))
2483             return AVERROR_EOF;
2484         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2485         goto retry;
2486     }
2487     sc = st->priv_data;
2488     /* must be done just before reading, to avoid infinite loop on sample */
2489     sc->current_sample++;
2490
2491     if (st->discard != AVDISCARD_ALL) {
2492         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2493             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2494                    sc->ffindex, sample->pos);
2495             return -1;
2496         }
2497         ret = av_get_packet(sc->pb, pkt, sample->size);
2498         if (ret < 0)
2499             return ret;
2500         if (sc->has_palette) {
2501             uint8_t *pal;
2502
2503             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2504             if (!pal) {
2505                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2506             } else {
2507                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2508                 sc->has_palette = 0;
2509             }
2510         }
2511 #if CONFIG_DV_DEMUXER
2512         if (mov->dv_demux && sc->dv_audio_container) {
2513             dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2514             av_free(pkt->data);
2515             pkt->size = 0;
2516             ret = dv_get_packet(mov->dv_demux, pkt);
2517             if (ret < 0)
2518                 return ret;
2519         }
2520 #endif
2521     }
2522
2523     pkt->stream_index = sc->ffindex;
2524     pkt->dts = sample->timestamp;
2525     if (sc->ctts_data) {
2526         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2527         /* update ctts context */
2528         sc->ctts_sample++;
2529         if (sc->ctts_index < sc->ctts_count &&
2530             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2531             sc->ctts_index++;
2532             sc->ctts_sample = 0;
2533         }
2534         if (sc->wrong_dts)
2535             pkt->dts = AV_NOPTS_VALUE;
2536     } else {
2537         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
2538             st->index_entries[sc->current_sample].timestamp : st->duration;
2539         pkt->duration = next_dts - pkt->dts;
2540         pkt->pts = pkt->dts;
2541     }
2542     if (st->discard == AVDISCARD_ALL)
2543         goto retry;
2544     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
2545     pkt->pos = sample->pos;
2546     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2547             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
2548     return 0;
2549 }
2550
2551 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
2552 {
2553     MOVStreamContext *sc = st->priv_data;
2554     int sample, time_sample;
2555     int i;
2556
2557     sample = av_index_search_timestamp(st, timestamp, flags);
2558     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
2559     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
2560         sample = 0;
2561     if (sample < 0) /* not sure what to do */
2562         return -1;
2563     sc->current_sample = sample;
2564     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
2565     /* adjust ctts index */
2566     if (sc->ctts_data) {
2567         time_sample = 0;
2568         for (i = 0; i < sc->ctts_count; i++) {
2569             int next = time_sample + sc->ctts_data[i].count;
2570             if (next > sc->current_sample) {
2571                 sc->ctts_index = i;
2572                 sc->ctts_sample = sc->current_sample - time_sample;
2573                 break;
2574             }
2575             time_sample = next;
2576         }
2577     }
2578     return sample;
2579 }
2580
2581 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
2582 {
2583     AVStream *st;
2584     int64_t seek_timestamp, timestamp;
2585     int sample;
2586     int i;
2587
2588     if (stream_index >= s->nb_streams)
2589         return -1;
2590     if (sample_time < 0)
2591         sample_time = 0;
2592
2593     st = s->streams[stream_index];
2594     sample = mov_seek_stream(s, st, sample_time, flags);
2595     if (sample < 0)
2596         return -1;
2597
2598     /* adjust seek timestamp to found sample timestamp */
2599     seek_timestamp = st->index_entries[sample].timestamp;
2600
2601     for (i = 0; i < s->nb_streams; i++) {
2602         st = s->streams[i];
2603         if (stream_index == i)
2604             continue;
2605
2606         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2607         mov_seek_stream(s, st, timestamp, flags);
2608     }
2609     return 0;
2610 }
2611
2612 static int mov_read_close(AVFormatContext *s)
2613 {
2614     MOVContext *mov = s->priv_data;
2615     int i, j;
2616
2617     for (i = 0; i < s->nb_streams; i++) {
2618         AVStream *st = s->streams[i];
2619         MOVStreamContext *sc = st->priv_data;
2620
2621         av_freep(&sc->ctts_data);
2622         for (j = 0; j < sc->drefs_count; j++) {
2623             av_freep(&sc->drefs[j].path);
2624             av_freep(&sc->drefs[j].dir);
2625         }
2626         av_freep(&sc->drefs);
2627         if (sc->pb && sc->pb != s->pb)
2628             avio_close(sc->pb);
2629
2630         av_freep(&st->codec->palctrl);
2631     }
2632
2633     if (mov->dv_demux) {
2634         for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
2635             av_freep(&mov->dv_fctx->streams[i]->codec);
2636             av_freep(&mov->dv_fctx->streams[i]);
2637         }
2638         av_freep(&mov->dv_fctx);
2639         av_freep(&mov->dv_demux);
2640     }
2641
2642     av_freep(&mov->trex_data);
2643
2644     return 0;
2645 }
2646
2647 AVInputFormat ff_mov_demuxer = {
2648     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
2649     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
2650     .priv_data_size = sizeof(MOVContext),
2651     .read_probe     = mov_probe,
2652     .read_header    = mov_read_header,
2653     .read_packet    = mov_read_packet,
2654     .read_close     = mov_read_close,
2655     .read_seek      = mov_read_seek,
2656 };