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