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