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