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