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