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