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