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