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