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