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