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