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