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