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