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