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