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