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