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