]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / mov.c
1 /*
2  * MOV demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <limits.h>
24
25 //#define DEBUG
26 //#define MOV_EXPORT_ALL_METADATA
27
28 #include "libavutil/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     if (flags & 1) { // floating point
1174         if (flags & 2) { // big endian
1175             if      (bps == 32) return AV_CODEC_ID_PCM_F32BE;
1176             else if (bps == 64) return AV_CODEC_ID_PCM_F64BE;
1177         } else {
1178             if      (bps == 32) return AV_CODEC_ID_PCM_F32LE;
1179             else if (bps == 64) return AV_CODEC_ID_PCM_F64LE;
1180         }
1181     } else {
1182         if (flags & 2) {
1183             if      (bps == 8) {
1184                 // signed integer
1185                 if (flags & 4)  return AV_CODEC_ID_PCM_S8;
1186                 else            return AV_CODEC_ID_PCM_U8;
1187            }else if (bps == 16) return AV_CODEC_ID_PCM_S16BE;
1188             else if (bps == 24) return AV_CODEC_ID_PCM_S24BE;
1189             else if (bps == 32) return AV_CODEC_ID_PCM_S32BE;
1190         } else {
1191             if      (bps == 8) {
1192                 if (flags & 4)  return AV_CODEC_ID_PCM_S8;
1193                 else            return AV_CODEC_ID_PCM_U8;
1194            }else if (bps == 16) return AV_CODEC_ID_PCM_S16LE;
1195             else if (bps == 24) return AV_CODEC_ID_PCM_S24LE;
1196             else if (bps == 32) return AV_CODEC_ID_PCM_S32LE;
1197         }
1198     }
1199     return AV_CODEC_ID_NONE;
1200 }
1201
1202 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1203 {
1204     AVStream *st;
1205     MOVStreamContext *sc;
1206     int j, pseudo_stream_id;
1207
1208     if (c->fc->nb_streams < 1)
1209         return 0;
1210     st = c->fc->streams[c->fc->nb_streams-1];
1211     sc = st->priv_data;
1212
1213     for (pseudo_stream_id = 0;
1214          pseudo_stream_id < entries && !pb->eof_reached;
1215          pseudo_stream_id++) {
1216         //Parsing Sample description table
1217         enum AVCodecID id;
1218         int dref_id = 1;
1219         MOVAtom a = { AV_RL32("stsd") };
1220         int64_t start_pos = avio_tell(pb);
1221         int64_t size = avio_rb32(pb); /* size */
1222         uint32_t format = avio_rl32(pb); /* data format */
1223
1224         if (size >= 16) {
1225             avio_rb32(pb); /* reserved */
1226             avio_rb16(pb); /* reserved */
1227             dref_id = avio_rb16(pb);
1228         }else if (size <= 7){
1229             av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
1230             return AVERROR_INVALIDDATA;
1231         }
1232
1233         if (st->codec->codec_tag &&
1234             st->codec->codec_tag != format &&
1235             (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id
1236                                    : st->codec->codec_tag != MKTAG('j','p','e','g'))
1237            ){
1238             /* Multiple fourcc, we skip JPEG. This is not correct, we should
1239              * export it as a separate AVStream but this needs a few changes
1240              * in the MOV demuxer, patch welcome. */
1241             av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1242             avio_skip(pb, size - (avio_tell(pb) - start_pos));
1243             continue;
1244         }
1245         /* we cannot demux concatenated h264 streams because of different extradata */
1246         if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
1247             av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 might not play corrently.\n");
1248         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
1249         sc->dref_id= dref_id;
1250
1251         st->codec->codec_tag = format;
1252         id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1253         if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1254             id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
1255
1256         if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1257             st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1258         } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
1259                    format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1260             id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1261             if (id <= 0)
1262                 id = ff_codec_get_id(ff_codec_bmp_tags, format);
1263             if (id > 0)
1264                 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1265             else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1266                      (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1267                       st->codec->codec_id == AV_CODEC_ID_NONE)){
1268                 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1269                 if (id > 0)
1270                     st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1271             }
1272         }
1273
1274         av_dlog(c->fc, "size=%"PRId64" 4CC= %c%c%c%c codec_type=%d\n", size,
1275                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
1276                 (format >> 24) & 0xff, st->codec->codec_type);
1277
1278         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
1279             unsigned int color_depth, len;
1280             int color_greyscale;
1281             int color_table_id;
1282
1283             st->codec->codec_id = id;
1284             avio_rb16(pb); /* version */
1285             avio_rb16(pb); /* revision level */
1286             avio_rb32(pb); /* vendor */
1287             avio_rb32(pb); /* temporal quality */
1288             avio_rb32(pb); /* spatial quality */
1289
1290             st->codec->width = avio_rb16(pb); /* width */
1291             st->codec->height = avio_rb16(pb); /* height */
1292
1293             avio_rb32(pb); /* horiz resolution */
1294             avio_rb32(pb); /* vert resolution */
1295             avio_rb32(pb); /* data size, always 0 */
1296             avio_rb16(pb); /* frames per samples */
1297
1298             len = avio_r8(pb); /* codec name, pascal string */
1299             if (len > 31)
1300                 len = 31;
1301             mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
1302             if (len < 31)
1303                 avio_skip(pb, 31 - len);
1304             /* codec_tag YV12 triggers an UV swap in rawdec.c */
1305             if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
1306                 st->codec->codec_tag=MKTAG('I', '4', '2', '0');
1307
1308             st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1309             color_table_id = avio_rb16(pb); /* colortable id */
1310             av_dlog(c->fc, "depth %d, ctab id %d\n",
1311                    st->codec->bits_per_coded_sample, color_table_id);
1312             /* figure out the palette situation */
1313             color_depth = st->codec->bits_per_coded_sample & 0x1F;
1314             color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1315
1316             /* if the depth is 2, 4, or 8 bpp, file is palettized */
1317             if ((color_depth == 2) || (color_depth == 4) ||
1318                 (color_depth == 8)) {
1319                 /* for palette traversal */
1320                 unsigned int color_start, color_count, color_end;
1321                 unsigned char a, r, g, b;
1322
1323                 if (color_greyscale) {
1324                     int color_index, color_dec;
1325                     /* compute the greyscale palette */
1326                     st->codec->bits_per_coded_sample = color_depth;
1327                     color_count = 1 << color_depth;
1328                     color_index = 255;
1329                     color_dec = 256 / (color_count - 1);
1330                     for (j = 0; j < color_count; j++) {
1331                         if (id == AV_CODEC_ID_CINEPAK){
1332                             r = g = b = color_count - 1 - color_index;
1333                         }else
1334                         r = g = b = color_index;
1335                         sc->palette[j] =
1336                             (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1337                         color_index -= color_dec;
1338                         if (color_index < 0)
1339                             color_index = 0;
1340                     }
1341                 } else if (color_table_id) {
1342                     const uint8_t *color_table;
1343                     /* if flag bit 3 is set, use the default palette */
1344                     color_count = 1 << color_depth;
1345                     if (color_depth == 2)
1346                         color_table = ff_qt_default_palette_4;
1347                     else if (color_depth == 4)
1348                         color_table = ff_qt_default_palette_16;
1349                     else
1350                         color_table = ff_qt_default_palette_256;
1351
1352                     for (j = 0; j < color_count; j++) {
1353                         r = color_table[j * 3 + 0];
1354                         g = color_table[j * 3 + 1];
1355                         b = color_table[j * 3 + 2];
1356                         sc->palette[j] =
1357                             (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1358                     }
1359                 } else {
1360                     /* load the palette from the file */
1361                     color_start = avio_rb32(pb);
1362                     color_count = avio_rb16(pb);
1363                     color_end = avio_rb16(pb);
1364                     if ((color_start <= 255) &&
1365                         (color_end <= 255)) {
1366                         for (j = color_start; j <= color_end; j++) {
1367                             /* each A, R, G, or B component is 16 bits;
1368                              * only use the top 8 bits */
1369                             a = avio_r8(pb);
1370                             avio_r8(pb);
1371                             r = avio_r8(pb);
1372                             avio_r8(pb);
1373                             g = avio_r8(pb);
1374                             avio_r8(pb);
1375                             b = avio_r8(pb);
1376                             avio_r8(pb);
1377                             sc->palette[j] =
1378                                 (a << 24 ) | (r << 16) | (g << 8) | (b);
1379                         }
1380                     }
1381                 }
1382                 sc->has_palette = 1;
1383             }
1384         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
1385             int bits_per_sample, flags;
1386             uint16_t version = avio_rb16(pb);
1387
1388             st->codec->codec_id = id;
1389             avio_rb16(pb); /* revision level */
1390             avio_rb32(pb); /* vendor */
1391
1392             st->codec->channels = avio_rb16(pb);             /* channel count */
1393             av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
1394             st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */
1395
1396             sc->audio_cid = avio_rb16(pb);
1397             avio_rb16(pb); /* packet size = 0 */
1398
1399             st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1400
1401             //Read QT version 1 fields. In version 0 these do not exist.
1402             av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
1403             if (!c->isom ||
1404                 strstr(av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE)->value, "qt  ")) {
1405                 if (version==1) {
1406                     sc->samples_per_frame = avio_rb32(pb);
1407                     avio_rb32(pb); /* bytes per packet */
1408                     sc->bytes_per_frame = avio_rb32(pb);
1409                     avio_rb32(pb); /* bytes per sample */
1410                 } else if (version==2) {
1411                     avio_rb32(pb); /* sizeof struct only */
1412                     st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
1413                     st->codec->channels = avio_rb32(pb);
1414                     avio_rb32(pb); /* always 0x7F000000 */
1415                     st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
1416                     flags = avio_rb32(pb); /* lpcm format specific flag */
1417                     sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
1418                     sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
1419                     if (format == MKTAG('l','p','c','m'))
1420                         st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
1421                 }
1422             }
1423
1424             switch (st->codec->codec_id) {
1425             case AV_CODEC_ID_PCM_S8:
1426             case AV_CODEC_ID_PCM_U8:
1427                 if (st->codec->bits_per_coded_sample == 16)
1428                     st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1429                 break;
1430             case AV_CODEC_ID_PCM_S16LE:
1431             case AV_CODEC_ID_PCM_S16BE:
1432                 if (st->codec->bits_per_coded_sample == 8)
1433                     st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1434                 else if (st->codec->bits_per_coded_sample == 24)
1435                     st->codec->codec_id =
1436                         st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1437                         AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1438                 break;
1439             /* set values for old format before stsd version 1 appeared */
1440             case AV_CODEC_ID_MACE3:
1441                 sc->samples_per_frame = 6;
1442                 sc->bytes_per_frame = 2*st->codec->channels;
1443                 break;
1444             case AV_CODEC_ID_MACE6:
1445                 sc->samples_per_frame = 6;
1446                 sc->bytes_per_frame = 1*st->codec->channels;
1447                 break;
1448             case AV_CODEC_ID_ADPCM_IMA_QT:
1449                 sc->samples_per_frame = 64;
1450                 sc->bytes_per_frame = 34*st->codec->channels;
1451                 break;
1452             case AV_CODEC_ID_GSM:
1453                 sc->samples_per_frame = 160;
1454                 sc->bytes_per_frame = 33;
1455                 break;
1456             default:
1457                 break;
1458             }
1459
1460             bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1461             if (bits_per_sample) {
1462                 st->codec->bits_per_coded_sample = bits_per_sample;
1463                 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1464             }
1465         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
1466             // ttxt stsd contains display flags, justification, background
1467             // color, fonts, and default styles, so fake an atom to read it
1468             MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
1469             if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
1470                 mov_read_glbl(c, pb, fake_atom);
1471             st->codec->codec_id= id;
1472             st->codec->width = sc->width;
1473             st->codec->height = sc->height;
1474         } else {
1475             if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1476                 MOVStreamContext *tmcd_ctx = st->priv_data;
1477                 int val;
1478                 avio_rb32(pb);       /* reserved */
1479                 val = avio_rb32(pb); /* flags */
1480                 tmcd_ctx->tmcd_flags = val;
1481                 if (val & 1)
1482                     st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
1483                 avio_rb32(pb); /* time scale */
1484                 avio_rb32(pb); /* frame duration */
1485                 st->codec->time_base.den = avio_r8(pb); /* number of frame */
1486                 st->codec->time_base.num = 1;
1487             }
1488             /* other codec type, just skip (rtp, mp4s, ...) */
1489             avio_skip(pb, size - (avio_tell(pb) - start_pos));
1490         }
1491         /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1492         a.size = size - (avio_tell(pb) - start_pos);
1493         if (a.size > 8) {
1494             int ret;
1495             if ((ret = mov_read_default(c, pb, a)) < 0)
1496                 return ret;
1497         } else if (a.size > 0)
1498             avio_skip(pb, a.size);
1499     }
1500
1501     if (pb->eof_reached)
1502         return AVERROR_EOF;
1503
1504     if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
1505         st->codec->sample_rate= sc->time_scale;
1506
1507     /* special codec parameters handling */
1508     switch (st->codec->codec_id) {
1509 #if CONFIG_DV_DEMUXER
1510     case AV_CODEC_ID_DVAUDIO:
1511         c->dv_fctx = avformat_alloc_context();
1512         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1513         if (!c->dv_demux) {
1514             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1515             return AVERROR(ENOMEM);
1516         }
1517         sc->dv_audio_container = 1;
1518         st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
1519         break;
1520 #endif
1521     /* no ifdef since parameters are always those */
1522     case AV_CODEC_ID_QCELP:
1523         // force sample rate for qcelp when not stored in mov
1524         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1525             st->codec->sample_rate = 8000;
1526         st->codec->channels= 1; /* really needed */
1527         break;
1528     case AV_CODEC_ID_AMR_NB:
1529         st->codec->channels= 1; /* really needed */
1530         /* force sample rate for amr, stsd in 3gp does not store sample rate */
1531         st->codec->sample_rate = 8000;
1532         break;
1533     case AV_CODEC_ID_AMR_WB:
1534         st->codec->channels    = 1;
1535         st->codec->sample_rate = 16000;
1536         break;
1537     case AV_CODEC_ID_MP2:
1538     case AV_CODEC_ID_MP3:
1539         st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
1540         st->need_parsing = AVSTREAM_PARSE_FULL;
1541         break;
1542     case AV_CODEC_ID_GSM:
1543     case AV_CODEC_ID_ADPCM_MS:
1544     case AV_CODEC_ID_ADPCM_IMA_WAV:
1545     case AV_CODEC_ID_ILBC:
1546         st->codec->block_align = sc->bytes_per_frame;
1547         break;
1548     case AV_CODEC_ID_ALAC:
1549         if (st->codec->extradata_size == 36) {
1550             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1551             st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1552         }
1553         break;
1554     case AV_CODEC_ID_AC3:
1555         st->need_parsing = AVSTREAM_PARSE_FULL;
1556         break;
1557     case AV_CODEC_ID_MPEG1VIDEO:
1558         st->need_parsing = AVSTREAM_PARSE_FULL;
1559         break;
1560     case AV_CODEC_ID_VC1:
1561         st->need_parsing = AVSTREAM_PARSE_FULL;
1562         break;
1563     default:
1564         break;
1565     }
1566
1567     return 0;
1568 }
1569
1570 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1571 {
1572     int entries;
1573
1574     avio_r8(pb); /* version */
1575     avio_rb24(pb); /* flags */
1576     entries = avio_rb32(pb);
1577
1578     return ff_mov_read_stsd_entries(c, pb, entries);
1579 }
1580
1581 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1582 {
1583     AVStream *st;
1584     MOVStreamContext *sc;
1585     unsigned int i, entries;
1586
1587     if (c->fc->nb_streams < 1)
1588         return 0;
1589     st = c->fc->streams[c->fc->nb_streams-1];
1590     sc = st->priv_data;
1591
1592     avio_r8(pb); /* version */
1593     avio_rb24(pb); /* flags */
1594
1595     entries = avio_rb32(pb);
1596
1597     av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1598
1599     if (!entries)
1600         return 0;
1601     if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1602         return AVERROR_INVALIDDATA;
1603     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1604     if (!sc->stsc_data)
1605         return AVERROR(ENOMEM);
1606
1607     for (i = 0; i < entries && !pb->eof_reached; i++) {
1608         sc->stsc_data[i].first = avio_rb32(pb);
1609         sc->stsc_data[i].count = avio_rb32(pb);
1610         sc->stsc_data[i].id = avio_rb32(pb);
1611     }
1612
1613     sc->stsc_count = i;
1614
1615     if (pb->eof_reached)
1616         return AVERROR_EOF;
1617
1618     return 0;
1619 }
1620
1621 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1622 {
1623     AVStream *st;
1624     MOVStreamContext *sc;
1625     unsigned i, entries;
1626
1627     if (c->fc->nb_streams < 1)
1628         return 0;
1629     st = c->fc->streams[c->fc->nb_streams-1];
1630     sc = st->priv_data;
1631
1632     avio_rb32(pb); // version + flags
1633
1634     entries = avio_rb32(pb);
1635     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1636         return AVERROR_INVALIDDATA;
1637     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1638     if (!sc->stps_data)
1639         return AVERROR(ENOMEM);
1640
1641     for (i = 0; i < entries && !pb->eof_reached; i++) {
1642         sc->stps_data[i] = avio_rb32(pb);
1643         //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1644     }
1645
1646     sc->stps_count = i;
1647
1648     if (pb->eof_reached)
1649         return AVERROR_EOF;
1650
1651     return 0;
1652 }
1653
1654 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1655 {
1656     AVStream *st;
1657     MOVStreamContext *sc;
1658     unsigned int i, entries;
1659
1660     if (c->fc->nb_streams < 1)
1661         return 0;
1662     st = c->fc->streams[c->fc->nb_streams-1];
1663     sc = st->priv_data;
1664
1665     avio_r8(pb); /* version */
1666     avio_rb24(pb); /* flags */
1667
1668     entries = avio_rb32(pb);
1669
1670     av_dlog(c->fc, "keyframe_count = %d\n", entries);
1671
1672     if (!entries)
1673     {
1674         sc->keyframe_absent = 1;
1675         return 0;
1676     }
1677     if (entries >= UINT_MAX / sizeof(int))
1678         return AVERROR_INVALIDDATA;
1679     sc->keyframes = av_malloc(entries * sizeof(int));
1680     if (!sc->keyframes)
1681         return AVERROR(ENOMEM);
1682
1683     for (i = 0; i < entries && !pb->eof_reached; i++) {
1684         sc->keyframes[i] = avio_rb32(pb);
1685         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1686     }
1687
1688     sc->keyframe_count = i;
1689
1690     if (pb->eof_reached)
1691         return AVERROR_EOF;
1692
1693     return 0;
1694 }
1695
1696 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1697 {
1698     AVStream *st;
1699     MOVStreamContext *sc;
1700     unsigned int i, entries, sample_size, field_size, num_bytes;
1701     GetBitContext gb;
1702     unsigned char* buf;
1703
1704     if (c->fc->nb_streams < 1)
1705         return 0;
1706     st = c->fc->streams[c->fc->nb_streams-1];
1707     sc = st->priv_data;
1708
1709     avio_r8(pb); /* version */
1710     avio_rb24(pb); /* flags */
1711
1712     if (atom.type == MKTAG('s','t','s','z')) {
1713         sample_size = avio_rb32(pb);
1714         if (!sc->sample_size) /* do not overwrite value computed in stsd */
1715             sc->sample_size = sample_size;
1716         sc->alt_sample_size = sample_size;
1717         field_size = 32;
1718     } else {
1719         sample_size = 0;
1720         avio_rb24(pb); /* reserved */
1721         field_size = avio_r8(pb);
1722     }
1723     entries = avio_rb32(pb);
1724
1725     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1726
1727     sc->sample_count = entries;
1728     if (sample_size)
1729         return 0;
1730
1731     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1732         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1733         return AVERROR_INVALIDDATA;
1734     }
1735
1736     if (!entries)
1737         return 0;
1738     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1739         return AVERROR_INVALIDDATA;
1740     sc->sample_sizes = av_malloc(entries * sizeof(int));
1741     if (!sc->sample_sizes)
1742         return AVERROR(ENOMEM);
1743
1744     num_bytes = (entries*field_size+4)>>3;
1745
1746     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1747     if (!buf) {
1748         av_freep(&sc->sample_sizes);
1749         return AVERROR(ENOMEM);
1750     }
1751
1752     if (avio_read(pb, buf, num_bytes) < num_bytes) {
1753         av_freep(&sc->sample_sizes);
1754         av_free(buf);
1755         return AVERROR_INVALIDDATA;
1756     }
1757
1758     init_get_bits(&gb, buf, 8*num_bytes);
1759
1760     for (i = 0; i < entries && !pb->eof_reached; i++) {
1761         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1762         sc->data_size += sc->sample_sizes[i];
1763     }
1764
1765     sc->sample_count = i;
1766
1767     if (pb->eof_reached)
1768         return AVERROR_EOF;
1769
1770     av_free(buf);
1771     return 0;
1772 }
1773
1774 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1775 {
1776     AVStream *st;
1777     MOVStreamContext *sc;
1778     unsigned int i, entries;
1779     int64_t duration=0;
1780     int64_t total_sample_count=0;
1781
1782     if (c->fc->nb_streams < 1)
1783         return 0;
1784     st = c->fc->streams[c->fc->nb_streams-1];
1785     sc = st->priv_data;
1786
1787     avio_r8(pb); /* version */
1788     avio_rb24(pb); /* flags */
1789     entries = avio_rb32(pb);
1790
1791     av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1792             c->fc->nb_streams-1, entries);
1793
1794     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1795         return -1;
1796
1797     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1798     if (!sc->stts_data)
1799         return AVERROR(ENOMEM);
1800
1801     for (i = 0; i < entries && !pb->eof_reached; i++) {
1802         int sample_duration;
1803         int sample_count;
1804
1805         sample_count=avio_rb32(pb);
1806         sample_duration = avio_rb32(pb);
1807         /* sample_duration < 0 is invalid based on the spec */
1808         if (sample_duration < 0) {
1809             av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1810             sample_duration = 1;
1811         }
1812         sc->stts_data[i].count= sample_count;
1813         sc->stts_data[i].duration= sample_duration;
1814
1815         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1816                 sample_count, sample_duration);
1817
1818         duration+=(int64_t)sample_duration*sample_count;
1819         total_sample_count+=sample_count;
1820     }
1821
1822     sc->stts_count = i;
1823
1824     if (pb->eof_reached)
1825         return AVERROR_EOF;
1826
1827     st->nb_frames= total_sample_count;
1828     if (duration)
1829         st->duration= duration;
1830     sc->track_end = duration;
1831     return 0;
1832 }
1833
1834 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1835 {
1836     AVStream *st;
1837     MOVStreamContext *sc;
1838     unsigned int i, entries;
1839
1840     if (c->fc->nb_streams < 1)
1841         return 0;
1842     st = c->fc->streams[c->fc->nb_streams-1];
1843     sc = st->priv_data;
1844
1845     avio_r8(pb); /* version */
1846     avio_rb24(pb); /* flags */
1847     entries = avio_rb32(pb);
1848
1849     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1850
1851     if (!entries)
1852         return 0;
1853     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1854         return AVERROR_INVALIDDATA;
1855     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1856     if (!sc->ctts_data)
1857         return AVERROR(ENOMEM);
1858
1859     for (i = 0; i < entries && !pb->eof_reached; i++) {
1860         int count    =avio_rb32(pb);
1861         int duration =avio_rb32(pb);
1862
1863         sc->ctts_data[i].count   = count;
1864         sc->ctts_data[i].duration= duration;
1865
1866         av_dlog(c->fc, "count=%d, duration=%d\n",
1867                 count, duration);
1868
1869         if (FFABS(duration) > (1<<28) && i+2<entries) {
1870             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1871             av_freep(&sc->ctts_data);
1872             sc->ctts_count = 0;
1873             return 0;
1874         }
1875
1876         if (duration < 0 && i+2<entries)
1877             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1878     }
1879
1880     sc->ctts_count = i;
1881
1882     if (pb->eof_reached)
1883         return AVERROR_EOF;
1884
1885     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1886
1887     return 0;
1888 }
1889
1890 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1891 {
1892     AVStream *st;
1893     MOVStreamContext *sc;
1894     unsigned int i, entries;
1895     uint8_t version;
1896     uint32_t grouping_type;
1897
1898     if (c->fc->nb_streams < 1)
1899         return 0;
1900     st = c->fc->streams[c->fc->nb_streams-1];
1901     sc = st->priv_data;
1902
1903     version = avio_r8(pb); /* version */
1904     avio_rb24(pb); /* flags */
1905     grouping_type = avio_rl32(pb);
1906     if (grouping_type != MKTAG( 'r','a','p',' '))
1907         return 0; /* only support 'rap ' grouping */
1908     if (version == 1)
1909         avio_rb32(pb); /* grouping_type_parameter */
1910
1911     entries = avio_rb32(pb);
1912     if (!entries)
1913         return 0;
1914     if (entries >= UINT_MAX / sizeof(*sc->rap_group))
1915         return AVERROR_INVALIDDATA;
1916     sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
1917     if (!sc->rap_group)
1918         return AVERROR(ENOMEM);
1919
1920     for (i = 0; i < entries && !pb->eof_reached; i++) {
1921         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
1922         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
1923     }
1924
1925     sc->rap_group_count = i;
1926
1927     return pb->eof_reached ? AVERROR_EOF : 0;
1928 }
1929
1930 static void mov_build_index(MOVContext *mov, AVStream *st)
1931 {
1932     MOVStreamContext *sc = st->priv_data;
1933     int64_t current_offset;
1934     int64_t current_dts = 0;
1935     unsigned int stts_index = 0;
1936     unsigned int stsc_index = 0;
1937     unsigned int stss_index = 0;
1938     unsigned int stps_index = 0;
1939     unsigned int i, j;
1940     uint64_t stream_size = 0;
1941     AVIndexEntry *mem;
1942
1943     /* adjust first dts according to edit list */
1944     if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1945         if (sc->empty_duration)
1946             sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1947         sc->time_offset = sc->start_time - sc->empty_duration;
1948         current_dts = -sc->time_offset;
1949         if (sc->ctts_count>0 && sc->stts_count>0 &&
1950             sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1951             /* more than 16 frames delay, dts are likely wrong
1952                this happens with files created by iMovie */
1953             sc->wrong_dts = 1;
1954             st->codec->has_b_frames = 1;
1955         }
1956     }
1957
1958     /* only use old uncompressed audio chunk demuxing when stts specifies it */
1959     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1960           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1961         unsigned int current_sample = 0;
1962         unsigned int stts_sample = 0;
1963         unsigned int sample_size;
1964         unsigned int distance = 0;
1965         unsigned int rap_group_index = 0;
1966         unsigned int rap_group_sample = 0;
1967         int rap_group_present = sc->rap_group_count && sc->rap_group;
1968         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
1969
1970         current_dts -= sc->dts_shift;
1971
1972         if (!sc->sample_count || st->nb_index_entries)
1973             return;
1974         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1975             return;
1976         mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1977         if (!mem)
1978             return;
1979         st->index_entries = mem;
1980         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1981
1982         for (i = 0; i < sc->chunk_count; i++) {
1983             current_offset = sc->chunk_offsets[i];
1984             while (stsc_index + 1 < sc->stsc_count &&
1985                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1986                 stsc_index++;
1987             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1988                 int keyframe = 0;
1989                 if (current_sample >= sc->sample_count) {
1990                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1991                     return;
1992                 }
1993
1994                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1995                     keyframe = 1;
1996                     if (stss_index + 1 < sc->keyframe_count)
1997                         stss_index++;
1998                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1999                     keyframe = 1;
2000                     if (stps_index + 1 < sc->stps_count)
2001                         stps_index++;
2002                 }
2003                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2004                     if (sc->rap_group[rap_group_index].index > 0)
2005                         keyframe = 1;
2006                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2007                         rap_group_sample = 0;
2008                         rap_group_index++;
2009                     }
2010                 }
2011                 if (keyframe)
2012                     distance = 0;
2013                 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
2014                 if (sc->pseudo_stream_id == -1 ||
2015                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2016                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2017                     e->pos = current_offset;
2018                     e->timestamp = current_dts;
2019                     e->size = sample_size;
2020                     e->min_distance = distance;
2021                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2022                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2023                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2024                             current_offset, current_dts, sample_size, distance, keyframe);
2025                 }
2026
2027                 current_offset += sample_size;
2028                 stream_size += sample_size;
2029                 current_dts += sc->stts_data[stts_index].duration;
2030                 distance++;
2031                 stts_sample++;
2032                 current_sample++;
2033                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2034                     stts_sample = 0;
2035                     stts_index++;
2036                 }
2037             }
2038         }
2039         if (st->duration > 0)
2040             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2041     } else {
2042         unsigned chunk_samples, total = 0;
2043
2044         // compute total chunk count
2045         for (i = 0; i < sc->stsc_count; i++) {
2046             unsigned count, chunk_count;
2047
2048             chunk_samples = sc->stsc_data[i].count;
2049             if (i != sc->stsc_count - 1 &&
2050                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2051                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2052                 return;
2053             }
2054
2055             if (sc->samples_per_frame >= 160) { // gsm
2056                 count = chunk_samples / sc->samples_per_frame;
2057             } else if (sc->samples_per_frame > 1) {
2058                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2059                 count = (chunk_samples+samples-1) / samples;
2060             } else {
2061                 count = (chunk_samples+1023) / 1024;
2062             }
2063
2064             if (i < sc->stsc_count - 1)
2065                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2066             else
2067                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2068             total += chunk_count * count;
2069         }
2070
2071         av_dlog(mov->fc, "chunk count %d\n", total);
2072         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2073             return;
2074         mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
2075         if (!mem)
2076             return;
2077         st->index_entries = mem;
2078         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2079
2080         // populate index
2081         for (i = 0; i < sc->chunk_count; i++) {
2082             current_offset = sc->chunk_offsets[i];
2083             if (stsc_index + 1 < sc->stsc_count &&
2084                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2085                 stsc_index++;
2086             chunk_samples = sc->stsc_data[stsc_index].count;
2087
2088             while (chunk_samples > 0) {
2089                 AVIndexEntry *e;
2090                 unsigned size, samples;
2091
2092                 if (sc->samples_per_frame >= 160) { // gsm
2093                     samples = sc->samples_per_frame;
2094                     size = sc->bytes_per_frame;
2095                 } else {
2096                     if (sc->samples_per_frame > 1) {
2097                         samples = FFMIN((1024 / sc->samples_per_frame)*
2098                                         sc->samples_per_frame, chunk_samples);
2099                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2100                     } else {
2101                         samples = FFMIN(1024, chunk_samples);
2102                         size = samples * sc->sample_size;
2103                     }
2104                 }
2105
2106                 if (st->nb_index_entries >= total) {
2107                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2108                     return;
2109                 }
2110                 e = &st->index_entries[st->nb_index_entries++];
2111                 e->pos = current_offset;
2112                 e->timestamp = current_dts;
2113                 e->size = size;
2114                 e->min_distance = 0;
2115                 e->flags = AVINDEX_KEYFRAME;
2116                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2117                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2118                         size, samples);
2119
2120                 current_offset += size;
2121                 current_dts += samples;
2122                 chunk_samples -= samples;
2123             }
2124         }
2125     }
2126 }
2127
2128 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2129                          AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2130 {
2131     /* try relative path, we do not try the absolute because it can leak information about our
2132        system to an attacker */
2133     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2134         char filename[1024];
2135         const char *src_path;
2136         int i, l;
2137
2138         /* find a source dir */
2139         src_path = strrchr(src, '/');
2140         if (src_path)
2141             src_path++;
2142         else
2143             src_path = src;
2144
2145         /* find a next level down to target */
2146         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2147             if (ref->path[l] == '/') {
2148                 if (i == ref->nlvl_to - 1)
2149                     break;
2150                 else
2151                     i++;
2152             }
2153
2154         /* compose filename if next level down to target was found */
2155         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
2156             memcpy(filename, src, src_path - src);
2157             filename[src_path - src] = 0;
2158
2159             for (i = 1; i < ref->nlvl_from; i++)
2160                 av_strlcat(filename, "../", 1024);
2161
2162             av_strlcat(filename, ref->path + l + 1, 1024);
2163
2164             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2165                 return 0;
2166         }
2167     } else if (use_absolute_path) {
2168         av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2169                "this is a possible security issue\n");
2170         if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2171             return 0;
2172     }
2173
2174     return AVERROR(ENOENT);
2175 }
2176
2177 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2178 {
2179     if (sc->time_scale <= 0) {
2180         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2181         sc->time_scale = c->time_scale;
2182         if (sc->time_scale <= 0)
2183             sc->time_scale = 1;
2184     }
2185 }
2186
2187 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2188 {
2189     AVStream *st;
2190     MOVStreamContext *sc;
2191     int ret;
2192
2193     st = avformat_new_stream(c->fc, NULL);
2194     if (!st) return AVERROR(ENOMEM);
2195     st->id = c->fc->nb_streams;
2196     sc = av_mallocz(sizeof(MOVStreamContext));
2197     if (!sc) return AVERROR(ENOMEM);
2198
2199     st->priv_data = sc;
2200     st->codec->codec_type = AVMEDIA_TYPE_DATA;
2201     sc->ffindex = st->index;
2202
2203     if ((ret = mov_read_default(c, pb, atom)) < 0)
2204         return ret;
2205
2206     /* sanity checks */
2207     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2208                             (!sc->sample_size && !sc->sample_count))) {
2209         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2210                st->index);
2211         return 0;
2212     }
2213
2214     fix_timescale(c, sc);
2215
2216     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2217
2218     mov_build_index(c, st);
2219
2220     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2221         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2222         if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2223             c->use_absolute_path, c->fc) < 0)
2224             av_log(c->fc, AV_LOG_ERROR,
2225                    "stream %d, error opening alias: path='%s', dir='%s', "
2226                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2227                    st->index, dref->path, dref->dir, dref->filename,
2228                    dref->volume, dref->nlvl_from, dref->nlvl_to);
2229     } else
2230         sc->pb = c->fc->pb;
2231
2232     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2233         if (!st->sample_aspect_ratio.num &&
2234             (st->codec->width != sc->width || st->codec->height != sc->height)) {
2235             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2236                                              ((double)st->codec->width * sc->height), INT_MAX);
2237         }
2238
2239         if (st->duration > 0)
2240             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2241                     sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2242
2243 #if FF_API_R_FRAME_RATE
2244         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2245             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2246                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2247 #endif
2248     }
2249
2250     switch (st->codec->codec_id) {
2251 #if CONFIG_H261_DECODER
2252     case AV_CODEC_ID_H261:
2253 #endif
2254 #if CONFIG_H263_DECODER
2255     case AV_CODEC_ID_H263:
2256 #endif
2257 #if CONFIG_MPEG4_DECODER
2258     case AV_CODEC_ID_MPEG4:
2259 #endif
2260         st->codec->width = 0; /* let decoder init width/height */
2261         st->codec->height= 0;
2262         break;
2263     }
2264
2265     /* Do not need those anymore. */
2266     av_freep(&sc->chunk_offsets);
2267     av_freep(&sc->stsc_data);
2268     av_freep(&sc->sample_sizes);
2269     av_freep(&sc->keyframes);
2270     av_freep(&sc->stts_data);
2271     av_freep(&sc->stps_data);
2272     av_freep(&sc->rap_group);
2273
2274     return 0;
2275 }
2276
2277 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2278 {
2279     int ret;
2280     c->itunes_metadata = 1;
2281     ret = mov_read_default(c, pb, atom);
2282     c->itunes_metadata = 0;
2283     return ret;
2284 }
2285
2286 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2287 {
2288     while (atom.size > 8) {
2289         uint32_t tag = avio_rl32(pb);
2290         atom.size -= 4;
2291         if (tag == MKTAG('h','d','l','r')) {
2292             avio_seek(pb, -8, SEEK_CUR);
2293             atom.size += 8;
2294             return mov_read_default(c, pb, atom);
2295         }
2296     }
2297     return 0;
2298 }
2299
2300 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2301 {
2302     int i;
2303     int width;
2304     int height;
2305     int64_t disp_transform[2];
2306     int display_matrix[3][2];
2307     AVStream *st;
2308     MOVStreamContext *sc;
2309     int version;
2310
2311     if (c->fc->nb_streams < 1)
2312         return 0;
2313     st = c->fc->streams[c->fc->nb_streams-1];
2314     sc = st->priv_data;
2315
2316     version = avio_r8(pb);
2317     avio_rb24(pb); /* flags */
2318     /*
2319     MOV_TRACK_ENABLED 0x0001
2320     MOV_TRACK_IN_MOVIE 0x0002
2321     MOV_TRACK_IN_PREVIEW 0x0004
2322     MOV_TRACK_IN_POSTER 0x0008
2323     */
2324
2325     if (version == 1) {
2326         avio_rb64(pb);
2327         avio_rb64(pb);
2328     } else {
2329         avio_rb32(pb); /* creation time */
2330         avio_rb32(pb); /* modification time */
2331     }
2332     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2333     avio_rb32(pb); /* reserved */
2334
2335     /* highlevel (considering edits) duration in movie timebase */
2336     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2337     avio_rb32(pb); /* reserved */
2338     avio_rb32(pb); /* reserved */
2339
2340     avio_rb16(pb); /* layer */
2341     avio_rb16(pb); /* alternate group */
2342     avio_rb16(pb); /* volume */
2343     avio_rb16(pb); /* reserved */
2344
2345     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2346     // they're kept in fixed point format through all calculations
2347     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2348     for (i = 0; i < 3; i++) {
2349         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
2350         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
2351         avio_rb32(pb);           // 2.30 fixed point (not used)
2352     }
2353
2354     width = avio_rb32(pb);       // 16.16 fixed point track width
2355     height = avio_rb32(pb);      // 16.16 fixed point track height
2356     sc->width = width >> 16;
2357     sc->height = height >> 16;
2358
2359     //Assign clockwise rotate values based on transform matrix so that
2360     //we can compensate for iPhone orientation during capture.
2361
2362     if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2363          av_dict_set(&st->metadata, "rotate", "90", 0);
2364     }
2365
2366     if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2367          av_dict_set(&st->metadata, "rotate", "180", 0);
2368     }
2369
2370     if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2371          av_dict_set(&st->metadata, "rotate", "270", 0);
2372     }
2373
2374     // transform the display width/height according to the matrix
2375     // skip this if the display matrix is the default identity matrix
2376     // or if it is rotating the picture, ex iPhone 3GS
2377     // to keep the same scale, use [width height 1<<16]
2378     if (width && height &&
2379         ((display_matrix[0][0] != 65536  ||
2380           display_matrix[1][1] != 65536) &&
2381          !display_matrix[0][1] &&
2382          !display_matrix[1][0] &&
2383          !display_matrix[2][0] && !display_matrix[2][1])) {
2384         for (i = 0; i < 2; i++)
2385             disp_transform[i] =
2386                 (int64_t)  width  * display_matrix[0][i] +
2387                 (int64_t)  height * display_matrix[1][i] +
2388                 ((int64_t) display_matrix[2][i] << 16);
2389
2390         //sample aspect ratio is new width/height divided by old width/height
2391         st->sample_aspect_ratio = av_d2q(
2392             ((double) disp_transform[0] * height) /
2393             ((double) disp_transform[1] * width), INT_MAX);
2394     }
2395     return 0;
2396 }
2397
2398 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2399 {
2400     MOVFragment *frag = &c->fragment;
2401     MOVTrackExt *trex = NULL;
2402     int flags, track_id, i;
2403
2404     avio_r8(pb); /* version */
2405     flags = avio_rb24(pb);
2406
2407     track_id = avio_rb32(pb);
2408     if (!track_id)
2409         return AVERROR_INVALIDDATA;
2410     frag->track_id = track_id;
2411     for (i = 0; i < c->trex_count; i++)
2412         if (c->trex_data[i].track_id == frag->track_id) {
2413             trex = &c->trex_data[i];
2414             break;
2415         }
2416     if (!trex) {
2417         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2418         return AVERROR_INVALIDDATA;
2419     }
2420
2421     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2422                              avio_rb64(pb) : frag->moof_offset;
2423     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2424
2425     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2426                      avio_rb32(pb) : trex->duration;
2427     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
2428                      avio_rb32(pb) : trex->size;
2429     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
2430                      avio_rb32(pb) : trex->flags;
2431     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2432     return 0;
2433 }
2434
2435 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2436 {
2437     c->chapter_track = avio_rb32(pb);
2438     return 0;
2439 }
2440
2441 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2442 {
2443     MOVTrackExt *trex;
2444
2445     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2446         return AVERROR_INVALIDDATA;
2447     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2448     if (!trex)
2449         return AVERROR(ENOMEM);
2450
2451     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2452
2453     c->trex_data = trex;
2454     trex = &c->trex_data[c->trex_count++];
2455     avio_r8(pb); /* version */
2456     avio_rb24(pb); /* flags */
2457     trex->track_id = avio_rb32(pb);
2458     trex->stsd_id  = avio_rb32(pb);
2459     trex->duration = avio_rb32(pb);
2460     trex->size     = avio_rb32(pb);
2461     trex->flags    = avio_rb32(pb);
2462     return 0;
2463 }
2464
2465 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2466 {
2467     MOVFragment *frag = &c->fragment;
2468     AVStream *st = NULL;
2469     MOVStreamContext *sc;
2470     MOVStts *ctts_data;
2471     uint64_t offset;
2472     int64_t dts;
2473     int data_offset = 0;
2474     unsigned entries, first_sample_flags = frag->flags;
2475     int flags, distance, i, found_keyframe = 0;
2476
2477     for (i = 0; i < c->fc->nb_streams; i++) {
2478         if (c->fc->streams[i]->id == frag->track_id) {
2479             st = c->fc->streams[i];
2480             break;
2481         }
2482     }
2483     if (!st) {
2484         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2485         return AVERROR_INVALIDDATA;
2486     }
2487     sc = st->priv_data;
2488     if (sc->pseudo_stream_id+1 != frag->stsd_id)
2489         return 0;
2490     avio_r8(pb); /* version */
2491     flags = avio_rb24(pb);
2492     entries = avio_rb32(pb);
2493     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2494
2495     /* Always assume the presence of composition time offsets.
2496      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2497      *  1) in the initial movie, there are no samples.
2498      *  2) in the first movie fragment, there is only one sample without composition time offset.
2499      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
2500     if (!sc->ctts_count && sc->sample_count)
2501     {
2502         /* Complement ctts table if moov atom doesn't have ctts atom. */
2503         ctts_data = av_malloc(sizeof(*sc->ctts_data));
2504         if (!ctts_data)
2505             return AVERROR(ENOMEM);
2506         sc->ctts_data = ctts_data;
2507         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2508         sc->ctts_data[sc->ctts_count].duration = 0;
2509         sc->ctts_count++;
2510     }
2511     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2512         return AVERROR_INVALIDDATA;
2513     ctts_data = av_realloc(sc->ctts_data,
2514                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2515     if (!ctts_data)
2516         return AVERROR(ENOMEM);
2517     sc->ctts_data = ctts_data;
2518
2519     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
2520     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2521     dts    = sc->track_end - sc->time_offset;
2522     offset = frag->base_data_offset + data_offset;
2523     distance = 0;
2524     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2525     for (i = 0; i < entries && !pb->eof_reached; i++) {
2526         unsigned sample_size = frag->size;
2527         int sample_flags = i ? frag->flags : first_sample_flags;
2528         unsigned sample_duration = frag->duration;
2529         int keyframe = 0;
2530
2531         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2532         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
2533         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
2534         sc->ctts_data[sc->ctts_count].count = 1;
2535         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2536                                                   avio_rb32(pb) : 0;
2537         sc->ctts_count++;
2538         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2539             keyframe = 1;
2540         else if (!found_keyframe)
2541             keyframe = found_keyframe =
2542                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2543                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2544         if (keyframe)
2545             distance = 0;
2546         av_add_index_entry(st, offset, dts, sample_size, distance,
2547                            keyframe ? AVINDEX_KEYFRAME : 0);
2548         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2549                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2550                 offset, dts, sample_size, distance, keyframe);
2551         distance++;
2552         dts += sample_duration;
2553         offset += sample_size;
2554         sc->data_size += sample_size;
2555     }
2556
2557     if (pb->eof_reached)
2558         return AVERROR_EOF;
2559
2560     frag->moof_offset = offset;
2561     st->duration = sc->track_end = dts + sc->time_offset;
2562     return 0;
2563 }
2564
2565 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2566 /* like the files created with Adobe Premiere 5.0, for samples see */
2567 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2568 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2569 {
2570     int err;
2571
2572     if (atom.size < 8)
2573         return 0; /* continue */
2574     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2575         avio_skip(pb, atom.size - 4);
2576         return 0;
2577     }
2578     atom.type = avio_rl32(pb);
2579     atom.size -= 8;
2580     if (atom.type != MKTAG('m','d','a','t')) {
2581         avio_skip(pb, atom.size);
2582         return 0;
2583     }
2584     err = mov_read_mdat(c, pb, atom);
2585     return err;
2586 }
2587
2588 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2589 {
2590 #if CONFIG_ZLIB
2591     AVIOContext ctx;
2592     uint8_t *cmov_data;
2593     uint8_t *moov_data; /* uncompressed data */
2594     long cmov_len, moov_len;
2595     int ret = -1;
2596
2597     avio_rb32(pb); /* dcom atom */
2598     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2599         return AVERROR_INVALIDDATA;
2600     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2601         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
2602         return AVERROR_INVALIDDATA;
2603     }
2604     avio_rb32(pb); /* cmvd atom */
2605     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2606         return AVERROR_INVALIDDATA;
2607     moov_len = avio_rb32(pb); /* uncompressed size */
2608     cmov_len = atom.size - 6 * 4;
2609
2610     cmov_data = av_malloc(cmov_len);
2611     if (!cmov_data)
2612         return AVERROR(ENOMEM);
2613     moov_data = av_malloc(moov_len);
2614     if (!moov_data) {
2615         av_free(cmov_data);
2616         return AVERROR(ENOMEM);
2617     }
2618     avio_read(pb, cmov_data, cmov_len);
2619     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2620         goto free_and_return;
2621     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2622         goto free_and_return;
2623     atom.type = MKTAG('m','o','o','v');
2624     atom.size = moov_len;
2625     ret = mov_read_default(c, &ctx, atom);
2626 free_and_return:
2627     av_free(moov_data);
2628     av_free(cmov_data);
2629     return ret;
2630 #else
2631     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2632     return AVERROR(ENOSYS);
2633 #endif
2634 }
2635
2636 /* edit list atom */
2637 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2638 {
2639     MOVStreamContext *sc;
2640     int i, edit_count, version, edit_start_index = 0;
2641     int unsupported = 0;
2642
2643     if (c->fc->nb_streams < 1 || c->ignore_editlist)
2644         return 0;
2645     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2646
2647     version = avio_r8(pb); /* version */
2648     avio_rb24(pb); /* flags */
2649     edit_count = avio_rb32(pb); /* entries */
2650
2651     if ((uint64_t)edit_count*12+8 > atom.size)
2652         return AVERROR_INVALIDDATA;
2653
2654     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2655     for (i=0; i<edit_count; i++){
2656         int64_t time;
2657         int64_t duration;
2658         int rate;
2659         if (version == 1) {
2660             duration = avio_rb64(pb);
2661             time     = avio_rb64(pb);
2662         } else {
2663             duration = avio_rb32(pb); /* segment duration */
2664             time     = (int32_t)avio_rb32(pb); /* media time */
2665         }
2666         rate = avio_rb32(pb);
2667         if (i == 0 && time == -1) {
2668             sc->empty_duration = duration;
2669             edit_start_index = 1;
2670         } else if (i == edit_start_index && time >= 0)
2671             sc->start_time = time;
2672         else
2673             unsupported = 1;
2674
2675         av_dlog(c->fc, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
2676                 duration, time, rate / 65536.0);
2677     }
2678
2679     if (unsupported)
2680         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2681                "a/v desync might occur, patch welcome\n");
2682
2683     return 0;
2684 }
2685
2686 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2687 {
2688     if (atom.size < 16)
2689         return 0;
2690     avio_skip(pb, 4);
2691     ff_mov_read_chan(c->fc, pb, c->fc->streams[0],  atom.size - 4);
2692     return 0;
2693 }
2694
2695 static int mov_read_tref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2696 {
2697     uint32_t i, size;
2698     MOVStreamContext *sc;
2699
2700     if (c->fc->nb_streams < 1)
2701         return AVERROR_INVALIDDATA;
2702     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
2703
2704     size = avio_rb32(pb);
2705     if (size < 12)
2706         return 0;
2707
2708     sc->trefs_count = (size - 4) / 8;
2709     sc->trefs = av_malloc(sc->trefs_count * sizeof(*sc->trefs));
2710     if (!sc->trefs)
2711         return AVERROR(ENOMEM);
2712
2713     sc->tref_type = avio_rl32(pb);
2714     for (i = 0; i < sc->trefs_count; i++)
2715         sc->trefs[i] = avio_rb32(pb);
2716     return 0;
2717 }
2718
2719 static const MOVParseTableEntry mov_default_parse_table[] = {
2720 { MKTAG('A','C','L','R'), mov_read_avid },
2721 { MKTAG('A','P','R','G'), mov_read_avid },
2722 { MKTAG('A','A','L','P'), mov_read_avid },
2723 { MKTAG('A','R','E','S'), mov_read_avid },
2724 { MKTAG('a','v','s','s'), mov_read_avss },
2725 { MKTAG('c','h','p','l'), mov_read_chpl },
2726 { MKTAG('c','o','6','4'), mov_read_stco },
2727 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2728 { MKTAG('d','i','n','f'), mov_read_default },
2729 { MKTAG('d','r','e','f'), mov_read_dref },
2730 { MKTAG('e','d','t','s'), mov_read_default },
2731 { MKTAG('e','l','s','t'), mov_read_elst },
2732 { MKTAG('e','n','d','a'), mov_read_enda },
2733 { MKTAG('f','i','e','l'), mov_read_fiel },
2734 { MKTAG('f','t','y','p'), mov_read_ftyp },
2735 { MKTAG('g','l','b','l'), mov_read_glbl },
2736 { MKTAG('h','d','l','r'), mov_read_hdlr },
2737 { MKTAG('i','l','s','t'), mov_read_ilst },
2738 { MKTAG('j','p','2','h'), mov_read_jp2h },
2739 { MKTAG('m','d','a','t'), mov_read_mdat },
2740 { MKTAG('m','d','h','d'), mov_read_mdhd },
2741 { MKTAG('m','d','i','a'), mov_read_default },
2742 { MKTAG('m','e','t','a'), mov_read_meta },
2743 { MKTAG('m','i','n','f'), mov_read_default },
2744 { MKTAG('m','o','o','f'), mov_read_moof },
2745 { MKTAG('m','o','o','v'), mov_read_moov },
2746 { MKTAG('m','v','e','x'), mov_read_default },
2747 { MKTAG('m','v','h','d'), mov_read_mvhd },
2748 { MKTAG('S','M','I',' '), mov_read_svq3 },
2749 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2750 { MKTAG('a','v','c','C'), mov_read_glbl },
2751 { MKTAG('p','a','s','p'), mov_read_pasp },
2752 { MKTAG('s','t','b','l'), mov_read_default },
2753 { MKTAG('s','t','c','o'), mov_read_stco },
2754 { MKTAG('s','t','p','s'), mov_read_stps },
2755 { MKTAG('s','t','r','f'), mov_read_strf },
2756 { MKTAG('s','t','s','c'), mov_read_stsc },
2757 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2758 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2759 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2760 { MKTAG('s','t','t','s'), mov_read_stts },
2761 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2762 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2763 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2764 { MKTAG('t','r','a','k'), mov_read_trak },
2765 { MKTAG('t','r','a','f'), mov_read_default },
2766 { MKTAG('t','r','e','f'), mov_read_tref },
2767 { MKTAG('c','h','a','p'), mov_read_chap },
2768 { MKTAG('t','r','e','x'), mov_read_trex },
2769 { MKTAG('t','r','u','n'), mov_read_trun },
2770 { MKTAG('u','d','t','a'), mov_read_default },
2771 { MKTAG('w','a','v','e'), mov_read_wave },
2772 { MKTAG('e','s','d','s'), mov_read_esds },
2773 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2774 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2775 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2776 { MKTAG('w','f','e','x'), mov_read_wfex },
2777 { MKTAG('c','m','o','v'), mov_read_cmov },
2778 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2779 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2780 { MKTAG('s','b','g','p'), mov_read_sbgp },
2781 { 0, NULL }
2782 };
2783
2784 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2785 {
2786     int64_t total_size = 0;
2787     MOVAtom a;
2788     int i;
2789
2790     if (atom.size < 0)
2791         atom.size = INT64_MAX;
2792     while (total_size + 8 <= atom.size && !url_feof(pb)) {
2793         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
2794         a.size = atom.size;
2795         a.type=0;
2796         if (atom.size >= 8) {
2797             a.size = avio_rb32(pb);
2798             a.type = avio_rl32(pb);
2799             if (atom.type != MKTAG('r','o','o','t') &&
2800                 atom.type != MKTAG('m','o','o','v'))
2801             {
2802                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
2803                 {
2804                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
2805                     avio_skip(pb, -8);
2806                     return 0;
2807                 }
2808             }
2809             total_size += 8;
2810             if (a.size == 1) { /* 64 bit extended size */
2811                 a.size = avio_rb64(pb) - 8;
2812                 total_size += 8;
2813             }
2814         }
2815         av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
2816                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
2817         if (a.size == 0) {
2818             a.size = atom.size - total_size + 8;
2819         }
2820         a.size -= 8;
2821         if (a.size < 0)
2822             break;
2823         a.size = FFMIN(a.size, atom.size - total_size);
2824
2825         for (i = 0; mov_default_parse_table[i].type; i++)
2826             if (mov_default_parse_table[i].type == a.type) {
2827                 parse = mov_default_parse_table[i].parse;
2828                 break;
2829             }
2830
2831         // container is user data
2832         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
2833                        atom.type == MKTAG('i','l','s','t')))
2834             parse = mov_read_udta_string;
2835
2836         if (!parse) { /* skip leaf atoms data */
2837             avio_skip(pb, a.size);
2838         } else {
2839             int64_t start_pos = avio_tell(pb);
2840             int64_t left;
2841             int err = parse(c, pb, a);
2842             if (err < 0)
2843                 return err;
2844             if (c->found_moov && c->found_mdat &&
2845                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
2846                  start_pos + a.size == avio_size(pb))) {
2847                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
2848                     c->next_root_atom = start_pos + a.size;
2849                 return 0;
2850             }
2851             left = a.size - avio_tell(pb) + start_pos;
2852             if (left > 0) /* skip garbage at atom end */
2853                 avio_skip(pb, left);
2854             else if(left < 0) {
2855                 av_log(c->fc, AV_LOG_DEBUG, "undoing overread of %"PRId64" in '%.4s'\n", -left, (char*)&a.type);
2856                 avio_seek(pb, left, SEEK_CUR);
2857             }
2858         }
2859
2860         total_size += a.size;
2861     }
2862
2863     if (total_size < atom.size && atom.size < 0x7ffff)
2864         avio_skip(pb, atom.size - total_size);
2865
2866     return 0;
2867 }
2868
2869 static int mov_probe(AVProbeData *p)
2870 {
2871     int64_t offset;
2872     uint32_t tag;
2873     int score = 0;
2874     int moov_offset = -1;
2875
2876     /* check file header */
2877     offset = 0;
2878     for (;;) {
2879         /* ignore invalid offset */
2880         if ((offset + 8) > (unsigned int)p->buf_size)
2881             break;
2882         tag = AV_RL32(p->buf + offset + 4);
2883         switch(tag) {
2884         /* check for obvious tags */
2885         case MKTAG('m','o','o','v'):
2886             moov_offset = offset + 4;
2887         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2888         case MKTAG('m','d','a','t'):
2889         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2890         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2891         case MKTAG('f','t','y','p'):
2892             if (AV_RB32(p->buf+offset) < 8 &&
2893                 (AV_RB32(p->buf+offset) != 1 ||
2894                  offset + 12 > (unsigned int)p->buf_size ||
2895                  AV_RB64(p->buf+offset + 8) == 0)) {
2896                 score = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2897             } else {
2898                 score = AVPROBE_SCORE_MAX;
2899             }
2900             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2901             break;
2902         /* those are more common words, so rate then a bit less */
2903         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2904         case MKTAG('w','i','d','e'):
2905         case MKTAG('f','r','e','e'):
2906         case MKTAG('j','u','n','k'):
2907         case MKTAG('p','i','c','t'):
2908             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
2909             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2910             break;
2911         case MKTAG(0x82,0x82,0x7f,0x7d):
2912         case MKTAG('s','k','i','p'):
2913         case MKTAG('u','u','i','d'):
2914         case MKTAG('p','r','f','l'):
2915             /* if we only find those cause probedata is too small at least rate them */
2916             score  = FFMAX(score, AVPROBE_SCORE_MAX - 50);
2917             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2918             break;
2919         default:
2920             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
2921         }
2922     }
2923     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
2924         /* moov atom in the header - we should make sure that this is not a
2925          * MOV-packed MPEG-PS */
2926         offset = moov_offset;
2927
2928         while(offset < (p->buf_size - 16)){ /* Sufficient space */
2929                /* We found an actual hdlr atom */
2930             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
2931                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
2932                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
2933                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
2934                 /* We found a media handler reference atom describing an
2935                  * MPEG-PS-in-MOV, return a
2936                  * low score to force expanding the probe window until
2937                  * mpegps_probe finds what it needs */
2938                 return 5;
2939             }else
2940                 /* Keep looking */
2941                 offset+=2;
2942         }
2943     }
2944
2945     return score;
2946 }
2947
2948 // must be done after parsing all trak because there's no order requirement
2949 static void mov_read_chapters(AVFormatContext *s)
2950 {
2951     MOVContext *mov = s->priv_data;
2952     AVStream *st = NULL;
2953     MOVStreamContext *sc;
2954     int64_t cur_pos;
2955     int i;
2956
2957     for (i = 0; i < s->nb_streams; i++)
2958         if (s->streams[i]->id == mov->chapter_track) {
2959             st = s->streams[i];
2960             break;
2961         }
2962     if (!st) {
2963         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2964         return;
2965     }
2966
2967     st->discard = AVDISCARD_ALL;
2968     sc = st->priv_data;
2969     cur_pos = avio_tell(sc->pb);
2970
2971     for (i = 0; i < st->nb_index_entries; i++) {
2972         AVIndexEntry *sample = &st->index_entries[i];
2973         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2974         uint8_t *title;
2975         uint16_t ch;
2976         int len, title_len;
2977
2978         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2979             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2980             goto finish;
2981         }
2982
2983         // the first two bytes are the length of the title
2984         len = avio_rb16(sc->pb);
2985         if (len > sample->size-2)
2986             continue;
2987         title_len = 2*len + 1;
2988         if (!(title = av_mallocz(title_len)))
2989             goto finish;
2990
2991         // The samples could theoretically be in any encoding if there's an encd
2992         // atom following, but in practice are only utf-8 or utf-16, distinguished
2993         // instead by the presence of a BOM
2994         if (!len) {
2995             title[0] = 0;
2996         } else {
2997             ch = avio_rb16(sc->pb);
2998             if (ch == 0xfeff)
2999                 avio_get_str16be(sc->pb, len, title, title_len);
3000             else if (ch == 0xfffe)
3001                 avio_get_str16le(sc->pb, len, title, title_len);
3002             else {
3003                 AV_WB16(title, ch);
3004                 if (len == 1 || len == 2)
3005                     title[len] = 0;
3006                 else
3007                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
3008             }
3009         }
3010
3011         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3012         av_freep(&title);
3013     }
3014 finish:
3015     avio_seek(sc->pb, cur_pos, SEEK_SET);
3016 }
3017
3018 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
3019                                              uint32_t value, int flags)
3020 {
3021     AVTimecode tc;
3022     char buf[AV_TIMECODE_STR_SIZE];
3023     AVRational rate = {st->codec->time_base.den,
3024                        st->codec->time_base.num};
3025     int ret = av_timecode_init(&tc, rate, flags, 0, s);
3026     if (ret < 0)
3027         return ret;
3028     av_dict_set(&st->metadata, "timecode",
3029                 av_timecode_make_string(&tc, buf, value), 0);
3030     return 0;
3031 }
3032
3033 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
3034 {
3035     MOVStreamContext *sc = st->priv_data;
3036     int flags = 0;
3037     int64_t cur_pos = avio_tell(sc->pb);
3038     uint32_t value;
3039
3040     if (!st->nb_index_entries)
3041         return -1;
3042
3043     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
3044     value = avio_rb32(s->pb);
3045
3046     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
3047     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
3048     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
3049
3050     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
3051      * not the case) and thus assume "frame number format" instead of QT one.
3052      * No sample with tmcd track can be found with a QT timecode at the moment,
3053      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
3054      * format). */
3055     parse_timecode_in_framenum_format(s, st, value, flags);
3056
3057     avio_seek(sc->pb, cur_pos, SEEK_SET);
3058     return 0;
3059 }
3060
3061 static int mov_read_close(AVFormatContext *s)
3062 {
3063     MOVContext *mov = s->priv_data;
3064     int i, j;
3065
3066     for (i = 0; i < s->nb_streams; i++) {
3067         AVStream *st = s->streams[i];
3068         MOVStreamContext *sc = st->priv_data;
3069
3070         av_freep(&sc->ctts_data);
3071         for (j = 0; j < sc->drefs_count; j++) {
3072             av_freep(&sc->drefs[j].path);
3073             av_freep(&sc->drefs[j].dir);
3074         }
3075         av_freep(&sc->drefs);
3076         av_freep(&sc->trefs);
3077         if (sc->pb && sc->pb != s->pb)
3078             avio_close(sc->pb);
3079         sc->pb = NULL;
3080         av_freep(&sc->chunk_offsets);
3081         av_freep(&sc->keyframes);
3082         av_freep(&sc->sample_sizes);
3083         av_freep(&sc->stps_data);
3084         av_freep(&sc->stsc_data);
3085         av_freep(&sc->stts_data);
3086     }
3087
3088     if (mov->dv_demux) {
3089         for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
3090             av_freep(&mov->dv_fctx->streams[i]->codec);
3091             av_freep(&mov->dv_fctx->streams[i]);
3092         }
3093         av_freep(&mov->dv_fctx);
3094         av_freep(&mov->dv_demux);
3095     }
3096
3097     av_freep(&mov->trex_data);
3098
3099     return 0;
3100 }
3101
3102 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
3103 {
3104     int i, j;
3105
3106     for (i = 0; i < s->nb_streams; i++) {
3107         AVStream *st = s->streams[i];
3108         MOVStreamContext *sc = st->priv_data;
3109
3110         if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
3111             continue;
3112         for (j = 0; j < sc->trefs_count; j++)
3113             if (tmcd_id == sc->trefs[j])
3114                 return 1;
3115     }
3116     return 0;
3117 }
3118
3119 /* look for a tmcd track not referenced by any video track, and export it globally */
3120 static void export_orphan_timecode(AVFormatContext *s)
3121 {
3122     int i;
3123
3124     for (i = 0; i < s->nb_streams; i++) {
3125         AVStream *st = s->streams[i];
3126
3127         if (st->codec->codec_tag  == MKTAG('t','m','c','d') &&
3128             !tmcd_is_referenced(s, i + 1)) {
3129             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
3130             if (tcr) {
3131                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
3132                 break;
3133             }
3134         }
3135     }
3136 }
3137
3138 static int mov_read_header(AVFormatContext *s)
3139 {
3140     MOVContext *mov = s->priv_data;
3141     AVIOContext *pb = s->pb;
3142     int i, err;
3143     MOVAtom atom = { AV_RL32("root") };
3144
3145     mov->fc = s;
3146     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3147     if (pb->seekable)
3148         atom.size = avio_size(pb);
3149     else
3150         atom.size = INT64_MAX;
3151
3152     /* check MOV header */
3153     if ((err = mov_read_default(mov, pb, atom)) < 0) {
3154         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3155         mov_read_close(s);
3156         return err;
3157     }
3158     if (!mov->found_moov) {
3159         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3160         mov_read_close(s);
3161         return AVERROR_INVALIDDATA;
3162     }
3163     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3164
3165     if (pb->seekable) {
3166         if (mov->chapter_track > 0)
3167             mov_read_chapters(s);
3168         for (i = 0; i < s->nb_streams; i++)
3169             if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
3170                 mov_read_timecode_track(s, s->streams[i]);
3171     }
3172
3173     /* copy timecode metadata from tmcd tracks to the related video streams */
3174     for (i = 0; i < s->nb_streams; i++) {
3175         AVStream *st = s->streams[i];
3176         MOVStreamContext *sc = st->priv_data;
3177         if (sc->tref_type == AV_RL32("tmcd") && sc->trefs_count) {
3178             AVDictionaryEntry *tcr;
3179             int tmcd_st_id = sc->trefs[0] - 1;
3180
3181             if (tmcd_st_id < 0 || tmcd_st_id >= s->nb_streams)
3182                 continue;
3183             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
3184             if (tcr)
3185                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
3186         }
3187     }
3188     export_orphan_timecode(s);
3189
3190     for (i = 0; i < s->nb_streams; i++) {
3191         AVStream *st = s->streams[i];
3192         MOVStreamContext *sc = st->priv_data;
3193         fix_timescale(mov, sc);
3194         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
3195             st->skip_samples = sc->start_pad;
3196         }
3197     }
3198
3199     if (mov->trex_data) {
3200         for (i = 0; i < s->nb_streams; i++) {
3201             AVStream *st = s->streams[i];
3202             MOVStreamContext *sc = st->priv_data;
3203             if (st->duration)
3204                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3205         }
3206     }
3207
3208     return 0;
3209 }
3210
3211 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3212 {
3213     AVIndexEntry *sample = NULL;
3214     int64_t best_dts = INT64_MAX;
3215     int i;
3216     for (i = 0; i < s->nb_streams; i++) {
3217         AVStream *avst = s->streams[i];
3218         MOVStreamContext *msc = avst->priv_data;
3219         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3220             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3221             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3222             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3223             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
3224                 (s->pb->seekable &&
3225                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3226                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3227                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3228                 sample = current_sample;
3229                 best_dts = dts;
3230                 *st = avst;
3231             }
3232         }
3233     }
3234     return sample;
3235 }
3236
3237 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3238 {
3239     MOVContext *mov = s->priv_data;
3240     MOVStreamContext *sc;
3241     AVIndexEntry *sample;
3242     AVStream *st = NULL;
3243     int ret;
3244     mov->fc = s;
3245  retry:
3246     sample = mov_find_next_sample(s, &st);
3247     if (!sample) {
3248         mov->found_mdat = 0;
3249         if (!mov->next_root_atom)
3250             return AVERROR_EOF;
3251         avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3252         mov->next_root_atom = 0;
3253         if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3254             url_feof(s->pb))
3255             return AVERROR_EOF;
3256         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3257         goto retry;
3258     }
3259     sc = st->priv_data;
3260     /* must be done just before reading, to avoid infinite loop on sample */
3261     sc->current_sample++;
3262
3263     if (st->discard != AVDISCARD_ALL) {
3264         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3265             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3266                    sc->ffindex, sample->pos);
3267             return AVERROR_INVALIDDATA;
3268         }
3269         ret = av_get_packet(sc->pb, pkt, sample->size);
3270         if (ret < 0)
3271             return ret;
3272         if (sc->has_palette) {
3273             uint8_t *pal;
3274
3275             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3276             if (!pal) {
3277                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3278             } else {
3279                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3280                 sc->has_palette = 0;
3281             }
3282         }
3283 #if CONFIG_DV_DEMUXER
3284         if (mov->dv_demux && sc->dv_audio_container) {
3285             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
3286             av_free(pkt->data);
3287             pkt->size = 0;
3288             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3289             if (ret < 0)
3290                 return ret;
3291         }
3292 #endif
3293     }
3294
3295     pkt->stream_index = sc->ffindex;
3296     pkt->dts = sample->timestamp;
3297     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3298         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3299         /* update ctts context */
3300         sc->ctts_sample++;
3301         if (sc->ctts_index < sc->ctts_count &&
3302             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3303             sc->ctts_index++;
3304             sc->ctts_sample = 0;
3305         }
3306         if (sc->wrong_dts)
3307             pkt->dts = AV_NOPTS_VALUE;
3308     } else {
3309         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3310             st->index_entries[sc->current_sample].timestamp : st->duration;
3311         pkt->duration = next_dts - pkt->dts;
3312         pkt->pts = pkt->dts;
3313     }
3314     if (st->discard == AVDISCARD_ALL)
3315         goto retry;
3316     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3317     pkt->pos = sample->pos;
3318     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3319             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3320     return 0;
3321 }
3322
3323 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3324 {
3325     MOVStreamContext *sc = st->priv_data;
3326     int sample, time_sample;
3327     int i;
3328
3329     sample = av_index_search_timestamp(st, timestamp, flags);
3330     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3331     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3332         sample = 0;
3333     if (sample < 0) /* not sure what to do */
3334         return AVERROR_INVALIDDATA;
3335     sc->current_sample = sample;
3336     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3337     /* adjust ctts index */
3338     if (sc->ctts_data) {
3339         time_sample = 0;
3340         for (i = 0; i < sc->ctts_count; i++) {
3341             int next = time_sample + sc->ctts_data[i].count;
3342             if (next > sc->current_sample) {
3343                 sc->ctts_index = i;
3344                 sc->ctts_sample = sc->current_sample - time_sample;
3345                 break;
3346             }
3347             time_sample = next;
3348         }
3349     }
3350     return sample;
3351 }
3352
3353 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3354 {
3355     AVStream *st;
3356     int64_t seek_timestamp, timestamp;
3357     int sample;
3358     int i;
3359
3360     if (stream_index >= s->nb_streams)
3361         return AVERROR_INVALIDDATA;
3362
3363     st = s->streams[stream_index];
3364     sample = mov_seek_stream(s, st, sample_time, flags);
3365     if (sample < 0)
3366         return sample;
3367
3368     /* adjust seek timestamp to found sample timestamp */
3369     seek_timestamp = st->index_entries[sample].timestamp;
3370
3371     for (i = 0; i < s->nb_streams; i++) {
3372         MOVStreamContext *sc = s->streams[i]->priv_data;
3373         st = s->streams[i];
3374         st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
3375
3376         if (stream_index == i)
3377             continue;
3378
3379         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3380         mov_seek_stream(s, st, timestamp, flags);
3381     }
3382     return 0;
3383 }
3384
3385 static const AVOption options[] = {
3386     {"use_absolute_path",
3387         "allow using absolute path when opening alias, this is a possible security issue",
3388         offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.i64 = 0},
3389         0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3390     {"ignore_editlist", "", offsetof(MOVContext, ignore_editlist), FF_OPT_TYPE_INT, {.i64 = 0},
3391         0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3392     {NULL}
3393 };
3394
3395 static const AVClass class = {
3396     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3397     .item_name  = av_default_item_name,
3398     .option     = options,
3399     .version    = LIBAVUTIL_VERSION_INT,
3400 };
3401
3402 AVInputFormat ff_mov_demuxer = {
3403     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
3404     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3405     .priv_data_size = sizeof(MOVContext),
3406     .read_probe     = mov_probe,
3407     .read_header    = mov_read_header,
3408     .read_packet    = mov_read_packet,
3409     .read_close     = mov_read_close,
3410     .read_seek      = mov_read_seek,
3411     .priv_class     = &class,
3412 };