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