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