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