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