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