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