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