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