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