]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
Merge commit 'e13da244f41610ee073b2f72bcf62b60fa402bb5'
[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 ((ret = mov_read_default(c, pb, atom)) < 0)
1440             return ret;
1441     } else
1442         avio_skip(pb, atom.size);
1443     return 0;
1444 }
1445
1446 /**
1447  * This function reads atom content and puts data in extradata without tag
1448  * nor size unlike mov_read_extradata.
1449  */
1450 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1451 {
1452     AVStream *st;
1453     int ret;
1454
1455     if (c->fc->nb_streams < 1)
1456         return 0;
1457     st = c->fc->streams[c->fc->nb_streams-1];
1458
1459     if ((uint64_t)atom.size > (1<<30))
1460         return AVERROR_INVALIDDATA;
1461
1462     if (atom.size >= 10) {
1463         // Broken files created by legacy versions of libavformat will
1464         // wrap a whole fiel atom inside of a glbl atom.
1465         unsigned size = avio_rb32(pb);
1466         unsigned type = avio_rl32(pb);
1467         avio_seek(pb, -8, SEEK_CUR);
1468         if (type == MKTAG('f','i','e','l') && size == atom.size)
1469             return mov_read_default(c, pb, atom);
1470     }
1471     if (st->codec->extradata_size > 1 && st->codec->extradata) {
1472         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1473         return 0;
1474     }
1475     av_freep(&st->codec->extradata);
1476     ret = ff_get_extradata(st->codec, pb, atom.size);
1477     if (ret < 0)
1478         return ret;
1479
1480     return 0;
1481 }
1482
1483 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1484 {
1485     AVStream *st;
1486     uint8_t profile_level;
1487     int ret;
1488
1489     if (c->fc->nb_streams < 1)
1490         return 0;
1491     st = c->fc->streams[c->fc->nb_streams-1];
1492
1493     if (atom.size >= (1<<28) || atom.size < 7)
1494         return AVERROR_INVALIDDATA;
1495
1496     profile_level = avio_r8(pb);
1497     if ((profile_level & 0xf0) != 0xc0)
1498         return 0;
1499
1500     avio_seek(pb, 6, SEEK_CUR);
1501     av_freep(&st->codec->extradata);
1502     ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1503     if (ret < 0)
1504         return ret;
1505
1506     return 0;
1507 }
1508
1509 /**
1510  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1511  * but can have extradata appended at the end after the 40 bytes belonging
1512  * to the struct.
1513  */
1514 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1515 {
1516     AVStream *st;
1517     int ret;
1518
1519     if (c->fc->nb_streams < 1)
1520         return 0;
1521     if (atom.size <= 40)
1522         return 0;
1523     st = c->fc->streams[c->fc->nb_streams-1];
1524
1525     if ((uint64_t)atom.size > (1<<30))
1526         return AVERROR_INVALIDDATA;
1527
1528     avio_skip(pb, 40);
1529     av_freep(&st->codec->extradata);
1530     ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1531     if (ret < 0)
1532         return ret;
1533
1534     return 0;
1535 }
1536
1537 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1538 {
1539     AVStream *st;
1540     MOVStreamContext *sc;
1541     unsigned int i, entries;
1542
1543     if (c->fc->nb_streams < 1)
1544         return 0;
1545     st = c->fc->streams[c->fc->nb_streams-1];
1546     sc = st->priv_data;
1547
1548     avio_r8(pb); /* version */
1549     avio_rb24(pb); /* flags */
1550
1551     entries = avio_rb32(pb);
1552
1553     if (!entries)
1554         return 0;
1555
1556     if (sc->chunk_offsets)
1557         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1558     av_free(sc->chunk_offsets);
1559     sc->chunk_count = 0;
1560     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1561     if (!sc->chunk_offsets)
1562         return AVERROR(ENOMEM);
1563     sc->chunk_count = entries;
1564
1565     if      (atom.type == MKTAG('s','t','c','o'))
1566         for (i = 0; i < entries && !pb->eof_reached; i++)
1567             sc->chunk_offsets[i] = avio_rb32(pb);
1568     else if (atom.type == MKTAG('c','o','6','4'))
1569         for (i = 0; i < entries && !pb->eof_reached; i++)
1570             sc->chunk_offsets[i] = avio_rb64(pb);
1571     else
1572         return AVERROR_INVALIDDATA;
1573
1574     sc->chunk_count = i;
1575
1576     if (pb->eof_reached)
1577         return AVERROR_EOF;
1578
1579     return 0;
1580 }
1581
1582 /**
1583  * Compute codec id for 'lpcm' tag.
1584  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1585  */
1586 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1587 {
1588     /* lpcm flags:
1589      * 0x1 = float
1590      * 0x2 = big-endian
1591      * 0x4 = signed
1592      */
1593     return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1594 }
1595
1596 static int mov_codec_id(AVStream *st, uint32_t format)
1597 {
1598     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1599
1600     if (id <= 0 &&
1601         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1602          (format & 0xFFFF) == 'T' + ('S' << 8)))
1603         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1604
1605     if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1606         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1607     } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1608                /* skip old asf mpeg4 tag */
1609                format && format != MKTAG('m','p','4','s')) {
1610         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1611         if (id <= 0)
1612             id = ff_codec_get_id(ff_codec_bmp_tags, format);
1613         if (id > 0)
1614             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1615         else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1616                     (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1617                     st->codec->codec_id == AV_CODEC_ID_NONE)) {
1618             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1619             if (id > 0)
1620                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1621         }
1622     }
1623
1624     st->codec->codec_tag = format;
1625
1626     return id;
1627 }
1628
1629 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1630                                  AVStream *st, MOVStreamContext *sc)
1631 {
1632     uint8_t codec_name[32];
1633     unsigned int color_depth, len, j;
1634     int color_greyscale;
1635     int color_table_id;
1636
1637     avio_rb16(pb); /* version */
1638     avio_rb16(pb); /* revision level */
1639     avio_rb32(pb); /* vendor */
1640     avio_rb32(pb); /* temporal quality */
1641     avio_rb32(pb); /* spatial quality */
1642
1643     st->codec->width  = avio_rb16(pb); /* width */
1644     st->codec->height = avio_rb16(pb); /* height */
1645
1646     avio_rb32(pb); /* horiz resolution */
1647     avio_rb32(pb); /* vert resolution */
1648     avio_rb32(pb); /* data size, always 0 */
1649     avio_rb16(pb); /* frames per samples */
1650
1651     len = avio_r8(pb); /* codec name, pascal string */
1652     if (len > 31)
1653         len = 31;
1654     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1655     if (len < 31)
1656         avio_skip(pb, 31 - len);
1657
1658     if (codec_name[0])
1659         av_dict_set(&st->metadata, "encoder", codec_name, 0);
1660
1661     /* codec_tag YV12 triggers an UV swap in rawdec.c */
1662     if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1663         st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1664         st->codec->width &= ~1;
1665         st->codec->height &= ~1;
1666     }
1667     /* Flash Media Server uses tag H263 with Sorenson Spark */
1668     if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1669         !memcmp(codec_name, "Sorenson H263", 13))
1670         st->codec->codec_id = AV_CODEC_ID_FLV1;
1671
1672     st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1673     color_table_id = avio_rb16(pb); /* colortable id */
1674     av_log(c->fc, AV_LOG_TRACE, "depth %d, ctab id %d\n",
1675             st->codec->bits_per_coded_sample, color_table_id);
1676     /* figure out the palette situation */
1677     color_depth     = st->codec->bits_per_coded_sample & 0x1F;
1678     color_greyscale = st->codec->bits_per_coded_sample & 0x20;
1679     /* Do not create a greyscale palette for cinepak */
1680     if (color_greyscale && st->codec->codec_id == AV_CODEC_ID_CINEPAK)
1681         return;
1682
1683     /* if the depth is 2, 4, or 8 bpp, file is palettized */
1684     if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
1685         /* for palette traversal */
1686         unsigned int color_start, color_count, color_end;
1687         unsigned char a, r, g, b;
1688
1689         if (color_greyscale) {
1690             int color_index, color_dec;
1691             /* compute the greyscale palette */
1692             st->codec->bits_per_coded_sample = color_depth;
1693             color_count = 1 << color_depth;
1694             color_index = 255;
1695             color_dec   = 256 / (color_count - 1);
1696             for (j = 0; j < color_count; j++) {
1697                 r = g = b = color_index;
1698                 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1699                 color_index -= color_dec;
1700                 if (color_index < 0)
1701                     color_index = 0;
1702             }
1703         } else if (color_table_id) {
1704             const uint8_t *color_table;
1705             /* if flag bit 3 is set, use the default palette */
1706             color_count = 1 << color_depth;
1707             if (color_depth == 2)
1708                 color_table = ff_qt_default_palette_4;
1709             else if (color_depth == 4)
1710                 color_table = ff_qt_default_palette_16;
1711             else
1712                 color_table = ff_qt_default_palette_256;
1713
1714             for (j = 0; j < color_count; j++) {
1715                 r = color_table[j * 3 + 0];
1716                 g = color_table[j * 3 + 1];
1717                 b = color_table[j * 3 + 2];
1718                 sc->palette[j] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);
1719             }
1720         } else {
1721             /* load the palette from the file */
1722             color_start = avio_rb32(pb);
1723             color_count = avio_rb16(pb);
1724             color_end   = avio_rb16(pb);
1725             if ((color_start <= 255) && (color_end <= 255)) {
1726                 for (j = color_start; j <= color_end; j++) {
1727                     /* each A, R, G, or B component is 16 bits;
1728                         * only use the top 8 bits */
1729                     a = avio_r8(pb);
1730                     avio_r8(pb);
1731                     r = avio_r8(pb);
1732                     avio_r8(pb);
1733                     g = avio_r8(pb);
1734                     avio_r8(pb);
1735                     b = avio_r8(pb);
1736                     avio_r8(pb);
1737                     sc->palette[j] = (a << 24 ) | (r << 16) | (g << 8) | (b);
1738                 }
1739             }
1740         }
1741         sc->has_palette = 1;
1742     }
1743 }
1744
1745 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1746                                  AVStream *st, MOVStreamContext *sc)
1747 {
1748     int bits_per_sample, flags;
1749     uint16_t version = avio_rb16(pb);
1750     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1751
1752     avio_rb16(pb); /* revision level */
1753     avio_rb32(pb); /* vendor */
1754
1755     st->codec->channels              = avio_rb16(pb); /* channel count */
1756     st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1757     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1758
1759     sc->audio_cid = avio_rb16(pb);
1760     avio_rb16(pb); /* packet size = 0 */
1761
1762     st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1763
1764     // Read QT version 1 fields. In version 0 these do not exist.
1765     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1766     if (!c->isom ||
1767         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
1768
1769         if (version == 1) {
1770             sc->samples_per_frame = avio_rb32(pb);
1771             avio_rb32(pb); /* bytes per packet */
1772             sc->bytes_per_frame = avio_rb32(pb);
1773             avio_rb32(pb); /* bytes per sample */
1774         } else if (version == 2) {
1775             avio_rb32(pb); /* sizeof struct only */
1776             st->codec->sample_rate = av_int2double(avio_rb64(pb));
1777             st->codec->channels    = avio_rb32(pb);
1778             avio_rb32(pb); /* always 0x7F000000 */
1779             st->codec->bits_per_coded_sample = avio_rb32(pb);
1780
1781             flags = avio_rb32(pb); /* lpcm format specific flag */
1782             sc->bytes_per_frame   = avio_rb32(pb);
1783             sc->samples_per_frame = avio_rb32(pb);
1784             if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1785                 st->codec->codec_id =
1786                     ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1787                                              flags);
1788         }
1789         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1790             /* can't correctly handle variable sized packet as audio unit */
1791             switch (st->codec->codec_id) {
1792             case AV_CODEC_ID_MP2:
1793             case AV_CODEC_ID_MP3:
1794                 st->need_parsing = AVSTREAM_PARSE_FULL;
1795                 break;
1796             }
1797         }
1798     }
1799
1800     switch (st->codec->codec_id) {
1801     case AV_CODEC_ID_PCM_S8:
1802     case AV_CODEC_ID_PCM_U8:
1803         if (st->codec->bits_per_coded_sample == 16)
1804             st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1805         break;
1806     case AV_CODEC_ID_PCM_S16LE:
1807     case AV_CODEC_ID_PCM_S16BE:
1808         if (st->codec->bits_per_coded_sample == 8)
1809             st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1810         else if (st->codec->bits_per_coded_sample == 24)
1811             st->codec->codec_id =
1812                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1813                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1814         else if (st->codec->bits_per_coded_sample == 32)
1815              st->codec->codec_id =
1816                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1817                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1818         break;
1819     /* set values for old format before stsd version 1 appeared */
1820     case AV_CODEC_ID_MACE3:
1821         sc->samples_per_frame = 6;
1822         sc->bytes_per_frame   = 2 * st->codec->channels;
1823         break;
1824     case AV_CODEC_ID_MACE6:
1825         sc->samples_per_frame = 6;
1826         sc->bytes_per_frame   = 1 * st->codec->channels;
1827         break;
1828     case AV_CODEC_ID_ADPCM_IMA_QT:
1829         sc->samples_per_frame = 64;
1830         sc->bytes_per_frame   = 34 * st->codec->channels;
1831         break;
1832     case AV_CODEC_ID_GSM:
1833         sc->samples_per_frame = 160;
1834         sc->bytes_per_frame   = 33;
1835         break;
1836     default:
1837         break;
1838     }
1839
1840     bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1841     if (bits_per_sample) {
1842         st->codec->bits_per_coded_sample = bits_per_sample;
1843         sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1844     }
1845 }
1846
1847 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1848                                     AVStream *st, MOVStreamContext *sc,
1849                                     int64_t size)
1850 {
1851     // ttxt stsd contains display flags, justification, background
1852     // color, fonts, and default styles, so fake an atom to read it
1853     MOVAtom fake_atom = { .size = size };
1854     // mp4s contains a regular esds atom
1855     if (st->codec->codec_tag != AV_RL32("mp4s"))
1856         mov_read_glbl(c, pb, fake_atom);
1857     st->codec->width  = sc->width;
1858     st->codec->height = sc->height;
1859 }
1860
1861 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1862 {
1863     uint8_t r, g, b;
1864     int y, cb, cr;
1865
1866     y  = (ycbcr >> 16) & 0xFF;
1867     cr = (ycbcr >> 8)  & 0xFF;
1868     cb =  ycbcr        & 0xFF;
1869
1870     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
1871     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
1872     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
1873
1874     return (r << 16) | (g << 8) | b;
1875 }
1876
1877 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1878 {
1879     char buf[256] = {0};
1880     uint8_t *src = st->codec->extradata;
1881     int i;
1882
1883     if (st->codec->extradata_size != 64)
1884         return 0;
1885
1886     if (st->codec->width > 0 &&  st->codec->height > 0)
1887         snprintf(buf, sizeof(buf), "size: %dx%d\n",
1888                  st->codec->width, st->codec->height);
1889     av_strlcat(buf, "palette: ", sizeof(buf));
1890
1891     for (i = 0; i < 16; i++) {
1892         uint32_t yuv = AV_RB32(src + i * 4);
1893         uint32_t rgba = yuv_to_rgba(yuv);
1894
1895         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1896     }
1897
1898     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1899         return 0;
1900
1901     av_freep(&st->codec->extradata);
1902     st->codec->extradata_size = 0;
1903     st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1904     if (!st->codec->extradata)
1905         return AVERROR(ENOMEM);
1906     st->codec->extradata_size = strlen(buf);
1907     memcpy(st->codec->extradata, buf, st->codec->extradata_size);
1908
1909     return 0;
1910 }
1911
1912 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
1913                                 AVStream *st, MOVStreamContext *sc,
1914                                 int64_t size)
1915 {
1916     int ret;
1917
1918     if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
1919         if ((int)size != size)
1920             return AVERROR(ENOMEM);
1921
1922         ret = ff_get_extradata(st->codec, pb, size);
1923         if (ret < 0)
1924             return ret;
1925         if (size > 16) {
1926             MOVStreamContext *tmcd_ctx = st->priv_data;
1927             int val;
1928             val = AV_RB32(st->codec->extradata + 4);
1929             tmcd_ctx->tmcd_flags = val;
1930             if (val & 1)
1931                 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
1932             st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
1933             st->codec->time_base.num = 1;
1934             /* adjust for per frame dur in counter mode */
1935             if (tmcd_ctx->tmcd_flags & 0x0008) {
1936                 int timescale = AV_RB32(st->codec->extradata + 8);
1937                 int framedur = AV_RB32(st->codec->extradata + 12);
1938                 st->codec->time_base.den *= timescale;
1939                 st->codec->time_base.num *= framedur;
1940             }
1941             if (size > 30) {
1942                 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
1943                 uint32_t format = AV_RB32(st->codec->extradata + 22);
1944                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
1945                     uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
1946                     if (str_size > 0 && size >= (int)str_size + 26) {
1947                         char *reel_name = av_malloc(str_size + 1);
1948                         if (!reel_name)
1949                             return AVERROR(ENOMEM);
1950                         memcpy(reel_name, st->codec->extradata + 30, str_size);
1951                         reel_name[str_size] = 0; /* Add null terminator */
1952                         /* don't add reel_name if emtpy string */
1953                         if (*reel_name == 0) {
1954                             av_free(reel_name);
1955                         } else {
1956                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
1957                         }
1958                     }
1959                 }
1960             }
1961         }
1962     } else {
1963         /* other codec type, just skip (rtp, mp4s ...) */
1964         avio_skip(pb, size);
1965     }
1966     return 0;
1967 }
1968
1969 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
1970                                    AVStream *st, MOVStreamContext *sc)
1971 {
1972     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1973         !st->codec->sample_rate && sc->time_scale > 1)
1974         st->codec->sample_rate = sc->time_scale;
1975
1976     /* special codec parameters handling */
1977     switch (st->codec->codec_id) {
1978 #if CONFIG_DV_DEMUXER
1979     case AV_CODEC_ID_DVAUDIO:
1980         c->dv_fctx = avformat_alloc_context();
1981         if (!c->dv_fctx) {
1982             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
1983             return AVERROR(ENOMEM);
1984         }
1985         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
1986         if (!c->dv_demux) {
1987             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1988             return AVERROR(ENOMEM);
1989         }
1990         sc->dv_audio_container = 1;
1991         st->codec->codec_id    = AV_CODEC_ID_PCM_S16LE;
1992         break;
1993 #endif
1994     /* no ifdef since parameters are always those */
1995     case AV_CODEC_ID_QCELP:
1996         st->codec->channels = 1;
1997         // force sample rate for qcelp when not stored in mov
1998         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1999             st->codec->sample_rate = 8000;
2000         // FIXME: Why is the following needed for some files?
2001         sc->samples_per_frame = 160;
2002         if (!sc->bytes_per_frame)
2003             sc->bytes_per_frame = 35;
2004         break;
2005     case AV_CODEC_ID_AMR_NB:
2006         st->codec->channels    = 1;
2007         /* force sample rate for amr, stsd in 3gp does not store sample rate */
2008         st->codec->sample_rate = 8000;
2009         break;
2010     case AV_CODEC_ID_AMR_WB:
2011         st->codec->channels    = 1;
2012         st->codec->sample_rate = 16000;
2013         break;
2014     case AV_CODEC_ID_MP2:
2015     case AV_CODEC_ID_MP3:
2016         /* force type after stsd for m1a hdlr */
2017         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2018         break;
2019     case AV_CODEC_ID_GSM:
2020     case AV_CODEC_ID_ADPCM_MS:
2021     case AV_CODEC_ID_ADPCM_IMA_WAV:
2022     case AV_CODEC_ID_ILBC:
2023     case AV_CODEC_ID_MACE3:
2024     case AV_CODEC_ID_MACE6:
2025     case AV_CODEC_ID_QDM2:
2026         st->codec->block_align = sc->bytes_per_frame;
2027         break;
2028     case AV_CODEC_ID_ALAC:
2029         if (st->codec->extradata_size == 36) {
2030             st->codec->channels    = AV_RB8 (st->codec->extradata + 21);
2031             st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2032         }
2033         break;
2034     case AV_CODEC_ID_AC3:
2035     case AV_CODEC_ID_EAC3:
2036     case AV_CODEC_ID_MPEG1VIDEO:
2037     case AV_CODEC_ID_VC1:
2038         st->need_parsing = AVSTREAM_PARSE_FULL;
2039         break;
2040     default:
2041         break;
2042     }
2043     return 0;
2044 }
2045
2046 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2047                                   int codec_tag, int format,
2048                                   int64_t size)
2049 {
2050     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2051
2052     if (codec_tag &&
2053          (codec_tag != format &&
2054           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2055                                  : codec_tag != MKTAG('j','p','e','g')))) {
2056         /* Multiple fourcc, we skip JPEG. This is not correct, we should
2057          * export it as a separate AVStream but this needs a few changes
2058          * in the MOV demuxer, patch welcome. */
2059
2060         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2061         avio_skip(pb, size);
2062         return 1;
2063     }
2064     if ( codec_tag == AV_RL32("avc1") ||
2065          codec_tag == AV_RL32("hvc1") ||
2066          codec_tag == AV_RL32("hev1")
2067     )
2068         av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2069
2070     return 0;
2071 }
2072
2073 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2074 {
2075     AVStream *st;
2076     MOVStreamContext *sc;
2077     int pseudo_stream_id;
2078
2079     if (c->fc->nb_streams < 1)
2080         return 0;
2081     st = c->fc->streams[c->fc->nb_streams-1];
2082     sc = st->priv_data;
2083
2084     for (pseudo_stream_id = 0;
2085          pseudo_stream_id < entries && !pb->eof_reached;
2086          pseudo_stream_id++) {
2087         //Parsing Sample description table
2088         enum AVCodecID id;
2089         int ret, dref_id = 1;
2090         MOVAtom a = { AV_RL32("stsd") };
2091         int64_t start_pos = avio_tell(pb);
2092         int64_t size = avio_rb32(pb); /* size */
2093         uint32_t format = avio_rl32(pb); /* data format */
2094
2095         if (size >= 16) {
2096             avio_rb32(pb); /* reserved */
2097             avio_rb16(pb); /* reserved */
2098             dref_id = avio_rb16(pb);
2099         }else if (size <= 7){
2100             av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size);
2101             return AVERROR_INVALIDDATA;
2102         }
2103
2104         if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2105                                    size - (avio_tell(pb) - start_pos)))
2106             continue;
2107
2108         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2109         sc->dref_id= dref_id;
2110
2111         id = mov_codec_id(st, format);
2112
2113         av_log(c->fc, AV_LOG_TRACE,
2114                "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2115                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2116                 (format >> 24) & 0xff, format, st->codec->codec_type);
2117
2118         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2119             st->codec->codec_id = id;
2120             mov_parse_stsd_video(c, pb, st, sc);
2121         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2122             st->codec->codec_id = id;
2123             mov_parse_stsd_audio(c, pb, st, sc);
2124         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2125             st->codec->codec_id = id;
2126             mov_parse_stsd_subtitle(c, pb, st, sc,
2127                                     size - (avio_tell(pb) - start_pos));
2128         } else {
2129             ret = mov_parse_stsd_data(c, pb, st, sc,
2130                                       size - (avio_tell(pb) - start_pos));
2131             if (ret < 0)
2132                 return ret;
2133         }
2134         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2135         a.size = size - (avio_tell(pb) - start_pos);
2136         if (a.size > 8) {
2137             if ((ret = mov_read_default(c, pb, a)) < 0)
2138                 return ret;
2139         } else if (a.size > 0)
2140             avio_skip(pb, a.size);
2141     }
2142
2143     if (pb->eof_reached)
2144         return AVERROR_EOF;
2145
2146     return mov_finalize_stsd_codec(c, pb, st, sc);
2147 }
2148
2149 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2150 {
2151     int entries;
2152
2153     avio_r8(pb); /* version */
2154     avio_rb24(pb); /* flags */
2155     entries = avio_rb32(pb);
2156
2157     return ff_mov_read_stsd_entries(c, pb, entries);
2158 }
2159
2160 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2161 {
2162     AVStream *st;
2163     MOVStreamContext *sc;
2164     unsigned int i, entries;
2165
2166     if (c->fc->nb_streams < 1)
2167         return 0;
2168     st = c->fc->streams[c->fc->nb_streams-1];
2169     sc = st->priv_data;
2170
2171     avio_r8(pb); /* version */
2172     avio_rb24(pb); /* flags */
2173
2174     entries = avio_rb32(pb);
2175
2176     av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2177
2178     if (!entries)
2179         return 0;
2180     if (sc->stsc_data)
2181         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2182     av_free(sc->stsc_data);
2183     sc->stsc_count = 0;
2184     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2185     if (!sc->stsc_data)
2186         return AVERROR(ENOMEM);
2187
2188     for (i = 0; i < entries && !pb->eof_reached; i++) {
2189         sc->stsc_data[i].first = avio_rb32(pb);
2190         sc->stsc_data[i].count = avio_rb32(pb);
2191         sc->stsc_data[i].id = avio_rb32(pb);
2192     }
2193
2194     sc->stsc_count = i;
2195
2196     if (pb->eof_reached)
2197         return AVERROR_EOF;
2198
2199     return 0;
2200 }
2201
2202 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2203 {
2204     AVStream *st;
2205     MOVStreamContext *sc;
2206     unsigned i, entries;
2207
2208     if (c->fc->nb_streams < 1)
2209         return 0;
2210     st = c->fc->streams[c->fc->nb_streams-1];
2211     sc = st->priv_data;
2212
2213     avio_rb32(pb); // version + flags
2214
2215     entries = avio_rb32(pb);
2216     if (sc->stps_data)
2217         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2218     av_free(sc->stps_data);
2219     sc->stps_count = 0;
2220     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2221     if (!sc->stps_data)
2222         return AVERROR(ENOMEM);
2223
2224     for (i = 0; i < entries && !pb->eof_reached; i++) {
2225         sc->stps_data[i] = avio_rb32(pb);
2226         //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2227     }
2228
2229     sc->stps_count = i;
2230
2231     if (pb->eof_reached)
2232         return AVERROR_EOF;
2233
2234     return 0;
2235 }
2236
2237 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2238 {
2239     AVStream *st;
2240     MOVStreamContext *sc;
2241     unsigned int i, entries;
2242
2243     if (c->fc->nb_streams < 1)
2244         return 0;
2245     st = c->fc->streams[c->fc->nb_streams-1];
2246     sc = st->priv_data;
2247
2248     avio_r8(pb); /* version */
2249     avio_rb24(pb); /* flags */
2250
2251     entries = avio_rb32(pb);
2252
2253     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2254
2255     if (!entries)
2256     {
2257         sc->keyframe_absent = 1;
2258         if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2259             st->need_parsing = AVSTREAM_PARSE_HEADERS;
2260         return 0;
2261     }
2262     if (sc->keyframes)
2263         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2264     if (entries >= UINT_MAX / sizeof(int))
2265         return AVERROR_INVALIDDATA;
2266     av_freep(&sc->keyframes);
2267     sc->keyframe_count = 0;
2268     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2269     if (!sc->keyframes)
2270         return AVERROR(ENOMEM);
2271
2272     for (i = 0; i < entries && !pb->eof_reached; i++) {
2273         sc->keyframes[i] = avio_rb32(pb);
2274         //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2275     }
2276
2277     sc->keyframe_count = i;
2278
2279     if (pb->eof_reached)
2280         return AVERROR_EOF;
2281
2282     return 0;
2283 }
2284
2285 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2286 {
2287     AVStream *st;
2288     MOVStreamContext *sc;
2289     unsigned int i, entries, sample_size, field_size, num_bytes;
2290     GetBitContext gb;
2291     unsigned char* buf;
2292     int ret;
2293
2294     if (c->fc->nb_streams < 1)
2295         return 0;
2296     st = c->fc->streams[c->fc->nb_streams-1];
2297     sc = st->priv_data;
2298
2299     avio_r8(pb); /* version */
2300     avio_rb24(pb); /* flags */
2301
2302     if (atom.type == MKTAG('s','t','s','z')) {
2303         sample_size = avio_rb32(pb);
2304         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2305             sc->sample_size = sample_size;
2306         sc->stsz_sample_size = sample_size;
2307         field_size = 32;
2308     } else {
2309         sample_size = 0;
2310         avio_rb24(pb); /* reserved */
2311         field_size = avio_r8(pb);
2312     }
2313     entries = avio_rb32(pb);
2314
2315     av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2316
2317     sc->sample_count = entries;
2318     if (sample_size)
2319         return 0;
2320
2321     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2322         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2323         return AVERROR_INVALIDDATA;
2324     }
2325
2326     if (!entries)
2327         return 0;
2328     if (entries >= (UINT_MAX - 4) / field_size)
2329         return AVERROR_INVALIDDATA;
2330     if (sc->sample_sizes)
2331         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2332     av_free(sc->sample_sizes);
2333     sc->sample_count = 0;
2334     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2335     if (!sc->sample_sizes)
2336         return AVERROR(ENOMEM);
2337
2338     num_bytes = (entries*field_size+4)>>3;
2339
2340     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2341     if (!buf) {
2342         av_freep(&sc->sample_sizes);
2343         return AVERROR(ENOMEM);
2344     }
2345
2346     ret = ffio_read_size(pb, buf, num_bytes);
2347     if (ret < 0) {
2348         av_freep(&sc->sample_sizes);
2349         av_free(buf);
2350         return ret;
2351     }
2352
2353     init_get_bits(&gb, buf, 8*num_bytes);
2354
2355     for (i = 0; i < entries && !pb->eof_reached; i++) {
2356         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2357         sc->data_size += sc->sample_sizes[i];
2358     }
2359
2360     sc->sample_count = i;
2361
2362     av_free(buf);
2363
2364     if (pb->eof_reached)
2365         return AVERROR_EOF;
2366
2367     return 0;
2368 }
2369
2370 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2371 {
2372     AVStream *st;
2373     MOVStreamContext *sc;
2374     unsigned int i, entries;
2375     int64_t duration=0;
2376     int64_t total_sample_count=0;
2377
2378     if (c->fc->nb_streams < 1)
2379         return 0;
2380     st = c->fc->streams[c->fc->nb_streams-1];
2381     sc = st->priv_data;
2382
2383     avio_r8(pb); /* version */
2384     avio_rb24(pb); /* flags */
2385     entries = avio_rb32(pb);
2386
2387     av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2388             c->fc->nb_streams-1, entries);
2389
2390     if (sc->stts_data)
2391         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2392     av_free(sc->stts_data);
2393     sc->stts_count = 0;
2394     sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2395     if (!sc->stts_data)
2396         return AVERROR(ENOMEM);
2397
2398     for (i = 0; i < entries && !pb->eof_reached; i++) {
2399         int sample_duration;
2400         int sample_count;
2401
2402         sample_count=avio_rb32(pb);
2403         sample_duration = avio_rb32(pb);
2404
2405         if (sample_count < 0) {
2406             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2407             return AVERROR_INVALIDDATA;
2408         }
2409         sc->stts_data[i].count= sample_count;
2410         sc->stts_data[i].duration= sample_duration;
2411
2412         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2413                 sample_count, sample_duration);
2414
2415         if (   i+1 == entries
2416             && i
2417             && sample_count == 1
2418             && total_sample_count > 100
2419             && sample_duration/10 > duration / total_sample_count)
2420             sample_duration = duration / total_sample_count;
2421         duration+=(int64_t)sample_duration*sample_count;
2422         total_sample_count+=sample_count;
2423     }
2424
2425     sc->stts_count = i;
2426
2427     sc->duration_for_fps  += duration;
2428     sc->nb_frames_for_fps += total_sample_count;
2429
2430     if (pb->eof_reached)
2431         return AVERROR_EOF;
2432
2433     st->nb_frames= total_sample_count;
2434     if (duration)
2435         st->duration= duration;
2436     sc->track_end = duration;
2437     return 0;
2438 }
2439
2440 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2441 {
2442     if (duration < 0) {
2443         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2444     }
2445 }
2446
2447 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2448 {
2449     AVStream *st;
2450     MOVStreamContext *sc;
2451     unsigned int i, entries;
2452
2453     if (c->fc->nb_streams < 1)
2454         return 0;
2455     st = c->fc->streams[c->fc->nb_streams-1];
2456     sc = st->priv_data;
2457
2458     avio_r8(pb); /* version */
2459     avio_rb24(pb); /* flags */
2460     entries = avio_rb32(pb);
2461
2462     av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2463
2464     if (!entries)
2465         return 0;
2466     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2467         return AVERROR_INVALIDDATA;
2468     av_freep(&sc->ctts_data);
2469     sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2470     if (!sc->ctts_data)
2471         return AVERROR(ENOMEM);
2472
2473     for (i = 0; i < entries && !pb->eof_reached; i++) {
2474         int count    =avio_rb32(pb);
2475         int duration =avio_rb32(pb);
2476
2477         sc->ctts_data[i].count   = count;
2478         sc->ctts_data[i].duration= duration;
2479
2480         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2481                 count, duration);
2482
2483         if (FFABS(duration) > (1<<28) && i+2<entries) {
2484             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2485             av_freep(&sc->ctts_data);
2486             sc->ctts_count = 0;
2487             return 0;
2488         }
2489
2490         if (i+2<entries)
2491             mov_update_dts_shift(sc, duration);
2492     }
2493
2494     sc->ctts_count = i;
2495
2496     if (pb->eof_reached)
2497         return AVERROR_EOF;
2498
2499     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2500
2501     return 0;
2502 }
2503
2504 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2505 {
2506     AVStream *st;
2507     MOVStreamContext *sc;
2508     unsigned int i, entries;
2509     uint8_t version;
2510     uint32_t grouping_type;
2511
2512     if (c->fc->nb_streams < 1)
2513         return 0;
2514     st = c->fc->streams[c->fc->nb_streams-1];
2515     sc = st->priv_data;
2516
2517     version = avio_r8(pb); /* version */
2518     avio_rb24(pb); /* flags */
2519     grouping_type = avio_rl32(pb);
2520     if (grouping_type != MKTAG( 'r','a','p',' '))
2521         return 0; /* only support 'rap ' grouping */
2522     if (version == 1)
2523         avio_rb32(pb); /* grouping_type_parameter */
2524
2525     entries = avio_rb32(pb);
2526     if (!entries)
2527         return 0;
2528     if (sc->rap_group)
2529         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2530     av_free(sc->rap_group);
2531     sc->rap_group_count = 0;
2532     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2533     if (!sc->rap_group)
2534         return AVERROR(ENOMEM);
2535
2536     for (i = 0; i < entries && !pb->eof_reached; i++) {
2537         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2538         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2539     }
2540
2541     sc->rap_group_count = i;
2542
2543     return pb->eof_reached ? AVERROR_EOF : 0;
2544 }
2545
2546 static void mov_build_index(MOVContext *mov, AVStream *st)
2547 {
2548     MOVStreamContext *sc = st->priv_data;
2549     int64_t current_offset;
2550     int64_t current_dts = 0;
2551     unsigned int stts_index = 0;
2552     unsigned int stsc_index = 0;
2553     unsigned int stss_index = 0;
2554     unsigned int stps_index = 0;
2555     unsigned int i, j;
2556     uint64_t stream_size = 0;
2557
2558     if (sc->elst_count) {
2559         int i, edit_start_index = 0, unsupported = 0;
2560         int64_t empty_duration = 0; // empty duration of the first edit list entry
2561         int64_t start_time = 0; // start time of the media
2562
2563         for (i = 0; i < sc->elst_count; i++) {
2564             const MOVElst *e = &sc->elst_data[i];
2565             if (i == 0 && e->time == -1) {
2566                 /* if empty, the first entry is the start time of the stream
2567                  * relative to the presentation itself */
2568                 empty_duration = e->duration;
2569                 edit_start_index = 1;
2570             } else if (i == edit_start_index && e->time >= 0) {
2571                 start_time = e->time;
2572             } else
2573                 unsupported = 1;
2574         }
2575         if (unsupported)
2576             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2577                    "a/v desync might occur, patch welcome\n");
2578
2579         /* adjust first dts according to edit list */
2580         if ((empty_duration || start_time) && mov->time_scale > 0) {
2581             if (empty_duration)
2582                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2583             sc->time_offset = start_time - empty_duration;
2584             current_dts = -sc->time_offset;
2585             if (sc->ctts_count>0 && sc->stts_count>0 &&
2586                 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2587                 /* more than 16 frames delay, dts are likely wrong
2588                    this happens with files created by iMovie */
2589                 sc->wrong_dts = 1;
2590                 st->codec->has_b_frames = 1;
2591             }
2592         }
2593     }
2594
2595     /* only use old uncompressed audio chunk demuxing when stts specifies it */
2596     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2597           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2598         unsigned int current_sample = 0;
2599         unsigned int stts_sample = 0;
2600         unsigned int sample_size;
2601         unsigned int distance = 0;
2602         unsigned int rap_group_index = 0;
2603         unsigned int rap_group_sample = 0;
2604         int64_t last_dts = 0;
2605         int64_t dts_correction = 0;
2606         int rap_group_present = sc->rap_group_count && sc->rap_group;
2607         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2608
2609         current_dts -= sc->dts_shift;
2610         last_dts     = current_dts;
2611
2612         if (!sc->sample_count || st->nb_index_entries)
2613             return;
2614         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2615             return;
2616         if (av_reallocp_array(&st->index_entries,
2617                               st->nb_index_entries + sc->sample_count,
2618                               sizeof(*st->index_entries)) < 0) {
2619             st->nb_index_entries = 0;
2620             return;
2621         }
2622         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2623
2624         for (i = 0; i < sc->chunk_count; i++) {
2625             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2626             current_offset = sc->chunk_offsets[i];
2627             while (stsc_index + 1 < sc->stsc_count &&
2628                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2629                 stsc_index++;
2630
2631             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2632                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2633                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2634                 sc->stsz_sample_size = sc->sample_size;
2635             }
2636             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2637                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2638                 sc->stsz_sample_size = sc->sample_size;
2639             }
2640
2641             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2642                 int keyframe = 0;
2643                 if (current_sample >= sc->sample_count) {
2644                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2645                     return;
2646                 }
2647
2648                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2649                     keyframe = 1;
2650                     if (stss_index + 1 < sc->keyframe_count)
2651                         stss_index++;
2652                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2653                     keyframe = 1;
2654                     if (stps_index + 1 < sc->stps_count)
2655                         stps_index++;
2656                 }
2657                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2658                     if (sc->rap_group[rap_group_index].index > 0)
2659                         keyframe = 1;
2660                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2661                         rap_group_sample = 0;
2662                         rap_group_index++;
2663                     }
2664                 }
2665                 if (sc->keyframe_absent
2666                     && !sc->stps_count
2667                     && !rap_group_present
2668                     && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2669                      keyframe = 1;
2670                 if (keyframe)
2671                     distance = 0;
2672                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2673                 if (sc->pseudo_stream_id == -1 ||
2674                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2675                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2676                     e->pos = current_offset;
2677                     e->timestamp = current_dts;
2678                     e->size = sample_size;
2679                     e->min_distance = distance;
2680                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2681                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2682                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2683                             current_offset, current_dts, sample_size, distance, keyframe);
2684                     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2685                         ff_rfps_add_frame(mov->fc, st, current_dts);
2686                 }
2687
2688                 current_offset += sample_size;
2689                 stream_size += sample_size;
2690
2691                 /* A negative sample duration is invalid based on the spec,
2692                  * but some samples need it to correct the DTS. */
2693                 if (sc->stts_data[stts_index].duration < 0) {
2694                     av_log(mov->fc, AV_LOG_WARNING,
2695                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2696                            sc->stts_data[stts_index].duration, stts_index,
2697                            st->index);
2698                     dts_correction += sc->stts_data[stts_index].duration - 1;
2699                     sc->stts_data[stts_index].duration = 1;
2700                 }
2701                 current_dts += sc->stts_data[stts_index].duration;
2702                 if (!dts_correction || current_dts + dts_correction > last_dts) {
2703                     current_dts += dts_correction;
2704                     dts_correction = 0;
2705                 } else {
2706                     /* Avoid creating non-monotonous DTS */
2707                     dts_correction += current_dts - last_dts - 1;
2708                     current_dts = last_dts + 1;
2709                 }
2710                 last_dts = current_dts;
2711                 distance++;
2712                 stts_sample++;
2713                 current_sample++;
2714                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2715                     stts_sample = 0;
2716                     stts_index++;
2717                 }
2718             }
2719         }
2720         if (st->duration > 0)
2721             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2722     } else {
2723         unsigned chunk_samples, total = 0;
2724
2725         // compute total chunk count
2726         for (i = 0; i < sc->stsc_count; i++) {
2727             unsigned count, chunk_count;
2728
2729             chunk_samples = sc->stsc_data[i].count;
2730             if (i != sc->stsc_count - 1 &&
2731                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2732                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2733                 return;
2734             }
2735
2736             if (sc->samples_per_frame >= 160) { // gsm
2737                 count = chunk_samples / sc->samples_per_frame;
2738             } else if (sc->samples_per_frame > 1) {
2739                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2740                 count = (chunk_samples+samples-1) / samples;
2741             } else {
2742                 count = (chunk_samples+1023) / 1024;
2743             }
2744
2745             if (i < sc->stsc_count - 1)
2746                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2747             else
2748                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2749             total += chunk_count * count;
2750         }
2751
2752         av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2753         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2754             return;
2755         if (av_reallocp_array(&st->index_entries,
2756                               st->nb_index_entries + total,
2757                               sizeof(*st->index_entries)) < 0) {
2758             st->nb_index_entries = 0;
2759             return;
2760         }
2761         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2762
2763         // populate index
2764         for (i = 0; i < sc->chunk_count; i++) {
2765             current_offset = sc->chunk_offsets[i];
2766             if (stsc_index + 1 < sc->stsc_count &&
2767                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2768                 stsc_index++;
2769             chunk_samples = sc->stsc_data[stsc_index].count;
2770
2771             while (chunk_samples > 0) {
2772                 AVIndexEntry *e;
2773                 unsigned size, samples;
2774
2775                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2776                     avpriv_request_sample(mov->fc,
2777                            "Zero bytes per frame, but %d samples per frame",
2778                            sc->samples_per_frame);
2779                     return;
2780                 }
2781
2782                 if (sc->samples_per_frame >= 160) { // gsm
2783                     samples = sc->samples_per_frame;
2784                     size = sc->bytes_per_frame;
2785                 } else {
2786                     if (sc->samples_per_frame > 1) {
2787                         samples = FFMIN((1024 / sc->samples_per_frame)*
2788                                         sc->samples_per_frame, chunk_samples);
2789                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2790                     } else {
2791                         samples = FFMIN(1024, chunk_samples);
2792                         size = samples * sc->sample_size;
2793                     }
2794                 }
2795
2796                 if (st->nb_index_entries >= total) {
2797                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2798                     return;
2799                 }
2800                 e = &st->index_entries[st->nb_index_entries++];
2801                 e->pos = current_offset;
2802                 e->timestamp = current_dts;
2803                 e->size = size;
2804                 e->min_distance = 0;
2805                 e->flags = AVINDEX_KEYFRAME;
2806                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2807                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2808                         size, samples);
2809
2810                 current_offset += size;
2811                 current_dts += samples;
2812                 chunk_samples -= samples;
2813             }
2814         }
2815     }
2816 }
2817
2818 static int test_same_origin(const char *src, const char *ref) {
2819     char src_proto[64];
2820     char ref_proto[64];
2821     char src_auth[256];
2822     char ref_auth[256];
2823     char src_host[256];
2824     char ref_host[256];
2825     int src_port=-1;
2826     int ref_port=-1;
2827
2828     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2829     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2830
2831     if (strlen(src) == 0) {
2832         return -1;
2833     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2834         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2835         strlen(src_host) + 1 >= sizeof(src_host) ||
2836         strlen(ref_host) + 1 >= sizeof(ref_host)) {
2837         return 0;
2838     } else if (strcmp(src_proto, ref_proto) ||
2839                strcmp(src_auth, ref_auth) ||
2840                strcmp(src_host, ref_host) ||
2841                src_port != ref_port) {
2842         return 0;
2843     } else
2844         return 1;
2845 }
2846
2847 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref,
2848                          AVIOInterruptCB *int_cb)
2849 {
2850     AVOpenCallback open_func = c->fc->open_cb;
2851
2852     if (!open_func)
2853         open_func = ffio_open2_wrapper;
2854
2855     /* try relative path, we do not try the absolute because it can leak information about our
2856        system to an attacker */
2857     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2858         char filename[1025];
2859         const char *src_path;
2860         int i, l;
2861
2862         /* find a source dir */
2863         src_path = strrchr(src, '/');
2864         if (src_path)
2865             src_path++;
2866         else
2867             src_path = src;
2868
2869         /* find a next level down to target */
2870         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2871             if (ref->path[l] == '/') {
2872                 if (i == ref->nlvl_to - 1)
2873                     break;
2874                 else
2875                     i++;
2876             }
2877
2878         /* compose filename if next level down to target was found */
2879         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
2880             memcpy(filename, src, src_path - src);
2881             filename[src_path - src] = 0;
2882
2883             for (i = 1; i < ref->nlvl_from; i++)
2884                 av_strlcat(filename, "../", sizeof(filename));
2885
2886             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
2887             if (!c->use_absolute_path && !c->fc->open_cb) {
2888                 int same_origin = test_same_origin(src, filename);
2889
2890                 if (!same_origin) {
2891                     av_log(c->fc, AV_LOG_ERROR,
2892                         "Reference with mismatching origin, %s not tried for security reasons, "
2893                         "set demuxer option use_absolute_path to allow it anyway\n",
2894                         ref->path);
2895                     return AVERROR(ENOENT);
2896                 }
2897
2898                 if(strstr(ref->path + l + 1, "..") ||
2899                    strstr(ref->path + l + 1, ":") ||
2900                    (ref->nlvl_from > 1 && same_origin < 0) ||
2901                    (filename[0] == '/' && src_path == src))
2902                     return AVERROR(ENOENT);
2903             }
2904
2905             if (strlen(filename) + 1 == sizeof(filename))
2906                 return AVERROR(ENOENT);
2907             if (!open_func(c->fc, pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2908                 return 0;
2909         }
2910     } else if (c->use_absolute_path) {
2911         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
2912                "this is a possible security issue\n");
2913         if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2914             return 0;
2915     } else if (c->fc->open_cb) {
2916         if (!open_func(c->fc, pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2917             return 0;
2918     } else {
2919         av_log(c->fc, AV_LOG_ERROR,
2920                "Absolute path %s not tried for security reasons, "
2921                "set demuxer option use_absolute_path to allow absolute paths\n",
2922                ref->path);
2923     }
2924
2925     return AVERROR(ENOENT);
2926 }
2927
2928 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
2929 {
2930     if (sc->time_scale <= 0) {
2931         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
2932         sc->time_scale = c->time_scale;
2933         if (sc->time_scale <= 0)
2934             sc->time_scale = 1;
2935     }
2936 }
2937
2938 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2939 {
2940     AVStream *st;
2941     MOVStreamContext *sc;
2942     int ret;
2943
2944     st = avformat_new_stream(c->fc, NULL);
2945     if (!st) return AVERROR(ENOMEM);
2946     st->id = c->fc->nb_streams;
2947     sc = av_mallocz(sizeof(MOVStreamContext));
2948     if (!sc) return AVERROR(ENOMEM);
2949
2950     st->priv_data = sc;
2951     st->codec->codec_type = AVMEDIA_TYPE_DATA;
2952     sc->ffindex = st->index;
2953
2954     if ((ret = mov_read_default(c, pb, atom)) < 0)
2955         return ret;
2956
2957     /* sanity checks */
2958     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2959                             (!sc->sample_size && !sc->sample_count))) {
2960         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2961                st->index);
2962         return 0;
2963     }
2964
2965     fix_timescale(c, sc);
2966
2967     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2968
2969     mov_build_index(c, st);
2970
2971     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2972         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2973         if (mov_open_dref(c, &sc->pb, c->fc->filename, dref,
2974                           &c->fc->interrupt_callback) < 0)
2975             av_log(c->fc, AV_LOG_ERROR,
2976                    "stream %d, error opening alias: path='%s', dir='%s', "
2977                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2978                    st->index, dref->path, dref->dir, dref->filename,
2979                    dref->volume, dref->nlvl_from, dref->nlvl_to);
2980     } else {
2981         sc->pb = c->fc->pb;
2982         sc->pb_is_copied = 1;
2983     }
2984
2985     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2986         if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
2987             sc->height && sc->width &&
2988             (st->codec->width != sc->width || st->codec->height != sc->height)) {
2989             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2990                                              ((double)st->codec->width * sc->height), INT_MAX);
2991         }
2992
2993 #if FF_API_R_FRAME_RATE
2994         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2995             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2996                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2997 #endif
2998     }
2999
3000     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3001     if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3002         TAG_IS_AVCI(st->codec->codec_tag)) {
3003         ret = ff_generate_avci_extradata(st);
3004         if (ret < 0)
3005             return ret;
3006     }
3007
3008     switch (st->codec->codec_id) {
3009 #if CONFIG_H261_DECODER
3010     case AV_CODEC_ID_H261:
3011 #endif
3012 #if CONFIG_H263_DECODER
3013     case AV_CODEC_ID_H263:
3014 #endif
3015 #if CONFIG_MPEG4_DECODER
3016     case AV_CODEC_ID_MPEG4:
3017 #endif
3018         st->codec->width = 0; /* let decoder init width/height */
3019         st->codec->height= 0;
3020         break;
3021     }
3022
3023     /* Do not need those anymore. */
3024     av_freep(&sc->chunk_offsets);
3025     av_freep(&sc->stsc_data);
3026     av_freep(&sc->sample_sizes);
3027     av_freep(&sc->keyframes);
3028     av_freep(&sc->stts_data);
3029     av_freep(&sc->stps_data);
3030     av_freep(&sc->elst_data);
3031     av_freep(&sc->rap_group);
3032
3033     return 0;
3034 }
3035
3036 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3037 {
3038     int ret;
3039     c->itunes_metadata = 1;
3040     ret = mov_read_default(c, pb, atom);
3041     c->itunes_metadata = 0;
3042     return ret;
3043 }
3044
3045 static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
3046 {
3047     int64_t end = avio_tell(pb) + size;
3048     uint8_t *key = NULL, *val = NULL;
3049     int i;
3050     AVStream *st;
3051     MOVStreamContext *sc;
3052
3053     if (c->fc->nb_streams < 1)
3054         return 0;
3055     st = c->fc->streams[c->fc->nb_streams-1];
3056     sc = st->priv_data;
3057
3058     for (i = 0; i < 2; i++) {
3059         uint8_t **p;
3060         uint32_t len, tag;
3061         int ret;
3062
3063         if (end - avio_tell(pb) <= 12)
3064             break;
3065
3066         len = avio_rb32(pb);
3067         tag = avio_rl32(pb);
3068         avio_skip(pb, 4); // flags
3069
3070         if (len < 12 || len - 12 > end - avio_tell(pb))
3071             break;
3072         len -= 12;
3073
3074         if (tag == MKTAG('n', 'a', 'm', 'e'))
3075             p = &key;
3076         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3077             avio_skip(pb, 4);
3078             len -= 4;
3079             p = &val;
3080         } else
3081             break;
3082
3083         *p = av_malloc(len + 1);
3084         if (!*p)
3085             break;
3086         ret = ffio_read_size(pb, *p, len);
3087         if (ret < 0) {
3088             av_freep(p);
3089             return ret;
3090         }
3091         (*p)[len] = 0;
3092     }
3093
3094     if (key && val) {
3095         if (strcmp(key, "iTunSMPB") == 0) {
3096             int priming, remainder, samples;
3097             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3098                 if(priming>0 && priming<16384)
3099                     sc->start_pad = priming;
3100             }
3101         }
3102         if (strcmp(key, "cdec") != 0) {
3103             av_dict_set(&c->fc->metadata, key, val,
3104                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3105             key = val = NULL;
3106         }
3107     }
3108
3109     avio_seek(pb, end, SEEK_SET);
3110     av_freep(&key);
3111     av_freep(&val);
3112     return 0;
3113 }
3114
3115 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3116 {
3117     int64_t end = avio_tell(pb) + atom.size;
3118     uint32_t tag, len;
3119
3120     if (atom.size < 8)
3121         goto fail;
3122
3123     len = avio_rb32(pb);
3124     tag = avio_rl32(pb);
3125
3126     if (len > atom.size)
3127         goto fail;
3128
3129     if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
3130         uint8_t domain[128];
3131         int domain_len;
3132
3133         avio_skip(pb, 4); // flags
3134         len -= 12;
3135
3136         domain_len = avio_get_str(pb, len, domain, sizeof(domain));
3137         avio_skip(pb, len - domain_len);
3138         return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
3139     }
3140
3141 fail:
3142     av_log(c->fc, AV_LOG_VERBOSE,
3143            "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3144     return 0;
3145 }
3146
3147 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3148 {
3149     while (atom.size > 8) {
3150         uint32_t tag = avio_rl32(pb);
3151         atom.size -= 4;
3152         if (tag == MKTAG('h','d','l','r')) {
3153             avio_seek(pb, -8, SEEK_CUR);
3154             atom.size += 8;
3155             return mov_read_default(c, pb, atom);
3156         }
3157     }
3158     return 0;
3159 }
3160
3161 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3162 {
3163     int i;
3164     int width;
3165     int height;
3166     int display_matrix[3][3];
3167     AVStream *st;
3168     MOVStreamContext *sc;
3169     int version;
3170     int flags;
3171
3172     if (c->fc->nb_streams < 1)
3173         return 0;
3174     st = c->fc->streams[c->fc->nb_streams-1];
3175     sc = st->priv_data;
3176
3177     version = avio_r8(pb);
3178     flags = avio_rb24(pb);
3179     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3180
3181     if (version == 1) {
3182         avio_rb64(pb);
3183         avio_rb64(pb);
3184     } else {
3185         avio_rb32(pb); /* creation time */
3186         avio_rb32(pb); /* modification time */
3187     }
3188     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3189     avio_rb32(pb); /* reserved */
3190
3191     /* highlevel (considering edits) duration in movie timebase */
3192     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3193     avio_rb32(pb); /* reserved */
3194     avio_rb32(pb); /* reserved */
3195
3196     avio_rb16(pb); /* layer */
3197     avio_rb16(pb); /* alternate group */
3198     avio_rb16(pb); /* volume */
3199     avio_rb16(pb); /* reserved */
3200
3201     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3202     // they're kept in fixed point format through all calculations
3203     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3204     // side data, but the scale factor is not needed to calculate aspect ratio
3205     for (i = 0; i < 3; i++) {
3206         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
3207         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
3208         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
3209     }
3210
3211     width = avio_rb32(pb);       // 16.16 fixed point track width
3212     height = avio_rb32(pb);      // 16.16 fixed point track height
3213     sc->width = width >> 16;
3214     sc->height = height >> 16;
3215
3216     // save the matrix and add rotate metadata when it is not the default
3217     // identity
3218     if (display_matrix[0][0] != (1 << 16) ||
3219         display_matrix[1][1] != (1 << 16) ||
3220         display_matrix[2][2] != (1 << 30) ||
3221         display_matrix[0][1] || display_matrix[0][2] ||
3222         display_matrix[1][0] || display_matrix[1][2] ||
3223         display_matrix[2][0] || display_matrix[2][1]) {
3224         int i, j;
3225         double rotate;
3226
3227         av_freep(&sc->display_matrix);
3228         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3229         if (!sc->display_matrix)
3230             return AVERROR(ENOMEM);
3231
3232         for (i = 0; i < 3; i++)
3233             for (j = 0; j < 3; j++)
3234                 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3235
3236         rotate = av_display_rotation_get(sc->display_matrix);
3237         if (!isnan(rotate)) {
3238             char rotate_buf[64];
3239             rotate = -rotate;
3240             if (rotate < 0) // for backward compatibility
3241                 rotate += 360;
3242             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3243             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3244         }
3245     }
3246
3247     // transform the display width/height according to the matrix
3248     // to keep the same scale, use [width height 1<<16]
3249     if (width && height && sc->display_matrix) {
3250         double disp_transform[2];
3251
3252 #define SQR(a) ((a)*(double)(a))
3253         for (i = 0; i < 2; i++)
3254             disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));
3255
3256         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
3257             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3258             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3259             st->sample_aspect_ratio = av_d2q(
3260                 disp_transform[0] / disp_transform[1],
3261                 INT_MAX);
3262     }
3263     return 0;
3264 }
3265
3266 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3267 {
3268     MOVFragment *frag = &c->fragment;
3269     MOVTrackExt *trex = NULL;
3270     MOVFragmentIndex* index = NULL;
3271     int flags, track_id, i;
3272
3273     avio_r8(pb); /* version */
3274     flags = avio_rb24(pb);
3275
3276     track_id = avio_rb32(pb);
3277     if (!track_id)
3278         return AVERROR_INVALIDDATA;
3279     frag->track_id = track_id;
3280     for (i = 0; i < c->trex_count; i++)
3281         if (c->trex_data[i].track_id == frag->track_id) {
3282             trex = &c->trex_data[i];
3283             break;
3284         }
3285     if (!trex) {
3286         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3287         return AVERROR_INVALIDDATA;
3288     }
3289     for (i = 0; i < c->fragment_index_count; i++) {
3290         MOVFragmentIndex* candidate = c->fragment_index_data[i];
3291         if (candidate->track_id == frag->track_id) {
3292             av_log(c->fc, AV_LOG_DEBUG,
3293                    "found fragment index for track %u\n", frag->track_id);
3294             index = candidate;
3295             break;
3296         }
3297     }
3298
3299     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3300                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3301                              frag->moof_offset : frag->implicit_offset;
3302     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3303
3304     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3305                      avio_rb32(pb) : trex->duration;
3306     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
3307                      avio_rb32(pb) : trex->size;
3308     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
3309                      avio_rb32(pb) : trex->flags;
3310     frag->time     = AV_NOPTS_VALUE;
3311     if (index) {
3312         int i, found = 0;
3313         for (i = index->current_item; i < index->item_count; i++) {
3314             if (frag->implicit_offset == index->items[i].moof_offset) {
3315                 av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3316                         "for track %u and moof_offset %"PRId64"\n",
3317                         frag->track_id, index->items[i].moof_offset);
3318                 frag->time = index->items[i].time;
3319                 index->current_item = i + 1;
3320                 found = 1;
3321             }
3322         }
3323         if (!found) {
3324             av_log(c->fc, AV_LOG_WARNING, "track %u has a fragment index "
3325                    "but it doesn't have an (in-order) entry for moof_offset "
3326                    "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3327         }
3328     }
3329     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3330     return 0;
3331 }
3332
3333 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3334 {
3335     c->chapter_track = avio_rb32(pb);
3336     return 0;
3337 }
3338
3339 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3340 {
3341     MOVTrackExt *trex;
3342     int err;
3343
3344     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3345         return AVERROR_INVALIDDATA;
3346     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3347                                  sizeof(*c->trex_data))) < 0) {
3348         c->trex_count = 0;
3349         return err;
3350     }
3351
3352     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3353
3354     trex = &c->trex_data[c->trex_count++];
3355     avio_r8(pb); /* version */
3356     avio_rb24(pb); /* flags */
3357     trex->track_id = avio_rb32(pb);
3358     trex->stsd_id  = avio_rb32(pb);
3359     trex->duration = avio_rb32(pb);
3360     trex->size     = avio_rb32(pb);
3361     trex->flags    = avio_rb32(pb);
3362     return 0;
3363 }
3364
3365 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3366 {
3367     MOVFragment *frag = &c->fragment;
3368     AVStream *st = NULL;
3369     MOVStreamContext *sc;
3370     int version, i;
3371
3372     for (i = 0; i < c->fc->nb_streams; i++) {
3373         if (c->fc->streams[i]->id == frag->track_id) {
3374             st = c->fc->streams[i];
3375             break;
3376         }
3377     }
3378     if (!st) {
3379         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3380         return AVERROR_INVALIDDATA;
3381     }
3382     sc = st->priv_data;
3383     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3384         return 0;
3385     version = avio_r8(pb);
3386     avio_rb24(pb); /* flags */
3387     if (version) {
3388         sc->track_end = avio_rb64(pb);
3389     } else {
3390         sc->track_end = avio_rb32(pb);
3391     }
3392     return 0;
3393 }
3394
3395 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3396 {
3397     MOVFragment *frag = &c->fragment;
3398     AVStream *st = NULL;
3399     MOVStreamContext *sc;
3400     MOVStts *ctts_data;
3401     uint64_t offset;
3402     int64_t dts;
3403     int data_offset = 0;
3404     unsigned entries, first_sample_flags = frag->flags;
3405     int flags, distance, i, found_keyframe = 0, err;
3406
3407     for (i = 0; i < c->fc->nb_streams; i++) {
3408         if (c->fc->streams[i]->id == frag->track_id) {
3409             st = c->fc->streams[i];
3410             break;
3411         }
3412     }
3413     if (!st) {
3414         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3415         return AVERROR_INVALIDDATA;
3416     }
3417     sc = st->priv_data;
3418     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3419         return 0;
3420     avio_r8(pb); /* version */
3421     flags = avio_rb24(pb);
3422     entries = avio_rb32(pb);
3423     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3424
3425     /* Always assume the presence of composition time offsets.
3426      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3427      *  1) in the initial movie, there are no samples.
3428      *  2) in the first movie fragment, there is only one sample without composition time offset.
3429      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
3430     if (!sc->ctts_count && sc->sample_count)
3431     {
3432         /* Complement ctts table if moov atom doesn't have ctts atom. */
3433         ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3434         if (!ctts_data)
3435             return AVERROR(ENOMEM);
3436         sc->ctts_data = ctts_data;
3437         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3438         sc->ctts_data[sc->ctts_count].duration = 0;
3439         sc->ctts_count++;
3440     }
3441     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3442         return AVERROR_INVALIDDATA;
3443     if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3444                                  sizeof(*sc->ctts_data))) < 0) {
3445         sc->ctts_count = 0;
3446         return err;
3447     }
3448     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
3449     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3450     dts    = sc->track_end - sc->time_offset;
3451     offset = frag->base_data_offset + data_offset;
3452     distance = 0;
3453     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3454     for (i = 0; i < entries && !pb->eof_reached; i++) {
3455         unsigned sample_size = frag->size;
3456         int sample_flags = i ? frag->flags : first_sample_flags;
3457         unsigned sample_duration = frag->duration;
3458         int keyframe = 0;
3459
3460         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3461         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
3462         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
3463         sc->ctts_data[sc->ctts_count].count = 1;
3464         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3465                                                   avio_rb32(pb) : 0;
3466         mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3467         if (frag->time != AV_NOPTS_VALUE) {
3468             if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3469                 int64_t pts = frag->time;
3470                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3471                         " sc->dts_shift %d ctts.duration %d"
3472                         " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3473                         sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3474                         sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3475                 dts = pts - sc->dts_shift;
3476                 if (flags & MOV_TRUN_SAMPLE_CTS) {
3477                     dts -= sc->ctts_data[sc->ctts_count].duration;
3478                 } else {
3479                     dts -= sc->time_offset;
3480                 }
3481                 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3482             } else {
3483                 dts = frag->time;
3484                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3485                         ", using it for dts\n", dts);
3486             }
3487             frag->time = AV_NOPTS_VALUE;
3488         }
3489         sc->ctts_count++;
3490         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3491             keyframe = 1;
3492         else if (!found_keyframe)
3493             keyframe = found_keyframe =
3494                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3495                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3496         if (keyframe)
3497             distance = 0;
3498         err = av_add_index_entry(st, offset, dts, sample_size, distance,
3499                                  keyframe ? AVINDEX_KEYFRAME : 0);
3500         if (err < 0) {
3501             av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3502         }
3503         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3504                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3505                 offset, dts, sample_size, distance, keyframe);
3506         distance++;
3507         dts += sample_duration;
3508         offset += sample_size;
3509         sc->data_size += sample_size;
3510         sc->duration_for_fps += sample_duration;
3511         sc->nb_frames_for_fps ++;
3512     }
3513
3514     if (pb->eof_reached)
3515         return AVERROR_EOF;
3516
3517     frag->implicit_offset = offset;
3518     st->duration = sc->track_end = dts + sc->time_offset;
3519     return 0;
3520 }
3521
3522 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3523 /* like the files created with Adobe Premiere 5.0, for samples see */
3524 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3525 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3526 {
3527     int err;
3528
3529     if (atom.size < 8)
3530         return 0; /* continue */
3531     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3532         avio_skip(pb, atom.size - 4);
3533         return 0;
3534     }
3535     atom.type = avio_rl32(pb);
3536     atom.size -= 8;
3537     if (atom.type != MKTAG('m','d','a','t')) {
3538         avio_skip(pb, atom.size);
3539         return 0;
3540     }
3541     err = mov_read_mdat(c, pb, atom);
3542     return err;
3543 }
3544
3545 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3546 {
3547 #if CONFIG_ZLIB
3548     AVIOContext ctx;
3549     uint8_t *cmov_data;
3550     uint8_t *moov_data; /* uncompressed data */
3551     long cmov_len, moov_len;
3552     int ret = -1;
3553
3554     avio_rb32(pb); /* dcom atom */
3555     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3556         return AVERROR_INVALIDDATA;
3557     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3558         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3559         return AVERROR_INVALIDDATA;
3560     }
3561     avio_rb32(pb); /* cmvd atom */
3562     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3563         return AVERROR_INVALIDDATA;
3564     moov_len = avio_rb32(pb); /* uncompressed size */
3565     cmov_len = atom.size - 6 * 4;
3566
3567     cmov_data = av_malloc(cmov_len);
3568     if (!cmov_data)
3569         return AVERROR(ENOMEM);
3570     moov_data = av_malloc(moov_len);
3571     if (!moov_data) {
3572         av_free(cmov_data);
3573         return AVERROR(ENOMEM);
3574     }
3575     ret = ffio_read_size(pb, cmov_data, cmov_len);
3576     if (ret < 0)
3577         goto free_and_return;
3578
3579     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3580         goto free_and_return;
3581     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3582         goto free_and_return;
3583     ctx.seekable = AVIO_SEEKABLE_NORMAL;
3584     atom.type = MKTAG('m','o','o','v');
3585     atom.size = moov_len;
3586     ret = mov_read_default(c, &ctx, atom);
3587 free_and_return:
3588     av_free(moov_data);
3589     av_free(cmov_data);
3590     return ret;
3591 #else
3592     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3593     return AVERROR(ENOSYS);
3594 #endif
3595 }
3596
3597 /* edit list atom */
3598 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3599 {
3600     MOVStreamContext *sc;
3601     int i, edit_count, version;
3602
3603     if (c->fc->nb_streams < 1 || c->ignore_editlist)
3604         return 0;
3605     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3606
3607     version = avio_r8(pb); /* version */
3608     avio_rb24(pb); /* flags */
3609     edit_count = avio_rb32(pb); /* entries */
3610
3611     if (!edit_count)
3612         return 0;
3613     if (sc->elst_data)
3614         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3615     av_free(sc->elst_data);
3616     sc->elst_count = 0;
3617     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3618     if (!sc->elst_data)
3619         return AVERROR(ENOMEM);
3620
3621     av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3622     for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3623         MOVElst *e = &sc->elst_data[i];
3624
3625         if (version == 1) {
3626             e->duration = avio_rb64(pb);
3627             e->time     = avio_rb64(pb);
3628         } else {
3629             e->duration = avio_rb32(pb); /* segment duration */
3630             e->time     = (int32_t)avio_rb32(pb); /* media time */
3631         }
3632         e->rate = avio_rb32(pb) / 65536.0;
3633         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3634                 e->duration, e->time, e->rate);
3635     }
3636     sc->elst_count = i;
3637
3638     return 0;
3639 }
3640
3641 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3642 {
3643     MOVStreamContext *sc;
3644
3645     if (c->fc->nb_streams < 1)
3646         return AVERROR_INVALIDDATA;
3647     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3648     sc->timecode_track = avio_rb32(pb);
3649     return 0;
3650 }
3651
3652 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3653 {
3654     int ret;
3655     uint8_t uuid[16];
3656     static const uint8_t uuid_isml_manifest[] = {
3657         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3658         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3659     };
3660
3661     if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3662         return AVERROR_INVALIDDATA;
3663
3664     ret = avio_read(pb, uuid, sizeof(uuid));
3665     if (ret < 0) {
3666         return ret;
3667     } else if (ret != sizeof(uuid)) {
3668         return AVERROR_INVALIDDATA;
3669     }
3670     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3671         uint8_t *buffer, *ptr;
3672         char *endptr;
3673         size_t len = atom.size - sizeof(uuid);
3674
3675         if (len < 4) {
3676             return AVERROR_INVALIDDATA;
3677         }
3678         ret = avio_skip(pb, 4); // zeroes
3679         len -= 4;
3680
3681         buffer = av_mallocz(len + 1);
3682         if (!buffer) {
3683             return AVERROR(ENOMEM);
3684         }
3685         ret = avio_read(pb, buffer, len);
3686         if (ret < 0) {
3687             av_free(buffer);
3688             return ret;
3689         } else if (ret != len) {
3690             av_free(buffer);
3691             return AVERROR_INVALIDDATA;
3692         }
3693
3694         ptr = buffer;
3695         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3696             ptr += sizeof("systemBitrate=\"") - 1;
3697             c->bitrates_count++;
3698             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3699             if (!c->bitrates) {
3700                 c->bitrates_count = 0;
3701                 av_free(buffer);
3702                 return AVERROR(ENOMEM);
3703             }
3704             errno = 0;
3705             ret = strtol(ptr, &endptr, 10);
3706             if (ret < 0 || errno || *endptr != '"') {
3707                 c->bitrates[c->bitrates_count - 1] = 0;
3708             } else {
3709                 c->bitrates[c->bitrates_count - 1] = ret;
3710             }
3711         }
3712
3713         av_free(buffer);
3714     }
3715     return 0;
3716 }
3717
3718 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3719 {
3720     int ret;
3721     uint8_t content[16];
3722
3723     if (atom.size < 8)
3724         return 0;
3725
3726     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3727     if (ret < 0)
3728         return ret;
3729
3730     if (   !c->found_moov
3731         && !c->found_mdat
3732         && !memcmp(content, "Anevia\x1A\x1A", 8)
3733         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3734         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3735     }
3736
3737     return 0;
3738 }
3739
3740 static const MOVParseTableEntry mov_default_parse_table[] = {
3741 { MKTAG('A','C','L','R'), mov_read_aclr },
3742 { MKTAG('A','P','R','G'), mov_read_avid },
3743 { MKTAG('A','A','L','P'), mov_read_avid },
3744 { MKTAG('A','R','E','S'), mov_read_ares },
3745 { MKTAG('a','v','s','s'), mov_read_avss },
3746 { MKTAG('c','h','p','l'), mov_read_chpl },
3747 { MKTAG('c','o','6','4'), mov_read_stco },
3748 { MKTAG('c','o','l','r'), mov_read_colr },
3749 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3750 { MKTAG('d','i','n','f'), mov_read_default },
3751 { MKTAG('D','p','x','E'), mov_read_dpxe },
3752 { MKTAG('d','r','e','f'), mov_read_dref },
3753 { MKTAG('e','d','t','s'), mov_read_default },
3754 { MKTAG('e','l','s','t'), mov_read_elst },
3755 { MKTAG('e','n','d','a'), mov_read_enda },
3756 { MKTAG('f','i','e','l'), mov_read_fiel },
3757 { MKTAG('a','d','r','m'), mov_read_adrm },
3758 { MKTAG('f','t','y','p'), mov_read_ftyp },
3759 { MKTAG('g','l','b','l'), mov_read_glbl },
3760 { MKTAG('h','d','l','r'), mov_read_hdlr },
3761 { MKTAG('i','l','s','t'), mov_read_ilst },
3762 { MKTAG('j','p','2','h'), mov_read_jp2h },
3763 { MKTAG('m','d','a','t'), mov_read_mdat },
3764 { MKTAG('m','d','h','d'), mov_read_mdhd },
3765 { MKTAG('m','d','i','a'), mov_read_default },
3766 { MKTAG('m','e','t','a'), mov_read_meta },
3767 { MKTAG('m','i','n','f'), mov_read_default },
3768 { MKTAG('m','o','o','f'), mov_read_moof },
3769 { MKTAG('m','o','o','v'), mov_read_moov },
3770 { MKTAG('m','v','e','x'), mov_read_default },
3771 { MKTAG('m','v','h','d'), mov_read_mvhd },
3772 { MKTAG('S','M','I',' '), mov_read_svq3 },
3773 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
3774 { MKTAG('a','v','c','C'), mov_read_glbl },
3775 { MKTAG('p','a','s','p'), mov_read_pasp },
3776 { MKTAG('s','t','b','l'), mov_read_default },
3777 { MKTAG('s','t','c','o'), mov_read_stco },
3778 { MKTAG('s','t','p','s'), mov_read_stps },
3779 { MKTAG('s','t','r','f'), mov_read_strf },
3780 { MKTAG('s','t','s','c'), mov_read_stsc },
3781 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3782 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3783 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3784 { MKTAG('s','t','t','s'), mov_read_stts },
3785 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3786 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3787 { MKTAG('t','f','d','t'), mov_read_tfdt },
3788 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3789 { MKTAG('t','r','a','k'), mov_read_trak },
3790 { MKTAG('t','r','a','f'), mov_read_default },
3791 { MKTAG('t','r','e','f'), mov_read_default },
3792 { MKTAG('t','m','c','d'), mov_read_tmcd },
3793 { MKTAG('c','h','a','p'), mov_read_chap },
3794 { MKTAG('t','r','e','x'), mov_read_trex },
3795 { MKTAG('t','r','u','n'), mov_read_trun },
3796 { MKTAG('u','d','t','a'), mov_read_default },
3797 { MKTAG('w','a','v','e'), mov_read_wave },
3798 { MKTAG('e','s','d','s'), mov_read_esds },
3799 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3800 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3801 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3802 { MKTAG('w','f','e','x'), mov_read_wfex },
3803 { MKTAG('c','m','o','v'), mov_read_cmov },
3804 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3805 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3806 { MKTAG('s','b','g','p'), mov_read_sbgp },
3807 { MKTAG('h','v','c','C'), mov_read_glbl },
3808 { MKTAG('u','u','i','d'), mov_read_uuid },
3809 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
3810 { MKTAG('f','r','e','e'), mov_read_free },
3811 { MKTAG('-','-','-','-'), mov_read_custom },
3812 { 0, NULL }
3813 };
3814
3815 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3816 {
3817     int64_t total_size = 0;
3818     MOVAtom a;
3819     int i;
3820
3821     if (c->atom_depth > 10) {
3822         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
3823         return AVERROR_INVALIDDATA;
3824     }
3825     c->atom_depth ++;
3826
3827     if (atom.size < 0)
3828         atom.size = INT64_MAX;
3829     while (total_size + 8 <= atom.size && !avio_feof(pb)) {
3830         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3831         a.size = atom.size;
3832         a.type=0;
3833         if (atom.size >= 8) {
3834             a.size = avio_rb32(pb);
3835             a.type = avio_rl32(pb);
3836             if (a.type == MKTAG('f','r','e','e') &&
3837                 a.size >= 8 &&
3838                 c->moov_retry) {
3839                 uint8_t buf[8];
3840                 uint32_t *type = (uint32_t *)buf + 1;
3841                 if (avio_read(pb, buf, 8) != 8)
3842                     return AVERROR_INVALIDDATA;
3843                 avio_seek(pb, -8, SEEK_CUR);
3844                 if (*type == MKTAG('m','v','h','d') ||
3845                     *type == MKTAG('c','m','o','v')) {
3846                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
3847                     a.type = MKTAG('m','o','o','v');
3848                 }
3849             }
3850             if (atom.type != MKTAG('r','o','o','t') &&
3851                 atom.type != MKTAG('m','o','o','v'))
3852             {
3853                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
3854                 {
3855                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
3856                     avio_skip(pb, -8);
3857                     c->atom_depth --;
3858                     return 0;
3859                 }
3860             }
3861             total_size += 8;
3862             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
3863                 a.size = avio_rb64(pb) - 8;
3864                 total_size += 8;
3865             }
3866         }
3867         av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3868                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3869         if (a.size == 0) {
3870             a.size = atom.size - total_size + 8;
3871         }
3872         a.size -= 8;
3873         if (a.size < 0)
3874             break;
3875         a.size = FFMIN(a.size, atom.size - total_size);
3876
3877         for (i = 0; mov_default_parse_table[i].type; i++)
3878             if (mov_default_parse_table[i].type == a.type) {
3879                 parse = mov_default_parse_table[i].parse;
3880                 break;
3881             }
3882
3883         // container is user data
3884         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3885                        atom.type == MKTAG('i','l','s','t')))
3886             parse = mov_read_udta_string;
3887
3888         if (!parse) { /* skip leaf atoms data */
3889             avio_skip(pb, a.size);
3890         } else {
3891             int64_t start_pos = avio_tell(pb);
3892             int64_t left;
3893             int err = parse(c, pb, a);
3894             if (err < 0) {
3895                 c->atom_depth --;
3896                 return err;
3897             }
3898             if (c->found_moov && c->found_mdat &&
3899                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3900                  start_pos + a.size == avio_size(pb))) {
3901                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
3902                     c->next_root_atom = start_pos + a.size;
3903                 c->atom_depth --;
3904                 return 0;
3905             }
3906             left = a.size - avio_tell(pb) + start_pos;
3907             if (left > 0) /* skip garbage at atom end */
3908                 avio_skip(pb, left);
3909             else if (left < 0) {
3910                 av_log(c->fc, AV_LOG_WARNING,
3911                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
3912                        (char*)&a.type, -left);
3913                 avio_seek(pb, left, SEEK_CUR);
3914             }
3915         }
3916
3917         total_size += a.size;
3918     }
3919
3920     if (total_size < atom.size && atom.size < 0x7ffff)
3921         avio_skip(pb, atom.size - total_size);
3922
3923     c->atom_depth --;
3924     return 0;
3925 }
3926
3927 static int mov_probe(AVProbeData *p)
3928 {
3929     int64_t offset;
3930     uint32_t tag;
3931     int score = 0;
3932     int moov_offset = -1;
3933
3934     /* check file header */
3935     offset = 0;
3936     for (;;) {
3937         /* ignore invalid offset */
3938         if ((offset + 8) > (unsigned int)p->buf_size)
3939             break;
3940         tag = AV_RL32(p->buf + offset + 4);
3941         switch(tag) {
3942         /* check for obvious tags */
3943         case MKTAG('m','o','o','v'):
3944             moov_offset = offset + 4;
3945         case MKTAG('m','d','a','t'):
3946         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3947         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3948         case MKTAG('f','t','y','p'):
3949             if (AV_RB32(p->buf+offset) < 8 &&
3950                 (AV_RB32(p->buf+offset) != 1 ||
3951                  offset + 12 > (unsigned int)p->buf_size ||
3952                  AV_RB64(p->buf+offset + 8) == 0)) {
3953                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3954             } else if (tag == MKTAG('f','t','y','p') &&
3955                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
3956                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
3957                     )) {
3958                 score = FFMAX(score, 5);
3959             } else {
3960                 score = AVPROBE_SCORE_MAX;
3961             }
3962             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3963             break;
3964         /* those are more common words, so rate then a bit less */
3965         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3966         case MKTAG('w','i','d','e'):
3967         case MKTAG('f','r','e','e'):
3968         case MKTAG('j','u','n','k'):
3969         case MKTAG('p','i','c','t'):
3970             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
3971             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3972             break;
3973         case MKTAG(0x82,0x82,0x7f,0x7d):
3974         case MKTAG('s','k','i','p'):
3975         case MKTAG('u','u','i','d'):
3976         case MKTAG('p','r','f','l'):
3977             /* if we only find those cause probedata is too small at least rate them */
3978             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
3979             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3980             break;
3981         default:
3982             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
3983         }
3984     }
3985     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
3986         /* moov atom in the header - we should make sure that this is not a
3987          * MOV-packed MPEG-PS */
3988         offset = moov_offset;
3989
3990         while(offset < (p->buf_size - 16)){ /* Sufficient space */
3991                /* We found an actual hdlr atom */
3992             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
3993                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
3994                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
3995                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
3996                 /* We found a media handler reference atom describing an
3997                  * MPEG-PS-in-MOV, return a
3998                  * low score to force expanding the probe window until
3999                  * mpegps_probe finds what it needs */
4000                 return 5;
4001             }else
4002                 /* Keep looking */
4003                 offset+=2;
4004         }
4005     }
4006
4007     return score;
4008 }
4009
4010 // must be done after parsing all trak because there's no order requirement
4011 static void mov_read_chapters(AVFormatContext *s)
4012 {
4013     MOVContext *mov = s->priv_data;
4014     AVStream *st = NULL;
4015     MOVStreamContext *sc;
4016     int64_t cur_pos;
4017     int i;
4018
4019     for (i = 0; i < s->nb_streams; i++)
4020         if (s->streams[i]->id == mov->chapter_track) {
4021             st = s->streams[i];
4022             break;
4023         }
4024     if (!st) {
4025         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4026         return;
4027     }
4028
4029     st->discard = AVDISCARD_ALL;
4030     sc = st->priv_data;
4031     cur_pos = avio_tell(sc->pb);
4032
4033     for (i = 0; i < st->nb_index_entries; i++) {
4034         AVIndexEntry *sample = &st->index_entries[i];
4035         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4036         uint8_t *title;
4037         uint16_t ch;
4038         int len, title_len;
4039
4040         if (end < sample->timestamp) {
4041             av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4042             end = AV_NOPTS_VALUE;
4043         }
4044
4045         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4046             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4047             goto finish;
4048         }
4049
4050         // the first two bytes are the length of the title
4051         len = avio_rb16(sc->pb);
4052         if (len > sample->size-2)
4053             continue;
4054         title_len = 2*len + 1;
4055         if (!(title = av_mallocz(title_len)))
4056             goto finish;
4057
4058         // The samples could theoretically be in any encoding if there's an encd
4059         // atom following, but in practice are only utf-8 or utf-16, distinguished
4060         // instead by the presence of a BOM
4061         if (!len) {
4062             title[0] = 0;
4063         } else {
4064             ch = avio_rb16(sc->pb);
4065             if (ch == 0xfeff)
4066                 avio_get_str16be(sc->pb, len, title, title_len);
4067             else if (ch == 0xfffe)
4068                 avio_get_str16le(sc->pb, len, title, title_len);
4069             else {
4070                 AV_WB16(title, ch);
4071                 if (len == 1 || len == 2)
4072                     title[len] = 0;
4073                 else
4074                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4075             }
4076         }
4077
4078         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4079         av_freep(&title);
4080     }
4081 finish:
4082     avio_seek(sc->pb, cur_pos, SEEK_SET);
4083 }
4084
4085 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4086                                              uint32_t value, int flags)
4087 {
4088     AVTimecode tc;
4089     char buf[AV_TIMECODE_STR_SIZE];
4090     AVRational rate = {st->codec->time_base.den,
4091                        st->codec->time_base.num};
4092     int ret = av_timecode_init(&tc, rate, flags, 0, s);
4093     if (ret < 0)
4094         return ret;
4095     av_dict_set(&st->metadata, "timecode",
4096                 av_timecode_make_string(&tc, buf, value), 0);
4097     return 0;
4098 }
4099
4100 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4101 {
4102     MOVStreamContext *sc = st->priv_data;
4103     int flags = 0;
4104     int64_t cur_pos = avio_tell(sc->pb);
4105     uint32_t value;
4106
4107     if (!st->nb_index_entries)
4108         return -1;
4109
4110     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4111     value = avio_rb32(s->pb);
4112
4113     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4114     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4115     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4116
4117     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4118      * not the case) and thus assume "frame number format" instead of QT one.
4119      * No sample with tmcd track can be found with a QT timecode at the moment,
4120      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4121      * format). */
4122     parse_timecode_in_framenum_format(s, st, value, flags);
4123
4124     avio_seek(sc->pb, cur_pos, SEEK_SET);
4125     return 0;
4126 }
4127
4128 static int mov_read_close(AVFormatContext *s)
4129 {
4130     MOVContext *mov = s->priv_data;
4131     int i, j;
4132
4133     for (i = 0; i < s->nb_streams; i++) {
4134         AVStream *st = s->streams[i];
4135         MOVStreamContext *sc = st->priv_data;
4136
4137         if (!sc)
4138             continue;
4139
4140         av_freep(&sc->ctts_data);
4141         for (j = 0; j < sc->drefs_count; j++) {
4142             av_freep(&sc->drefs[j].path);
4143             av_freep(&sc->drefs[j].dir);
4144         }
4145         av_freep(&sc->drefs);
4146
4147         sc->drefs_count = 0;
4148
4149         if (!sc->pb_is_copied)
4150             avio_closep(&sc->pb);
4151
4152         sc->pb = NULL;
4153         av_freep(&sc->chunk_offsets);
4154         av_freep(&sc->stsc_data);
4155         av_freep(&sc->sample_sizes);
4156         av_freep(&sc->keyframes);
4157         av_freep(&sc->stts_data);
4158         av_freep(&sc->stps_data);
4159         av_freep(&sc->elst_data);
4160         av_freep(&sc->rap_group);
4161         av_freep(&sc->display_matrix);
4162     }
4163
4164     if (mov->dv_demux) {
4165         avformat_free_context(mov->dv_fctx);
4166         mov->dv_fctx = NULL;
4167     }
4168
4169     av_freep(&mov->trex_data);
4170     av_freep(&mov->bitrates);
4171
4172     for (i = 0; i < mov->fragment_index_count; i++) {
4173         MOVFragmentIndex* index = mov->fragment_index_data[i];
4174         av_freep(&index->items);
4175         av_freep(&mov->fragment_index_data[i]);
4176     }
4177     av_freep(&mov->fragment_index_data);
4178
4179     av_freep(&mov->aes_decrypt);
4180
4181     return 0;
4182 }
4183
4184 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4185 {
4186     int i;
4187
4188     for (i = 0; i < s->nb_streams; i++) {
4189         AVStream *st = s->streams[i];
4190         MOVStreamContext *sc = st->priv_data;
4191
4192         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4193             sc->timecode_track == tmcd_id)
4194             return 1;
4195     }
4196     return 0;
4197 }
4198
4199 /* look for a tmcd track not referenced by any video track, and export it globally */
4200 static void export_orphan_timecode(AVFormatContext *s)
4201 {
4202     int i;
4203
4204     for (i = 0; i < s->nb_streams; i++) {
4205         AVStream *st = s->streams[i];
4206
4207         if (st->codec->codec_tag  == MKTAG('t','m','c','d') &&
4208             !tmcd_is_referenced(s, i + 1)) {
4209             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4210             if (tcr) {
4211                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4212                 break;
4213             }
4214         }
4215     }
4216 }
4217
4218 static int read_tfra(MOVContext *mov, AVIOContext *f)
4219 {
4220     MOVFragmentIndex* index = NULL;
4221     int version, fieldlength, i, j;
4222     int64_t pos = avio_tell(f);
4223     uint32_t size = avio_rb32(f);
4224     void *tmp;
4225
4226     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4227         return 1;
4228     }
4229     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4230     index = av_mallocz(sizeof(MOVFragmentIndex));
4231     if (!index) {
4232         return AVERROR(ENOMEM);
4233     }
4234
4235     tmp = av_realloc_array(mov->fragment_index_data,
4236                            mov->fragment_index_count + 1,
4237                            sizeof(MOVFragmentIndex*));
4238     if (!tmp) {
4239         av_freep(&index);
4240         return AVERROR(ENOMEM);
4241     }
4242     mov->fragment_index_data = tmp;
4243     mov->fragment_index_data[mov->fragment_index_count++] = index;
4244
4245     version = avio_r8(f);
4246     avio_rb24(f);
4247     index->track_id = avio_rb32(f);
4248     fieldlength = avio_rb32(f);
4249     index->item_count = avio_rb32(f);
4250     index->items = av_mallocz_array(
4251             index->item_count, sizeof(MOVFragmentIndexItem));
4252     if (!index->items) {
4253         index->item_count = 0;
4254         return AVERROR(ENOMEM);
4255     }
4256     for (i = 0; i < index->item_count; i++) {
4257         int64_t time, offset;
4258         if (version == 1) {
4259             time   = avio_rb64(f);
4260             offset = avio_rb64(f);
4261         } else {
4262             time   = avio_rb32(f);
4263             offset = avio_rb32(f);
4264         }
4265         index->items[i].time = time;
4266         index->items[i].moof_offset = offset;
4267         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4268             avio_r8(f);
4269         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4270             avio_r8(f);
4271         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4272             avio_r8(f);
4273     }
4274
4275     avio_seek(f, pos + size, SEEK_SET);
4276     return 0;
4277 }
4278
4279 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4280 {
4281     int64_t stream_size = avio_size(f);
4282     int64_t original_pos = avio_tell(f);
4283     int64_t seek_ret;
4284     int32_t mfra_size;
4285     int ret = -1;
4286     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4287         ret = seek_ret;
4288         goto fail;
4289     }
4290     mfra_size = avio_rb32(f);
4291     if (mfra_size < 0 || mfra_size > stream_size) {
4292         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4293         goto fail;
4294     }
4295     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4296         ret = seek_ret;
4297         goto fail;
4298     }
4299     if (avio_rb32(f) != mfra_size) {
4300         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4301         goto fail;
4302     }
4303     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4304         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4305         goto fail;
4306     }
4307     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4308     do {
4309         ret = read_tfra(c, f);
4310         if (ret < 0)
4311             goto fail;
4312     } while (!ret);
4313     ret = 0;
4314 fail:
4315     seek_ret = avio_seek(f, original_pos, SEEK_SET);
4316     if (seek_ret < 0) {
4317         av_log(c->fc, AV_LOG_ERROR,
4318                "failed to seek back after looking for mfra\n");
4319         ret = seek_ret;
4320     }
4321     return ret;
4322 }
4323
4324 static int mov_read_header(AVFormatContext *s)
4325 {
4326     MOVContext *mov = s->priv_data;
4327     AVIOContext *pb = s->pb;
4328     int j, err;
4329     MOVAtom atom = { AV_RL32("root") };
4330     int i;
4331
4332     mov->fc = s;
4333     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4334     if (pb->seekable)
4335         atom.size = avio_size(pb);
4336     else
4337         atom.size = INT64_MAX;
4338
4339     /* check MOV header */
4340     do {
4341     if (mov->moov_retry)
4342         avio_seek(pb, 0, SEEK_SET);
4343     if ((err = mov_read_default(mov, pb, atom)) < 0) {
4344         av_log(s, AV_LOG_ERROR, "error reading header\n");
4345         mov_read_close(s);
4346         return err;
4347     }
4348     } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4349     if (!mov->found_moov) {
4350         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4351         mov_read_close(s);
4352         return AVERROR_INVALIDDATA;
4353     }
4354     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4355
4356     if (pb->seekable) {
4357         if (mov->chapter_track > 0)
4358             mov_read_chapters(s);
4359         for (i = 0; i < s->nb_streams; i++)
4360             if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4361                 mov_read_timecode_track(s, s->streams[i]);
4362     }
4363
4364     /* copy timecode metadata from tmcd tracks to the related video streams */
4365     for (i = 0; i < s->nb_streams; i++) {
4366         AVStream *st = s->streams[i];
4367         MOVStreamContext *sc = st->priv_data;
4368         if (sc->timecode_track > 0) {
4369             AVDictionaryEntry *tcr;
4370             int tmcd_st_id = -1;
4371
4372             for (j = 0; j < s->nb_streams; j++)
4373                 if (s->streams[j]->id == sc->timecode_track)
4374                     tmcd_st_id = j;
4375
4376             if (tmcd_st_id < 0 || tmcd_st_id == i)
4377                 continue;
4378             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4379             if (tcr)
4380                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4381         }
4382     }
4383     export_orphan_timecode(s);
4384
4385     for (i = 0; i < s->nb_streams; i++) {
4386         AVStream *st = s->streams[i];
4387         MOVStreamContext *sc = st->priv_data;
4388         fix_timescale(mov, sc);
4389         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4390             st->skip_samples = sc->start_pad;
4391         }
4392         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4393             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4394                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4395         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4396             if (st->codec->width <= 0 || st->codec->height <= 0) {
4397                 st->codec->width  = sc->width;
4398                 st->codec->height = sc->height;
4399             }
4400             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4401                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4402                     return err;
4403             }
4404         }
4405     }
4406
4407     if (mov->trex_data) {
4408         for (i = 0; i < s->nb_streams; i++) {
4409             AVStream *st = s->streams[i];
4410             MOVStreamContext *sc = st->priv_data;
4411             if (st->duration > 0)
4412                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4413         }
4414     }
4415
4416     if (mov->use_mfra_for > 0) {
4417         for (i = 0; i < s->nb_streams; i++) {
4418             AVStream *st = s->streams[i];
4419             MOVStreamContext *sc = st->priv_data;
4420             if (sc->duration_for_fps > 0) {
4421                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4422                     sc->duration_for_fps;
4423             }
4424         }
4425     }
4426
4427     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4428         if (mov->bitrates[i]) {
4429             s->streams[i]->codec->bit_rate = mov->bitrates[i];
4430         }
4431     }
4432
4433     ff_rfps_calculate(s);
4434
4435     for (i = 0; i < s->nb_streams; i++) {
4436         AVStream *st = s->streams[i];
4437         MOVStreamContext *sc = st->priv_data;
4438
4439         switch (st->codec->codec_type) {
4440         case AVMEDIA_TYPE_AUDIO:
4441             err = ff_replaygain_export(st, s->metadata);
4442             if (err < 0) {
4443                 mov_read_close(s);
4444                 return err;
4445             }
4446             break;
4447         case AVMEDIA_TYPE_VIDEO:
4448             if (sc->display_matrix) {
4449                 AVPacketSideData *sd, *tmp;
4450
4451                 tmp = av_realloc_array(st->side_data,
4452                                        st->nb_side_data + 1, sizeof(*tmp));
4453                 if (!tmp)
4454                     return AVERROR(ENOMEM);
4455
4456                 st->side_data = tmp;
4457                 st->nb_side_data++;
4458
4459                 sd = &st->side_data[st->nb_side_data - 1];
4460                 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4461                 sd->size = sizeof(int32_t) * 9;
4462                 sd->data = (uint8_t*)sc->display_matrix;
4463                 sc->display_matrix = NULL;
4464             }
4465             break;
4466         }
4467     }
4468     ff_configure_buffers_for_index(s, AV_TIME_BASE);
4469
4470     return 0;
4471 }
4472
4473 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
4474 {
4475     AVIndexEntry *sample = NULL;
4476     int64_t best_dts = INT64_MAX;
4477     int i;
4478     for (i = 0; i < s->nb_streams; i++) {
4479         AVStream *avst = s->streams[i];
4480         MOVStreamContext *msc = avst->priv_data;
4481         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
4482             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
4483             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
4484             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
4485             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
4486                 (s->pb->seekable &&
4487                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
4488                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
4489                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
4490                 sample = current_sample;
4491                 best_dts = dts;
4492                 *st = avst;
4493             }
4494         }
4495     }
4496     return sample;
4497 }
4498
4499 static int should_retry(AVIOContext *pb, int error_code) {
4500     if (error_code == AVERROR_EOF || avio_feof(pb))
4501         return 0;
4502
4503     return 1;
4504 }
4505
4506 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
4507 {
4508     MOVContext *mov = s->priv_data;
4509     MOVStreamContext *sc;
4510     AVIndexEntry *sample;
4511     AVStream *st = NULL;
4512     int ret;
4513     mov->fc = s;
4514  retry:
4515     sample = mov_find_next_sample(s, &st);
4516     if (!sample) {
4517         mov->found_mdat = 0;
4518         if (!mov->next_root_atom)
4519             return AVERROR_EOF;
4520         if (avio_seek(s->pb, mov->next_root_atom, SEEK_SET) != mov->next_root_atom) {
4521             av_log(mov->fc, AV_LOG_ERROR, "next root atom offset 0x%"PRIx64": partial file\n", mov->next_root_atom);
4522             return AVERROR_INVALIDDATA;
4523         }
4524         mov->next_root_atom = 0;
4525         if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
4526             avio_feof(s->pb))
4527             return AVERROR_EOF;
4528         av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
4529         goto retry;
4530     }
4531     sc = st->priv_data;
4532     /* must be done just before reading, to avoid infinite loop on sample */
4533     sc->current_sample++;
4534
4535     if (mov->next_root_atom) {
4536         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
4537         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
4538     }
4539
4540     if (st->discard != AVDISCARD_ALL) {
4541         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
4542         if (ret64 != sample->pos) {
4543             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
4544                    sc->ffindex, sample->pos);
4545             sc->current_sample -= should_retry(sc->pb, ret64);
4546             return AVERROR_INVALIDDATA;
4547         }
4548         ret = av_get_packet(sc->pb, pkt, sample->size);
4549         if (ret < 0) {
4550             sc->current_sample -= should_retry(sc->pb, ret);
4551             return ret;
4552         }
4553         if (sc->has_palette) {
4554             uint8_t *pal;
4555
4556             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
4557             if (!pal) {
4558                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
4559             } else {
4560                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
4561                 sc->has_palette = 0;
4562             }
4563         }
4564 #if CONFIG_DV_DEMUXER
4565         if (mov->dv_demux && sc->dv_audio_container) {
4566             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
4567             av_freep(&pkt->data);
4568             pkt->size = 0;
4569             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
4570             if (ret < 0)
4571                 return ret;
4572         }
4573 #endif
4574     }
4575
4576     pkt->stream_index = sc->ffindex;
4577     pkt->dts = sample->timestamp;
4578     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
4579         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
4580         /* update ctts context */
4581         sc->ctts_sample++;
4582         if (sc->ctts_index < sc->ctts_count &&
4583             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
4584             sc->ctts_index++;
4585             sc->ctts_sample = 0;
4586         }
4587         if (sc->wrong_dts)
4588             pkt->dts = AV_NOPTS_VALUE;
4589     } else {
4590         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
4591             st->index_entries[sc->current_sample].timestamp : st->duration;
4592         pkt->duration = next_dts - pkt->dts;
4593         pkt->pts = pkt->dts;
4594     }
4595     if (st->discard == AVDISCARD_ALL)
4596         goto retry;
4597     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
4598     pkt->pos = sample->pos;
4599
4600     if (mov->aax_mode)
4601         aax_filter(pkt->data, pkt->size, mov);
4602
4603     return 0;
4604 }
4605
4606 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
4607 {
4608     MOVStreamContext *sc = st->priv_data;
4609     int sample, time_sample;
4610     int i;
4611
4612     sample = av_index_search_timestamp(st, timestamp, flags);
4613     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
4614     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
4615         sample = 0;
4616     if (sample < 0) /* not sure what to do */
4617         return AVERROR_INVALIDDATA;
4618     sc->current_sample = sample;
4619     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
4620     /* adjust ctts index */
4621     if (sc->ctts_data) {
4622         time_sample = 0;
4623         for (i = 0; i < sc->ctts_count; i++) {
4624             int next = time_sample + sc->ctts_data[i].count;
4625             if (next > sc->current_sample) {
4626                 sc->ctts_index = i;
4627                 sc->ctts_sample = sc->current_sample - time_sample;
4628                 break;
4629             }
4630             time_sample = next;
4631         }
4632     }
4633     return sample;
4634 }
4635
4636 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
4637 {
4638     MOVContext *mc = s->priv_data;
4639     AVStream *st;
4640     int sample;
4641     int i;
4642
4643     if (stream_index >= s->nb_streams)
4644         return AVERROR_INVALIDDATA;
4645
4646     st = s->streams[stream_index];
4647     sample = mov_seek_stream(s, st, sample_time, flags);
4648     if (sample < 0)
4649         return sample;
4650
4651     if (mc->seek_individually) {
4652         /* adjust seek timestamp to found sample timestamp */
4653         int64_t seek_timestamp = st->index_entries[sample].timestamp;
4654
4655         for (i = 0; i < s->nb_streams; i++) {
4656             int64_t timestamp;
4657             MOVStreamContext *sc = s->streams[i]->priv_data;
4658             st = s->streams[i];
4659             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
4660
4661             if (stream_index == i)
4662                 continue;
4663
4664             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
4665             mov_seek_stream(s, st, timestamp, flags);
4666         }
4667     } else {
4668         for (i = 0; i < s->nb_streams; i++) {
4669             MOVStreamContext *sc;
4670             st = s->streams[i];
4671             sc = st->priv_data;
4672             sc->current_sample = 0;
4673         }
4674         while (1) {
4675             MOVStreamContext *sc;
4676             AVIndexEntry *entry = mov_find_next_sample(s, &st);
4677             if (!entry)
4678                 return AVERROR_INVALIDDATA;
4679             sc = st->priv_data;
4680             if (sc->ffindex == stream_index && sc->current_sample == sample)
4681                 break;
4682             sc->current_sample++;
4683         }
4684     }
4685     return 0;
4686 }
4687
4688 #define OFFSET(x) offsetof(MOVContext, x)
4689 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
4690 static const AVOption mov_options[] = {
4691     {"use_absolute_path",
4692         "allow using absolute path when opening alias, this is a possible security issue",
4693         OFFSET(use_absolute_path), AV_OPT_TYPE_INT, {.i64 = 0},
4694         0, 1, FLAGS},
4695     {"seek_streams_individually",
4696         "Seek each stream individually to the to the closest point",
4697         OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
4698         0, 1, FLAGS},
4699     {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_INT, {.i64 = 0},
4700         0, 1, FLAGS},
4701     {"use_mfra_for",
4702         "use mfra for fragment timestamps",
4703         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
4704         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
4705         "use_mfra_for"},
4706     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
4707         FLAGS, "use_mfra_for" },
4708     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
4709         FLAGS, "use_mfra_for" },
4710     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
4711         FLAGS, "use_mfra_for" },
4712     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
4713         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4714     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
4715         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
4716     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
4717         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
4718     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
4719         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
4720         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
4721         .flags = AV_OPT_FLAG_DECODING_PARAM },
4722     { NULL },
4723 };
4724
4725 static const AVClass mov_class = {
4726     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
4727     .item_name  = av_default_item_name,
4728     .option     = mov_options,
4729     .version    = LIBAVUTIL_VERSION_INT,
4730 };
4731
4732 AVInputFormat ff_mov_demuxer = {
4733     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
4734     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
4735     .priv_class     = &mov_class,
4736     .priv_data_size = sizeof(MOVContext),
4737     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
4738     .read_probe     = mov_probe,
4739     .read_header    = mov_read_header,
4740     .read_packet    = mov_read_packet,
4741     .read_close     = mov_read_close,
4742     .read_seek      = mov_read_seek,
4743     .flags          = AVFMT_NO_BYTE_SEEK,
4744 };