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