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