]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
fate: add audiomatch
[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         } else if (codec->codec_tag == MKTAG('A', 'V', 'd', '1') &&
1465                    atom.size >= 24) {
1466             int num, den;
1467             avio_skip(pb, 12);
1468             num = avio_rb32(pb);
1469             den = avio_rb32(pb);
1470             if (num <= 0 || den <= 0)
1471                 return 0;
1472             switch (avio_rb32(pb)) {
1473             case 2:
1474                 if (den >= INT_MAX / 2)
1475                     return 0;
1476                 den *= 2;
1477             case 1:
1478                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
1479                 c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
1480             default:
1481                 return 0;
1482             }
1483         }
1484     }
1485
1486     return mov_read_avid(c, pb, atom);
1487 }
1488
1489 static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1490 {
1491     int ret = 0;
1492     int length = 0;
1493     uint64_t original_size;
1494     if (c->fc->nb_streams >= 1) {
1495         AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
1496         if (codec->codec_id == AV_CODEC_ID_H264)
1497             return 0;
1498         if (atom.size == 16) {
1499             original_size = codec->extradata_size;
1500             ret = mov_realloc_extradata(codec, atom);
1501             if (!ret) {
1502                 length =  mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
1503                 if (length == atom.size) {
1504                     const uint8_t range_value = codec->extradata[original_size + 19];
1505                     switch (range_value) {
1506                     case 1:
1507                         codec->color_range = AVCOL_RANGE_MPEG;
1508                         break;
1509                     case 2:
1510                         codec->color_range = AVCOL_RANGE_JPEG;
1511                         break;
1512                     default:
1513                         av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
1514                         break;
1515                     }
1516                     ff_dlog(c, "color_range: %d\n", codec->color_range);
1517                 } else {
1518                   /* For some reason the whole atom was not added to the extradata */
1519                   av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
1520                 }
1521             } else {
1522                 av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
1523             }
1524         } else {
1525             av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
1526         }
1527     }
1528
1529     return ret;
1530 }
1531
1532 static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1533 {
1534     return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
1535 }
1536
1537 static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1538 {
1539     AVStream *st;
1540     int ret;
1541
1542     if (c->fc->nb_streams < 1)
1543         return 0;
1544     st = c->fc->streams[c->fc->nb_streams-1];
1545
1546     if ((uint64_t)atom.size > (1<<30))
1547         return AVERROR_INVALIDDATA;
1548
1549     if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
1550         st->codec->codec_id == AV_CODEC_ID_QDMC ||
1551         st->codec->codec_id == AV_CODEC_ID_SPEEX) {
1552         // pass all frma atom to codec, needed at least for QDMC and QDM2
1553         av_freep(&st->codec->extradata);
1554         ret = ff_get_extradata(st->codec, pb, atom.size);
1555         if (ret < 0)
1556             return ret;
1557     } else if (atom.size > 8) { /* to read frma, esds atoms */
1558         if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
1559             uint64_t buffer;
1560             ret = ffio_ensure_seekback(pb, 8);
1561             if (ret < 0)
1562                 return ret;
1563             buffer = avio_rb64(pb);
1564             atom.size -= 8;
1565             if (  (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
1566                 && buffer >> 32 <= atom.size
1567                 && buffer >> 32 >= 8) {
1568                 avio_skip(pb, -8);
1569                 atom.size += 8;
1570             } else if (!st->codec->extradata_size) {
1571 #define ALAC_EXTRADATA_SIZE 36
1572                 st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1573                 if (!st->codec->extradata)
1574                     return AVERROR(ENOMEM);
1575                 st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
1576                 AV_WB32(st->codec->extradata    , ALAC_EXTRADATA_SIZE);
1577                 AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
1578                 AV_WB64(st->codec->extradata + 12, buffer);
1579                 avio_read(pb, st->codec->extradata + 20, 16);
1580                 avio_skip(pb, atom.size - 24);
1581                 return 0;
1582             }
1583         }
1584         if ((ret = mov_read_default(c, pb, atom)) < 0)
1585             return ret;
1586     } else
1587         avio_skip(pb, atom.size);
1588     return 0;
1589 }
1590
1591 /**
1592  * This function reads atom content and puts data in extradata without tag
1593  * nor size unlike mov_read_extradata.
1594  */
1595 static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1596 {
1597     AVStream *st;
1598     int ret;
1599
1600     if (c->fc->nb_streams < 1)
1601         return 0;
1602     st = c->fc->streams[c->fc->nb_streams-1];
1603
1604     if ((uint64_t)atom.size > (1<<30))
1605         return AVERROR_INVALIDDATA;
1606
1607     if (atom.size >= 10) {
1608         // Broken files created by legacy versions of libavformat will
1609         // wrap a whole fiel atom inside of a glbl atom.
1610         unsigned size = avio_rb32(pb);
1611         unsigned type = avio_rl32(pb);
1612         avio_seek(pb, -8, SEEK_CUR);
1613         if (type == MKTAG('f','i','e','l') && size == atom.size)
1614             return mov_read_default(c, pb, atom);
1615     }
1616     if (st->codec->extradata_size > 1 && st->codec->extradata) {
1617         av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
1618         return 0;
1619     }
1620     av_freep(&st->codec->extradata);
1621     ret = ff_get_extradata(st->codec, pb, atom.size);
1622     if (ret < 0)
1623         return ret;
1624
1625     return 0;
1626 }
1627
1628 static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1629 {
1630     AVStream *st;
1631     uint8_t profile_level;
1632     int ret;
1633
1634     if (c->fc->nb_streams < 1)
1635         return 0;
1636     st = c->fc->streams[c->fc->nb_streams-1];
1637
1638     if (atom.size >= (1<<28) || atom.size < 7)
1639         return AVERROR_INVALIDDATA;
1640
1641     profile_level = avio_r8(pb);
1642     if ((profile_level & 0xf0) != 0xc0)
1643         return 0;
1644
1645     avio_seek(pb, 6, SEEK_CUR);
1646     av_freep(&st->codec->extradata);
1647     ret = ff_get_extradata(st->codec, pb, atom.size - 7);
1648     if (ret < 0)
1649         return ret;
1650
1651     return 0;
1652 }
1653
1654 /**
1655  * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
1656  * but can have extradata appended at the end after the 40 bytes belonging
1657  * to the struct.
1658  */
1659 static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1660 {
1661     AVStream *st;
1662     int ret;
1663
1664     if (c->fc->nb_streams < 1)
1665         return 0;
1666     if (atom.size <= 40)
1667         return 0;
1668     st = c->fc->streams[c->fc->nb_streams-1];
1669
1670     if ((uint64_t)atom.size > (1<<30))
1671         return AVERROR_INVALIDDATA;
1672
1673     avio_skip(pb, 40);
1674     av_freep(&st->codec->extradata);
1675     ret = ff_get_extradata(st->codec, pb, atom.size - 40);
1676     if (ret < 0)
1677         return ret;
1678
1679     return 0;
1680 }
1681
1682 static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1683 {
1684     AVStream *st;
1685     MOVStreamContext *sc;
1686     unsigned int i, entries;
1687
1688     if (c->fc->nb_streams < 1)
1689         return 0;
1690     st = c->fc->streams[c->fc->nb_streams-1];
1691     sc = st->priv_data;
1692
1693     avio_r8(pb); /* version */
1694     avio_rb24(pb); /* flags */
1695
1696     entries = avio_rb32(pb);
1697
1698     if (!entries)
1699         return 0;
1700
1701     if (sc->chunk_offsets)
1702         av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
1703     av_free(sc->chunk_offsets);
1704     sc->chunk_count = 0;
1705     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
1706     if (!sc->chunk_offsets)
1707         return AVERROR(ENOMEM);
1708     sc->chunk_count = entries;
1709
1710     if      (atom.type == MKTAG('s','t','c','o'))
1711         for (i = 0; i < entries && !pb->eof_reached; i++)
1712             sc->chunk_offsets[i] = avio_rb32(pb);
1713     else if (atom.type == MKTAG('c','o','6','4'))
1714         for (i = 0; i < entries && !pb->eof_reached; i++)
1715             sc->chunk_offsets[i] = avio_rb64(pb);
1716     else
1717         return AVERROR_INVALIDDATA;
1718
1719     sc->chunk_count = i;
1720
1721     if (pb->eof_reached)
1722         return AVERROR_EOF;
1723
1724     return 0;
1725 }
1726
1727 /**
1728  * Compute codec id for 'lpcm' tag.
1729  * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
1730  */
1731 enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
1732 {
1733     /* lpcm flags:
1734      * 0x1 = float
1735      * 0x2 = big-endian
1736      * 0x4 = signed
1737      */
1738     return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
1739 }
1740
1741 static int mov_codec_id(AVStream *st, uint32_t format)
1742 {
1743     int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
1744
1745     if (id <= 0 &&
1746         ((format & 0xFFFF) == 'm' + ('s' << 8) ||
1747          (format & 0xFFFF) == 'T' + ('S' << 8)))
1748         id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
1749
1750     if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
1751         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
1752     } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
1753                /* skip old asf mpeg4 tag */
1754                format && format != MKTAG('m','p','4','s')) {
1755         id = ff_codec_get_id(ff_codec_movvideo_tags, format);
1756         if (id <= 0)
1757             id = ff_codec_get_id(ff_codec_bmp_tags, format);
1758         if (id > 0)
1759             st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
1760         else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
1761                     (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
1762                     st->codec->codec_id == AV_CODEC_ID_NONE)) {
1763             id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1764             if (id > 0)
1765                 st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
1766         }
1767     }
1768
1769     st->codec->codec_tag = format;
1770
1771     return id;
1772 }
1773
1774 static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
1775                                  AVStream *st, MOVStreamContext *sc)
1776 {
1777     uint8_t codec_name[32];
1778     int64_t stsd_start;
1779     unsigned int len;
1780
1781     /* The first 16 bytes of the video sample description are already
1782      * read in ff_mov_read_stsd_entries() */
1783     stsd_start = avio_tell(pb) - 16;
1784
1785     avio_rb16(pb); /* version */
1786     avio_rb16(pb); /* revision level */
1787     avio_rb32(pb); /* vendor */
1788     avio_rb32(pb); /* temporal quality */
1789     avio_rb32(pb); /* spatial quality */
1790
1791     st->codec->width  = avio_rb16(pb); /* width */
1792     st->codec->height = avio_rb16(pb); /* height */
1793
1794     avio_rb32(pb); /* horiz resolution */
1795     avio_rb32(pb); /* vert resolution */
1796     avio_rb32(pb); /* data size, always 0 */
1797     avio_rb16(pb); /* frames per samples */
1798
1799     len = avio_r8(pb); /* codec name, pascal string */
1800     if (len > 31)
1801         len = 31;
1802     mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
1803     if (len < 31)
1804         avio_skip(pb, 31 - len);
1805
1806     if (codec_name[0])
1807         av_dict_set(&st->metadata, "encoder", codec_name, 0);
1808
1809     /* codec_tag YV12 triggers an UV swap in rawdec.c */
1810     if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
1811         st->codec->codec_tag = MKTAG('I', '4', '2', '0');
1812         st->codec->width &= ~1;
1813         st->codec->height &= ~1;
1814     }
1815     /* Flash Media Server uses tag H263 with Sorenson Spark */
1816     if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
1817         !memcmp(codec_name, "Sorenson H263", 13))
1818         st->codec->codec_id = AV_CODEC_ID_FLV1;
1819
1820     st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
1821
1822     avio_seek(pb, stsd_start, SEEK_SET);
1823
1824     if (ff_get_qtpalette(st->codec->codec_id, pb, sc->palette)) {
1825         st->codec->bits_per_coded_sample &= 0x1F;
1826         sc->has_palette = 1;
1827     }
1828 }
1829
1830 static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
1831                                  AVStream *st, MOVStreamContext *sc)
1832 {
1833     int bits_per_sample, flags;
1834     uint16_t version = avio_rb16(pb);
1835     AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
1836
1837     avio_rb16(pb); /* revision level */
1838     avio_rb32(pb); /* vendor */
1839
1840     st->codec->channels              = avio_rb16(pb); /* channel count */
1841     st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
1842     av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
1843
1844     sc->audio_cid = avio_rb16(pb);
1845     avio_rb16(pb); /* packet size = 0 */
1846
1847     st->codec->sample_rate = ((avio_rb32(pb) >> 16));
1848
1849     // Read QT version 1 fields. In version 0 these do not exist.
1850     av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
1851     if (!c->isom ||
1852         (compatible_brands && strstr(compatible_brands->value, "qt  "))) {
1853
1854         if (version == 1) {
1855             sc->samples_per_frame = avio_rb32(pb);
1856             avio_rb32(pb); /* bytes per packet */
1857             sc->bytes_per_frame = avio_rb32(pb);
1858             avio_rb32(pb); /* bytes per sample */
1859         } else if (version == 2) {
1860             avio_rb32(pb); /* sizeof struct only */
1861             st->codec->sample_rate = av_int2double(avio_rb64(pb));
1862             st->codec->channels    = avio_rb32(pb);
1863             avio_rb32(pb); /* always 0x7F000000 */
1864             st->codec->bits_per_coded_sample = avio_rb32(pb);
1865
1866             flags = avio_rb32(pb); /* lpcm format specific flag */
1867             sc->bytes_per_frame   = avio_rb32(pb);
1868             sc->samples_per_frame = avio_rb32(pb);
1869             if (st->codec->codec_tag == MKTAG('l','p','c','m'))
1870                 st->codec->codec_id =
1871                     ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
1872                                              flags);
1873         }
1874         if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
1875             /* can't correctly handle variable sized packet as audio unit */
1876             switch (st->codec->codec_id) {
1877             case AV_CODEC_ID_MP2:
1878             case AV_CODEC_ID_MP3:
1879                 st->need_parsing = AVSTREAM_PARSE_FULL;
1880                 break;
1881             }
1882         }
1883     }
1884
1885     if (sc->format == 0) {
1886         if (st->codec->bits_per_coded_sample == 8)
1887             st->codec->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
1888         else if (st->codec->bits_per_coded_sample == 16)
1889             st->codec->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
1890     }
1891
1892     switch (st->codec->codec_id) {
1893     case AV_CODEC_ID_PCM_S8:
1894     case AV_CODEC_ID_PCM_U8:
1895         if (st->codec->bits_per_coded_sample == 16)
1896             st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
1897         break;
1898     case AV_CODEC_ID_PCM_S16LE:
1899     case AV_CODEC_ID_PCM_S16BE:
1900         if (st->codec->bits_per_coded_sample == 8)
1901             st->codec->codec_id = AV_CODEC_ID_PCM_S8;
1902         else if (st->codec->bits_per_coded_sample == 24)
1903             st->codec->codec_id =
1904                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1905                 AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
1906         else if (st->codec->bits_per_coded_sample == 32)
1907              st->codec->codec_id =
1908                 st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
1909                 AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
1910         break;
1911     /* set values for old format before stsd version 1 appeared */
1912     case AV_CODEC_ID_MACE3:
1913         sc->samples_per_frame = 6;
1914         sc->bytes_per_frame   = 2 * st->codec->channels;
1915         break;
1916     case AV_CODEC_ID_MACE6:
1917         sc->samples_per_frame = 6;
1918         sc->bytes_per_frame   = 1 * st->codec->channels;
1919         break;
1920     case AV_CODEC_ID_ADPCM_IMA_QT:
1921         sc->samples_per_frame = 64;
1922         sc->bytes_per_frame   = 34 * st->codec->channels;
1923         break;
1924     case AV_CODEC_ID_GSM:
1925         sc->samples_per_frame = 160;
1926         sc->bytes_per_frame   = 33;
1927         break;
1928     default:
1929         break;
1930     }
1931
1932     bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1933     if (bits_per_sample) {
1934         st->codec->bits_per_coded_sample = bits_per_sample;
1935         sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1936     }
1937 }
1938
1939 static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
1940                                     AVStream *st, MOVStreamContext *sc,
1941                                     int64_t size)
1942 {
1943     // ttxt stsd contains display flags, justification, background
1944     // color, fonts, and default styles, so fake an atom to read it
1945     MOVAtom fake_atom = { .size = size };
1946     // mp4s contains a regular esds atom
1947     if (st->codec->codec_tag != AV_RL32("mp4s"))
1948         mov_read_glbl(c, pb, fake_atom);
1949     st->codec->width  = sc->width;
1950     st->codec->height = sc->height;
1951 }
1952
1953 static uint32_t yuv_to_rgba(uint32_t ycbcr)
1954 {
1955     uint8_t r, g, b;
1956     int y, cb, cr;
1957
1958     y  = (ycbcr >> 16) & 0xFF;
1959     cr = (ycbcr >> 8)  & 0xFF;
1960     cb =  ycbcr        & 0xFF;
1961
1962     b = av_clip_uint8((1164 * (y - 16)                     + 2018 * (cb - 128)) / 1000);
1963     g = av_clip_uint8((1164 * (y - 16) -  813 * (cr - 128) -  391 * (cb - 128)) / 1000);
1964     r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128)                    ) / 1000);
1965
1966     return (r << 16) | (g << 8) | b;
1967 }
1968
1969 static int mov_rewrite_dvd_sub_extradata(AVStream *st)
1970 {
1971     char buf[256] = {0};
1972     uint8_t *src = st->codec->extradata;
1973     int i;
1974
1975     if (st->codec->extradata_size != 64)
1976         return 0;
1977
1978     if (st->codec->width > 0 &&  st->codec->height > 0)
1979         snprintf(buf, sizeof(buf), "size: %dx%d\n",
1980                  st->codec->width, st->codec->height);
1981     av_strlcat(buf, "palette: ", sizeof(buf));
1982
1983     for (i = 0; i < 16; i++) {
1984         uint32_t yuv = AV_RB32(src + i * 4);
1985         uint32_t rgba = yuv_to_rgba(yuv);
1986
1987         av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
1988     }
1989
1990     if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
1991         return 0;
1992
1993     av_freep(&st->codec->extradata);
1994     st->codec->extradata_size = 0;
1995     st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
1996     if (!st->codec->extradata)
1997         return AVERROR(ENOMEM);
1998     st->codec->extradata_size = strlen(buf);
1999     memcpy(st->codec->extradata, buf, st->codec->extradata_size);
2000
2001     return 0;
2002 }
2003
2004 static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
2005                                 AVStream *st, MOVStreamContext *sc,
2006                                 int64_t size)
2007 {
2008     int ret;
2009
2010     if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
2011         if ((int)size != size)
2012             return AVERROR(ENOMEM);
2013
2014         ret = ff_get_extradata(st->codec, pb, size);
2015         if (ret < 0)
2016             return ret;
2017         if (size > 16) {
2018             MOVStreamContext *tmcd_ctx = st->priv_data;
2019             int val;
2020             val = AV_RB32(st->codec->extradata + 4);
2021             tmcd_ctx->tmcd_flags = val;
2022             if (val & 1)
2023                 st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
2024             st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
2025             st->codec->time_base.num = 1;
2026             /* adjust for per frame dur in counter mode */
2027             if (tmcd_ctx->tmcd_flags & 0x0008) {
2028                 int timescale = AV_RB32(st->codec->extradata + 8);
2029                 int framedur = AV_RB32(st->codec->extradata + 12);
2030                 st->codec->time_base.den *= timescale;
2031                 st->codec->time_base.num *= framedur;
2032             }
2033             if (size > 30) {
2034                 uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
2035                 uint32_t format = AV_RB32(st->codec->extradata + 22);
2036                 if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
2037                     uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
2038                     if (str_size > 0 && size >= (int)str_size + 26) {
2039                         char *reel_name = av_malloc(str_size + 1);
2040                         if (!reel_name)
2041                             return AVERROR(ENOMEM);
2042                         memcpy(reel_name, st->codec->extradata + 30, str_size);
2043                         reel_name[str_size] = 0; /* Add null terminator */
2044                         /* don't add reel_name if emtpy string */
2045                         if (*reel_name == 0) {
2046                             av_free(reel_name);
2047                         } else {
2048                             av_dict_set(&st->metadata, "reel_name", reel_name,  AV_DICT_DONT_STRDUP_VAL);
2049                         }
2050                     }
2051                 }
2052             }
2053         }
2054     } else {
2055         /* other codec type, just skip (rtp, mp4s ...) */
2056         avio_skip(pb, size);
2057     }
2058     return 0;
2059 }
2060
2061 static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
2062                                    AVStream *st, MOVStreamContext *sc)
2063 {
2064     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2065         !st->codec->sample_rate && sc->time_scale > 1)
2066         st->codec->sample_rate = sc->time_scale;
2067
2068     /* special codec parameters handling */
2069     switch (st->codec->codec_id) {
2070 #if CONFIG_DV_DEMUXER
2071     case AV_CODEC_ID_DVAUDIO:
2072         c->dv_fctx = avformat_alloc_context();
2073         if (!c->dv_fctx) {
2074             av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
2075             return AVERROR(ENOMEM);
2076         }
2077         c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
2078         if (!c->dv_demux) {
2079             av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
2080             return AVERROR(ENOMEM);
2081         }
2082         sc->dv_audio_container = 1;
2083         st->codec->codec_id    = AV_CODEC_ID_PCM_S16LE;
2084         break;
2085 #endif
2086     /* no ifdef since parameters are always those */
2087     case AV_CODEC_ID_QCELP:
2088         st->codec->channels = 1;
2089         // force sample rate for qcelp when not stored in mov
2090         if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
2091             st->codec->sample_rate = 8000;
2092         // FIXME: Why is the following needed for some files?
2093         sc->samples_per_frame = 160;
2094         if (!sc->bytes_per_frame)
2095             sc->bytes_per_frame = 35;
2096         break;
2097     case AV_CODEC_ID_AMR_NB:
2098         st->codec->channels    = 1;
2099         /* force sample rate for amr, stsd in 3gp does not store sample rate */
2100         st->codec->sample_rate = 8000;
2101         break;
2102     case AV_CODEC_ID_AMR_WB:
2103         st->codec->channels    = 1;
2104         st->codec->sample_rate = 16000;
2105         break;
2106     case AV_CODEC_ID_MP2:
2107     case AV_CODEC_ID_MP3:
2108         /* force type after stsd for m1a hdlr */
2109         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
2110         break;
2111     case AV_CODEC_ID_GSM:
2112     case AV_CODEC_ID_ADPCM_MS:
2113     case AV_CODEC_ID_ADPCM_IMA_WAV:
2114     case AV_CODEC_ID_ILBC:
2115     case AV_CODEC_ID_MACE3:
2116     case AV_CODEC_ID_MACE6:
2117     case AV_CODEC_ID_QDM2:
2118         st->codec->block_align = sc->bytes_per_frame;
2119         break;
2120     case AV_CODEC_ID_ALAC:
2121         if (st->codec->extradata_size == 36) {
2122             st->codec->channels    = AV_RB8 (st->codec->extradata + 21);
2123             st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
2124         }
2125         break;
2126     case AV_CODEC_ID_AC3:
2127     case AV_CODEC_ID_EAC3:
2128     case AV_CODEC_ID_MPEG1VIDEO:
2129     case AV_CODEC_ID_VC1:
2130         st->need_parsing = AVSTREAM_PARSE_FULL;
2131         break;
2132     default:
2133         break;
2134     }
2135     return 0;
2136 }
2137
2138 static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
2139                                   int codec_tag, int format,
2140                                   int64_t size)
2141 {
2142     int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
2143
2144     if (codec_tag &&
2145          (codec_tag != format &&
2146           (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
2147                                  : codec_tag != MKTAG('j','p','e','g')))) {
2148         /* Multiple fourcc, we skip JPEG. This is not correct, we should
2149          * export it as a separate AVStream but this needs a few changes
2150          * in the MOV demuxer, patch welcome. */
2151
2152         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
2153         avio_skip(pb, size);
2154         return 1;
2155     }
2156     if ( codec_tag == AV_RL32("avc1") ||
2157          codec_tag == AV_RL32("hvc1") ||
2158          codec_tag == AV_RL32("hev1")
2159     )
2160         av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
2161
2162     return 0;
2163 }
2164
2165 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
2166 {
2167     AVStream *st;
2168     MOVStreamContext *sc;
2169     int pseudo_stream_id;
2170
2171     if (c->fc->nb_streams < 1)
2172         return 0;
2173     st = c->fc->streams[c->fc->nb_streams-1];
2174     sc = st->priv_data;
2175
2176     for (pseudo_stream_id = 0;
2177          pseudo_stream_id < entries && !pb->eof_reached;
2178          pseudo_stream_id++) {
2179         //Parsing Sample description table
2180         enum AVCodecID id;
2181         int ret, dref_id = 1;
2182         MOVAtom a = { AV_RL32("stsd") };
2183         int64_t start_pos = avio_tell(pb);
2184         int64_t size    = avio_rb32(pb); /* size */
2185         uint32_t format = avio_rl32(pb); /* data format */
2186
2187         if (size >= 16) {
2188             avio_rb32(pb); /* reserved */
2189             avio_rb16(pb); /* reserved */
2190             dref_id = avio_rb16(pb);
2191         } else if (size <= 7) {
2192             av_log(c->fc, AV_LOG_ERROR,
2193                    "invalid size %"PRId64" in stsd\n", size);
2194             return AVERROR_INVALIDDATA;
2195         }
2196
2197         if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
2198                                    size - (avio_tell(pb) - start_pos)))
2199             continue;
2200
2201         sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
2202         sc->dref_id= dref_id;
2203         sc->format = format;
2204
2205         id = mov_codec_id(st, format);
2206
2207         av_log(c->fc, AV_LOG_TRACE,
2208                "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
2209                 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
2210                 (format >> 24) & 0xff, format, st->codec->codec_type);
2211
2212         if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
2213             st->codec->codec_id = id;
2214             mov_parse_stsd_video(c, pb, st, sc);
2215         } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
2216             st->codec->codec_id = id;
2217             mov_parse_stsd_audio(c, pb, st, sc);
2218         } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
2219             st->codec->codec_id = id;
2220             mov_parse_stsd_subtitle(c, pb, st, sc,
2221                                     size - (avio_tell(pb) - start_pos));
2222         } else {
2223             ret = mov_parse_stsd_data(c, pb, st, sc,
2224                                       size - (avio_tell(pb) - start_pos));
2225             if (ret < 0)
2226                 return ret;
2227         }
2228         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
2229         a.size = size - (avio_tell(pb) - start_pos);
2230         if (a.size > 8) {
2231             if ((ret = mov_read_default(c, pb, a)) < 0)
2232                 return ret;
2233         } else if (a.size > 0)
2234             avio_skip(pb, a.size);
2235     }
2236
2237     if (pb->eof_reached)
2238         return AVERROR_EOF;
2239
2240     return mov_finalize_stsd_codec(c, pb, st, sc);
2241 }
2242
2243 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2244 {
2245     int entries;
2246
2247     avio_r8(pb); /* version */
2248     avio_rb24(pb); /* flags */
2249     entries = avio_rb32(pb);
2250
2251     return ff_mov_read_stsd_entries(c, pb, entries);
2252 }
2253
2254 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2255 {
2256     AVStream *st;
2257     MOVStreamContext *sc;
2258     unsigned int i, entries;
2259
2260     if (c->fc->nb_streams < 1)
2261         return 0;
2262     st = c->fc->streams[c->fc->nb_streams-1];
2263     sc = st->priv_data;
2264
2265     avio_r8(pb); /* version */
2266     avio_rb24(pb); /* flags */
2267
2268     entries = avio_rb32(pb);
2269
2270     av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
2271
2272     if (!entries)
2273         return 0;
2274     if (sc->stsc_data)
2275         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
2276     av_free(sc->stsc_data);
2277     sc->stsc_count = 0;
2278     sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
2279     if (!sc->stsc_data)
2280         return AVERROR(ENOMEM);
2281
2282     for (i = 0; i < entries && !pb->eof_reached; i++) {
2283         sc->stsc_data[i].first = avio_rb32(pb);
2284         sc->stsc_data[i].count = avio_rb32(pb);
2285         sc->stsc_data[i].id = avio_rb32(pb);
2286     }
2287
2288     sc->stsc_count = i;
2289
2290     if (pb->eof_reached)
2291         return AVERROR_EOF;
2292
2293     return 0;
2294 }
2295
2296 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2297 {
2298     AVStream *st;
2299     MOVStreamContext *sc;
2300     unsigned i, entries;
2301
2302     if (c->fc->nb_streams < 1)
2303         return 0;
2304     st = c->fc->streams[c->fc->nb_streams-1];
2305     sc = st->priv_data;
2306
2307     avio_rb32(pb); // version + flags
2308
2309     entries = avio_rb32(pb);
2310     if (sc->stps_data)
2311         av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
2312     av_free(sc->stps_data);
2313     sc->stps_count = 0;
2314     sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
2315     if (!sc->stps_data)
2316         return AVERROR(ENOMEM);
2317
2318     for (i = 0; i < entries && !pb->eof_reached; i++) {
2319         sc->stps_data[i] = avio_rb32(pb);
2320         //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
2321     }
2322
2323     sc->stps_count = i;
2324
2325     if (pb->eof_reached)
2326         return AVERROR_EOF;
2327
2328     return 0;
2329 }
2330
2331 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2332 {
2333     AVStream *st;
2334     MOVStreamContext *sc;
2335     unsigned int i, entries;
2336
2337     if (c->fc->nb_streams < 1)
2338         return 0;
2339     st = c->fc->streams[c->fc->nb_streams-1];
2340     sc = st->priv_data;
2341
2342     avio_r8(pb); /* version */
2343     avio_rb24(pb); /* flags */
2344
2345     entries = avio_rb32(pb);
2346
2347     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
2348
2349     if (!entries)
2350     {
2351         sc->keyframe_absent = 1;
2352         if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
2353             st->need_parsing = AVSTREAM_PARSE_HEADERS;
2354         return 0;
2355     }
2356     if (sc->keyframes)
2357         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
2358     if (entries >= UINT_MAX / sizeof(int))
2359         return AVERROR_INVALIDDATA;
2360     av_freep(&sc->keyframes);
2361     sc->keyframe_count = 0;
2362     sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
2363     if (!sc->keyframes)
2364         return AVERROR(ENOMEM);
2365
2366     for (i = 0; i < entries && !pb->eof_reached; i++) {
2367         sc->keyframes[i] = avio_rb32(pb);
2368         //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
2369     }
2370
2371     sc->keyframe_count = i;
2372
2373     if (pb->eof_reached)
2374         return AVERROR_EOF;
2375
2376     return 0;
2377 }
2378
2379 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2380 {
2381     AVStream *st;
2382     MOVStreamContext *sc;
2383     unsigned int i, entries, sample_size, field_size, num_bytes;
2384     GetBitContext gb;
2385     unsigned char* buf;
2386     int ret;
2387
2388     if (c->fc->nb_streams < 1)
2389         return 0;
2390     st = c->fc->streams[c->fc->nb_streams-1];
2391     sc = st->priv_data;
2392
2393     avio_r8(pb); /* version */
2394     avio_rb24(pb); /* flags */
2395
2396     if (atom.type == MKTAG('s','t','s','z')) {
2397         sample_size = avio_rb32(pb);
2398         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2399             sc->sample_size = sample_size;
2400         sc->stsz_sample_size = sample_size;
2401         field_size = 32;
2402     } else {
2403         sample_size = 0;
2404         avio_rb24(pb); /* reserved */
2405         field_size = avio_r8(pb);
2406     }
2407     entries = avio_rb32(pb);
2408
2409     av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
2410
2411     sc->sample_count = entries;
2412     if (sample_size)
2413         return 0;
2414
2415     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2416         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
2417         return AVERROR_INVALIDDATA;
2418     }
2419
2420     if (!entries)
2421         return 0;
2422     if (entries >= (UINT_MAX - 4) / field_size)
2423         return AVERROR_INVALIDDATA;
2424     if (sc->sample_sizes)
2425         av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
2426     av_free(sc->sample_sizes);
2427     sc->sample_count = 0;
2428     sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
2429     if (!sc->sample_sizes)
2430         return AVERROR(ENOMEM);
2431
2432     num_bytes = (entries*field_size+4)>>3;
2433
2434     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2435     if (!buf) {
2436         av_freep(&sc->sample_sizes);
2437         return AVERROR(ENOMEM);
2438     }
2439
2440     ret = ffio_read_size(pb, buf, num_bytes);
2441     if (ret < 0) {
2442         av_freep(&sc->sample_sizes);
2443         av_free(buf);
2444         return ret;
2445     }
2446
2447     init_get_bits(&gb, buf, 8*num_bytes);
2448
2449     for (i = 0; i < entries && !pb->eof_reached; i++) {
2450         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2451         sc->data_size += sc->sample_sizes[i];
2452     }
2453
2454     sc->sample_count = i;
2455
2456     av_free(buf);
2457
2458     if (pb->eof_reached)
2459         return AVERROR_EOF;
2460
2461     return 0;
2462 }
2463
2464 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2465 {
2466     AVStream *st;
2467     MOVStreamContext *sc;
2468     unsigned int i, entries;
2469     int64_t duration=0;
2470     int64_t total_sample_count=0;
2471
2472     if (c->fc->nb_streams < 1)
2473         return 0;
2474     st = c->fc->streams[c->fc->nb_streams-1];
2475     sc = st->priv_data;
2476
2477     avio_r8(pb); /* version */
2478     avio_rb24(pb); /* flags */
2479     entries = avio_rb32(pb);
2480
2481     av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
2482             c->fc->nb_streams-1, entries);
2483
2484     if (sc->stts_data)
2485         av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
2486     av_free(sc->stts_data);
2487     sc->stts_count = 0;
2488     sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
2489     if (!sc->stts_data)
2490         return AVERROR(ENOMEM);
2491
2492     for (i = 0; i < entries && !pb->eof_reached; i++) {
2493         int sample_duration;
2494         int sample_count;
2495
2496         sample_count=avio_rb32(pb);
2497         sample_duration = avio_rb32(pb);
2498
2499         if (sample_count < 0) {
2500             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2501             return AVERROR_INVALIDDATA;
2502         }
2503         sc->stts_data[i].count= sample_count;
2504         sc->stts_data[i].duration= sample_duration;
2505
2506         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2507                 sample_count, sample_duration);
2508
2509         if (   i+1 == entries
2510             && i
2511             && sample_count == 1
2512             && total_sample_count > 100
2513             && sample_duration/10 > duration / total_sample_count)
2514             sample_duration = duration / total_sample_count;
2515         duration+=(int64_t)sample_duration*sample_count;
2516         total_sample_count+=sample_count;
2517     }
2518
2519     sc->stts_count = i;
2520
2521     sc->duration_for_fps  += duration;
2522     sc->nb_frames_for_fps += total_sample_count;
2523
2524     if (pb->eof_reached)
2525         return AVERROR_EOF;
2526
2527     st->nb_frames= total_sample_count;
2528     if (duration)
2529         st->duration= duration;
2530     sc->track_end = duration;
2531     return 0;
2532 }
2533
2534 static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
2535 {
2536     if (duration < 0) {
2537         if (duration == INT_MIN) {
2538             av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
2539             duration++;
2540         }
2541         sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2542     }
2543 }
2544
2545 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2546 {
2547     AVStream *st;
2548     MOVStreamContext *sc;
2549     unsigned int i, entries;
2550
2551     if (c->fc->nb_streams < 1)
2552         return 0;
2553     st = c->fc->streams[c->fc->nb_streams-1];
2554     sc = st->priv_data;
2555
2556     avio_r8(pb); /* version */
2557     avio_rb24(pb); /* flags */
2558     entries = avio_rb32(pb);
2559
2560     av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
2561
2562     if (!entries)
2563         return 0;
2564     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2565         return AVERROR_INVALIDDATA;
2566     av_freep(&sc->ctts_data);
2567     sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2568     if (!sc->ctts_data)
2569         return AVERROR(ENOMEM);
2570
2571     for (i = 0; i < entries && !pb->eof_reached; i++) {
2572         int count    =avio_rb32(pb);
2573         int duration =avio_rb32(pb);
2574
2575         sc->ctts_data[i].count   = count;
2576         sc->ctts_data[i].duration= duration;
2577
2578         av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
2579                 count, duration);
2580
2581         if (FFNABS(duration) < -(1<<28) && i+2<entries) {
2582             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
2583             av_freep(&sc->ctts_data);
2584             sc->ctts_count = 0;
2585             return 0;
2586         }
2587
2588         if (i+2<entries)
2589             mov_update_dts_shift(sc, duration);
2590     }
2591
2592     sc->ctts_count = i;
2593
2594     if (pb->eof_reached)
2595         return AVERROR_EOF;
2596
2597     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2598
2599     return 0;
2600 }
2601
2602 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2603 {
2604     AVStream *st;
2605     MOVStreamContext *sc;
2606     unsigned int i, entries;
2607     uint8_t version;
2608     uint32_t grouping_type;
2609
2610     if (c->fc->nb_streams < 1)
2611         return 0;
2612     st = c->fc->streams[c->fc->nb_streams-1];
2613     sc = st->priv_data;
2614
2615     version = avio_r8(pb); /* version */
2616     avio_rb24(pb); /* flags */
2617     grouping_type = avio_rl32(pb);
2618     if (grouping_type != MKTAG( 'r','a','p',' '))
2619         return 0; /* only support 'rap ' grouping */
2620     if (version == 1)
2621         avio_rb32(pb); /* grouping_type_parameter */
2622
2623     entries = avio_rb32(pb);
2624     if (!entries)
2625         return 0;
2626     if (sc->rap_group)
2627         av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
2628     av_free(sc->rap_group);
2629     sc->rap_group_count = 0;
2630     sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
2631     if (!sc->rap_group)
2632         return AVERROR(ENOMEM);
2633
2634     for (i = 0; i < entries && !pb->eof_reached; i++) {
2635         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2636         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2637     }
2638
2639     sc->rap_group_count = i;
2640
2641     return pb->eof_reached ? AVERROR_EOF : 0;
2642 }
2643
2644 static void mov_build_index(MOVContext *mov, AVStream *st)
2645 {
2646     MOVStreamContext *sc = st->priv_data;
2647     int64_t current_offset;
2648     int64_t current_dts = 0;
2649     unsigned int stts_index = 0;
2650     unsigned int stsc_index = 0;
2651     unsigned int stss_index = 0;
2652     unsigned int stps_index = 0;
2653     unsigned int i, j;
2654     uint64_t stream_size = 0;
2655
2656     if (sc->elst_count) {
2657         int i, edit_start_index = 0, unsupported = 0;
2658         int64_t empty_duration = 0; // empty duration of the first edit list entry
2659         int64_t start_time = 0; // start time of the media
2660
2661         for (i = 0; i < sc->elst_count; i++) {
2662             const MOVElst *e = &sc->elst_data[i];
2663             if (i == 0 && e->time == -1) {
2664                 /* if empty, the first entry is the start time of the stream
2665                  * relative to the presentation itself */
2666                 empty_duration = e->duration;
2667                 edit_start_index = 1;
2668             } else if (i == edit_start_index && e->time >= 0) {
2669                 start_time = e->time;
2670             } else
2671                 unsupported = 1;
2672         }
2673         if (unsupported)
2674             av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
2675                    "a/v desync might occur, patch welcome\n");
2676
2677         /* adjust first dts according to edit list */
2678         if ((empty_duration || start_time) && mov->time_scale > 0) {
2679             if (empty_duration)
2680                 empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
2681             sc->time_offset = start_time - empty_duration;
2682             current_dts = -sc->time_offset;
2683             if (sc->ctts_count>0 && sc->stts_count>0 &&
2684                 sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
2685                 /* more than 16 frames delay, dts are likely wrong
2686                    this happens with files created by iMovie */
2687                 sc->wrong_dts = 1;
2688                 st->codec->has_b_frames = 1;
2689             }
2690         }
2691
2692         if (!unsupported && st->codec->codec_id == AV_CODEC_ID_AAC && start_time > 0)
2693             sc->start_pad = start_time;
2694     }
2695
2696     /* only use old uncompressed audio chunk demuxing when stts specifies it */
2697     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
2698           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2699         unsigned int current_sample = 0;
2700         unsigned int stts_sample = 0;
2701         unsigned int sample_size;
2702         unsigned int distance = 0;
2703         unsigned int rap_group_index = 0;
2704         unsigned int rap_group_sample = 0;
2705         int64_t last_dts = 0;
2706         int64_t dts_correction = 0;
2707         int rap_group_present = sc->rap_group_count && sc->rap_group;
2708         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
2709
2710         current_dts -= sc->dts_shift;
2711         last_dts     = current_dts;
2712
2713         if (!sc->sample_count || st->nb_index_entries)
2714             return;
2715         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2716             return;
2717         if (av_reallocp_array(&st->index_entries,
2718                               st->nb_index_entries + sc->sample_count,
2719                               sizeof(*st->index_entries)) < 0) {
2720             st->nb_index_entries = 0;
2721             return;
2722         }
2723         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2724
2725         for (i = 0; i < sc->chunk_count; i++) {
2726             int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
2727             current_offset = sc->chunk_offsets[i];
2728             while (stsc_index + 1 < sc->stsc_count &&
2729                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2730                 stsc_index++;
2731
2732             if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
2733                 sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
2734                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
2735                 sc->stsz_sample_size = sc->sample_size;
2736             }
2737             if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
2738                 av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
2739                 sc->stsz_sample_size = sc->sample_size;
2740             }
2741
2742             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2743                 int keyframe = 0;
2744                 if (current_sample >= sc->sample_count) {
2745                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2746                     return;
2747                 }
2748
2749                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2750                     keyframe = 1;
2751                     if (stss_index + 1 < sc->keyframe_count)
2752                         stss_index++;
2753                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2754                     keyframe = 1;
2755                     if (stps_index + 1 < sc->stps_count)
2756                         stps_index++;
2757                 }
2758                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2759                     if (sc->rap_group[rap_group_index].index > 0)
2760                         keyframe = 1;
2761                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2762                         rap_group_sample = 0;
2763                         rap_group_index++;
2764                     }
2765                 }
2766                 if (sc->keyframe_absent
2767                     && !sc->stps_count
2768                     && !rap_group_present
2769                     && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
2770                      keyframe = 1;
2771                 if (keyframe)
2772                     distance = 0;
2773                 sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
2774                 if (sc->pseudo_stream_id == -1 ||
2775                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2776                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2777                     e->pos = current_offset;
2778                     e->timestamp = current_dts;
2779                     e->size = sample_size;
2780                     e->min_distance = distance;
2781                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2782                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2783                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
2784                             current_offset, current_dts, sample_size, distance, keyframe);
2785                     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
2786                         ff_rfps_add_frame(mov->fc, st, current_dts);
2787                 }
2788
2789                 current_offset += sample_size;
2790                 stream_size += sample_size;
2791
2792                 /* A negative sample duration is invalid based on the spec,
2793                  * but some samples need it to correct the DTS. */
2794                 if (sc->stts_data[stts_index].duration < 0) {
2795                     av_log(mov->fc, AV_LOG_WARNING,
2796                            "Invalid SampleDelta %d in STTS, at %d st:%d\n",
2797                            sc->stts_data[stts_index].duration, stts_index,
2798                            st->index);
2799                     dts_correction += sc->stts_data[stts_index].duration - 1;
2800                     sc->stts_data[stts_index].duration = 1;
2801                 }
2802                 current_dts += sc->stts_data[stts_index].duration;
2803                 if (!dts_correction || current_dts + dts_correction > last_dts) {
2804                     current_dts += dts_correction;
2805                     dts_correction = 0;
2806                 } else {
2807                     /* Avoid creating non-monotonous DTS */
2808                     dts_correction += current_dts - last_dts - 1;
2809                     current_dts = last_dts + 1;
2810                 }
2811                 last_dts = current_dts;
2812                 distance++;
2813                 stts_sample++;
2814                 current_sample++;
2815                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2816                     stts_sample = 0;
2817                     stts_index++;
2818                 }
2819             }
2820         }
2821         if (st->duration > 0)
2822             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
2823     } else {
2824         unsigned chunk_samples, total = 0;
2825
2826         // compute total chunk count
2827         for (i = 0; i < sc->stsc_count; i++) {
2828             unsigned count, chunk_count;
2829
2830             chunk_samples = sc->stsc_data[i].count;
2831             if (i != sc->stsc_count - 1 &&
2832                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2833                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2834                 return;
2835             }
2836
2837             if (sc->samples_per_frame >= 160) { // gsm
2838                 count = chunk_samples / sc->samples_per_frame;
2839             } else if (sc->samples_per_frame > 1) {
2840                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2841                 count = (chunk_samples+samples-1) / samples;
2842             } else {
2843                 count = (chunk_samples+1023) / 1024;
2844             }
2845
2846             if (i < sc->stsc_count - 1)
2847                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2848             else
2849                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2850             total += chunk_count * count;
2851         }
2852
2853         av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
2854         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2855             return;
2856         if (av_reallocp_array(&st->index_entries,
2857                               st->nb_index_entries + total,
2858                               sizeof(*st->index_entries)) < 0) {
2859             st->nb_index_entries = 0;
2860             return;
2861         }
2862         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2863
2864         // populate index
2865         for (i = 0; i < sc->chunk_count; i++) {
2866             current_offset = sc->chunk_offsets[i];
2867             if (stsc_index + 1 < sc->stsc_count &&
2868                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2869                 stsc_index++;
2870             chunk_samples = sc->stsc_data[stsc_index].count;
2871
2872             while (chunk_samples > 0) {
2873                 AVIndexEntry *e;
2874                 unsigned size, samples;
2875
2876                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2877                     avpriv_request_sample(mov->fc,
2878                            "Zero bytes per frame, but %d samples per frame",
2879                            sc->samples_per_frame);
2880                     return;
2881                 }
2882
2883                 if (sc->samples_per_frame >= 160) { // gsm
2884                     samples = sc->samples_per_frame;
2885                     size = sc->bytes_per_frame;
2886                 } else {
2887                     if (sc->samples_per_frame > 1) {
2888                         samples = FFMIN((1024 / sc->samples_per_frame)*
2889                                         sc->samples_per_frame, chunk_samples);
2890                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2891                     } else {
2892                         samples = FFMIN(1024, chunk_samples);
2893                         size = samples * sc->sample_size;
2894                     }
2895                 }
2896
2897                 if (st->nb_index_entries >= total) {
2898                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2899                     return;
2900                 }
2901                 e = &st->index_entries[st->nb_index_entries++];
2902                 e->pos = current_offset;
2903                 e->timestamp = current_dts;
2904                 e->size = size;
2905                 e->min_distance = 0;
2906                 e->flags = AVINDEX_KEYFRAME;
2907                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2908                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2909                         size, samples);
2910
2911                 current_offset += size;
2912                 current_dts += samples;
2913                 chunk_samples -= samples;
2914             }
2915         }
2916     }
2917 }
2918
2919 static int test_same_origin(const char *src, const char *ref) {
2920     char src_proto[64];
2921     char ref_proto[64];
2922     char src_auth[256];
2923     char ref_auth[256];
2924     char src_host[256];
2925     char ref_host[256];
2926     int src_port=-1;
2927     int ref_port=-1;
2928
2929     av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
2930     av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
2931
2932     if (strlen(src) == 0) {
2933         return -1;
2934     } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
2935         strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
2936         strlen(src_host) + 1 >= sizeof(src_host) ||
2937         strlen(ref_host) + 1 >= sizeof(ref_host)) {
2938         return 0;
2939     } else if (strcmp(src_proto, ref_proto) ||
2940                strcmp(src_auth, ref_auth) ||
2941                strcmp(src_host, ref_host) ||
2942                src_port != ref_port) {
2943         return 0;
2944     } else
2945         return 1;
2946 }
2947
2948 static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
2949 {
2950     /* try relative path, we do not try the absolute because it can leak information about our
2951        system to an attacker */
2952     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2953         char filename[1025];
2954         const char *src_path;
2955         int i, l;
2956
2957         /* find a source dir */
2958         src_path = strrchr(src, '/');
2959         if (src_path)
2960             src_path++;
2961         else
2962             src_path = src;
2963
2964         /* find a next level down to target */
2965         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2966             if (ref->path[l] == '/') {
2967                 if (i == ref->nlvl_to - 1)
2968                     break;
2969                 else
2970                     i++;
2971             }
2972
2973         /* compose filename if next level down to target was found */
2974         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
2975             memcpy(filename, src, src_path - src);
2976             filename[src_path - src] = 0;
2977
2978             for (i = 1; i < ref->nlvl_from; i++)
2979                 av_strlcat(filename, "../", sizeof(filename));
2980
2981             av_strlcat(filename, ref->path + l + 1, sizeof(filename));
2982             if (!c->use_absolute_path) {
2983                 int same_origin = test_same_origin(src, filename);
2984
2985                 if (!same_origin) {
2986                     av_log(c->fc, AV_LOG_ERROR,
2987                         "Reference with mismatching origin, %s not tried for security reasons, "
2988                         "set demuxer option use_absolute_path to allow it anyway\n",
2989                         ref->path);
2990                     return AVERROR(ENOENT);
2991                 }
2992
2993                 if(strstr(ref->path + l + 1, "..") ||
2994                    strstr(ref->path + l + 1, ":") ||
2995                    (ref->nlvl_from > 1 && same_origin < 0) ||
2996                    (filename[0] == '/' && src_path == src))
2997                     return AVERROR(ENOENT);
2998             }
2999
3000             if (strlen(filename) + 1 == sizeof(filename))
3001                 return AVERROR(ENOENT);
3002             if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
3003                 return 0;
3004         }
3005     } else if (c->use_absolute_path) {
3006         av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
3007                "this is a possible security issue\n");
3008         if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
3009             return 0;
3010     } else {
3011         av_log(c->fc, AV_LOG_ERROR,
3012                "Absolute path %s not tried for security reasons, "
3013                "set demuxer option use_absolute_path to allow absolute paths\n",
3014                ref->path);
3015     }
3016
3017     return AVERROR(ENOENT);
3018 }
3019
3020 static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
3021 {
3022     if (sc->time_scale <= 0) {
3023         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
3024         sc->time_scale = c->time_scale;
3025         if (sc->time_scale <= 0)
3026             sc->time_scale = 1;
3027     }
3028 }
3029
3030 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3031 {
3032     AVStream *st;
3033     MOVStreamContext *sc;
3034     int ret;
3035
3036     st = avformat_new_stream(c->fc, NULL);
3037     if (!st) return AVERROR(ENOMEM);
3038     st->id = c->fc->nb_streams;
3039     sc = av_mallocz(sizeof(MOVStreamContext));
3040     if (!sc) return AVERROR(ENOMEM);
3041
3042     st->priv_data = sc;
3043     st->codec->codec_type = AVMEDIA_TYPE_DATA;
3044     sc->ffindex = st->index;
3045     c->trak_index = st->index;
3046
3047     if ((ret = mov_read_default(c, pb, atom)) < 0)
3048         return ret;
3049
3050     c->trak_index = -1;
3051
3052     /* sanity checks */
3053     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
3054                             (!sc->sample_size && !sc->sample_count))) {
3055         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
3056                st->index);
3057         return 0;
3058     }
3059
3060     fix_timescale(c, sc);
3061
3062     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
3063
3064     mov_build_index(c, st);
3065
3066     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
3067         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
3068         if (c->enable_drefs) {
3069             if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
3070                 av_log(c->fc, AV_LOG_ERROR,
3071                        "stream %d, error opening alias: path='%s', dir='%s', "
3072                        "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
3073                        st->index, dref->path, dref->dir, dref->filename,
3074                        dref->volume, dref->nlvl_from, dref->nlvl_to);
3075         } else {
3076             av_log(c->fc, AV_LOG_WARNING,
3077                    "Skipped opening external track: "
3078                    "stream %d, alias: path='%s', dir='%s', "
3079                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
3080                    "Set enable_drefs to allow this.\n",
3081                    st->index, dref->path, dref->dir, dref->filename,
3082                    dref->volume, dref->nlvl_from, dref->nlvl_to);
3083         }
3084     } else {
3085         sc->pb = c->fc->pb;
3086         sc->pb_is_copied = 1;
3087     }
3088
3089     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3090         if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
3091             sc->height && sc->width &&
3092             (st->codec->width != sc->width || st->codec->height != sc->height)) {
3093             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
3094                                              ((double)st->codec->width * sc->height), INT_MAX);
3095         }
3096
3097 #if FF_API_R_FRAME_RATE
3098         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
3099             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
3100                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
3101 #endif
3102     }
3103
3104     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
3105     if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
3106         TAG_IS_AVCI(st->codec->codec_tag)) {
3107         ret = ff_generate_avci_extradata(st);
3108         if (ret < 0)
3109             return ret;
3110     }
3111
3112     switch (st->codec->codec_id) {
3113 #if CONFIG_H261_DECODER
3114     case AV_CODEC_ID_H261:
3115 #endif
3116 #if CONFIG_H263_DECODER
3117     case AV_CODEC_ID_H263:
3118 #endif
3119 #if CONFIG_MPEG4_DECODER
3120     case AV_CODEC_ID_MPEG4:
3121 #endif
3122         st->codec->width = 0; /* let decoder init width/height */
3123         st->codec->height= 0;
3124         break;
3125     }
3126
3127     // If the duration of the mp3 packets is not constant, then they could need a parser
3128     if (st->codec->codec_id == AV_CODEC_ID_MP3
3129         && sc->stts_count > 3
3130         && sc->stts_count*10 > st->nb_frames
3131         && sc->time_scale == st->codec->sample_rate) {
3132             st->need_parsing = AVSTREAM_PARSE_FULL;
3133     }
3134     /* Do not need those anymore. */
3135     av_freep(&sc->chunk_offsets);
3136     av_freep(&sc->stsc_data);
3137     av_freep(&sc->sample_sizes);
3138     av_freep(&sc->keyframes);
3139     av_freep(&sc->stts_data);
3140     av_freep(&sc->stps_data);
3141     av_freep(&sc->elst_data);
3142     av_freep(&sc->rap_group);
3143
3144     return 0;
3145 }
3146
3147 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3148 {
3149     int ret;
3150     c->itunes_metadata = 1;
3151     ret = mov_read_default(c, pb, atom);
3152     c->itunes_metadata = 0;
3153     return ret;
3154 }
3155
3156 static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3157 {
3158     uint32_t count;
3159     uint32_t i;
3160
3161     if (atom.size < 8)
3162         return 0;
3163
3164     avio_skip(pb, 4);
3165     count = avio_rb32(pb);
3166     if (count > UINT_MAX / sizeof(*c->meta_keys)) {
3167         av_log(c->fc, AV_LOG_ERROR,
3168                "The 'keys' atom with the invalid key count: %d\n", count);
3169         return AVERROR_INVALIDDATA;
3170     }
3171
3172     c->meta_keys_count = count + 1;
3173     c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
3174     if (!c->meta_keys)
3175         return AVERROR(ENOMEM);
3176
3177     for (i = 1; i <= count; ++i) {
3178         uint32_t key_size = avio_rb32(pb);
3179         uint32_t type = avio_rl32(pb);
3180         if (key_size < 8) {
3181             av_log(c->fc, AV_LOG_ERROR,
3182                    "The key# %d in meta has invalid size: %d\n", i, key_size);
3183             return AVERROR_INVALIDDATA;
3184         }
3185         key_size -= 8;
3186         if (type != MKTAG('m','d','t','a')) {
3187             avio_skip(pb, key_size);
3188         }
3189         c->meta_keys[i] = av_mallocz(key_size + 1);
3190         if (!c->meta_keys[i])
3191             return AVERROR(ENOMEM);
3192         avio_read(pb, c->meta_keys[i], key_size);
3193     }
3194
3195     return 0;
3196 }
3197
3198 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3199 {
3200     int64_t end = avio_tell(pb) + atom.size;
3201     uint8_t *key = NULL, *val = NULL, *mean = NULL;
3202     int i;
3203     int ret = 0;
3204     AVStream *st;
3205     MOVStreamContext *sc;
3206
3207     if (c->fc->nb_streams < 1)
3208         return 0;
3209     st = c->fc->streams[c->fc->nb_streams-1];
3210     sc = st->priv_data;
3211
3212     for (i = 0; i < 3; i++) {
3213         uint8_t **p;
3214         uint32_t len, tag;
3215
3216         if (end - avio_tell(pb) <= 12)
3217             break;
3218
3219         len = avio_rb32(pb);
3220         tag = avio_rl32(pb);
3221         avio_skip(pb, 4); // flags
3222
3223         if (len < 12 || len - 12 > end - avio_tell(pb))
3224             break;
3225         len -= 12;
3226
3227         if (tag == MKTAG('m', 'e', 'a', 'n'))
3228             p = &mean;
3229         else if (tag == MKTAG('n', 'a', 'm', 'e'))
3230             p = &key;
3231         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
3232             avio_skip(pb, 4);
3233             len -= 4;
3234             p = &val;
3235         } else
3236             break;
3237
3238         *p = av_malloc(len + 1);
3239         if (!*p)
3240             break;
3241         ret = ffio_read_size(pb, *p, len);
3242         if (ret < 0) {
3243             av_freep(p);
3244             break;
3245         }
3246         (*p)[len] = 0;
3247     }
3248
3249     if (mean && key && val) {
3250         if (strcmp(key, "iTunSMPB") == 0) {
3251             int priming, remainder, samples;
3252             if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
3253                 if(priming>0 && priming<16384)
3254                     sc->start_pad = priming;
3255             }
3256         }
3257         if (strcmp(key, "cdec") != 0) {
3258             av_dict_set(&c->fc->metadata, key, val,
3259                         AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
3260             key = val = NULL;
3261         }
3262     } else {
3263         av_log(c->fc, AV_LOG_VERBOSE,
3264                "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
3265     }
3266
3267     avio_seek(pb, end, SEEK_SET);
3268     av_freep(&key);
3269     av_freep(&val);
3270     av_freep(&mean);
3271     return ret;
3272 }
3273
3274 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3275 {
3276     while (atom.size > 8) {
3277         uint32_t tag = avio_rl32(pb);
3278         atom.size -= 4;
3279         if (tag == MKTAG('h','d','l','r')) {
3280             avio_seek(pb, -8, SEEK_CUR);
3281             atom.size += 8;
3282             return mov_read_default(c, pb, atom);
3283         }
3284     }
3285     return 0;
3286 }
3287
3288 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3289 {
3290     int i;
3291     int width;
3292     int height;
3293     int display_matrix[3][3];
3294     AVStream *st;
3295     MOVStreamContext *sc;
3296     int version;
3297     int flags;
3298
3299     if (c->fc->nb_streams < 1)
3300         return 0;
3301     st = c->fc->streams[c->fc->nb_streams-1];
3302     sc = st->priv_data;
3303
3304     version = avio_r8(pb);
3305     flags = avio_rb24(pb);
3306     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
3307
3308     if (version == 1) {
3309         avio_rb64(pb);
3310         avio_rb64(pb);
3311     } else {
3312         avio_rb32(pb); /* creation time */
3313         avio_rb32(pb); /* modification time */
3314     }
3315     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
3316     avio_rb32(pb); /* reserved */
3317
3318     /* highlevel (considering edits) duration in movie timebase */
3319     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
3320     avio_rb32(pb); /* reserved */
3321     avio_rb32(pb); /* reserved */
3322
3323     avio_rb16(pb); /* layer */
3324     avio_rb16(pb); /* alternate group */
3325     avio_rb16(pb); /* volume */
3326     avio_rb16(pb); /* reserved */
3327
3328     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
3329     // they're kept in fixed point format through all calculations
3330     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
3331     // side data, but the scale factor is not needed to calculate aspect ratio
3332     for (i = 0; i < 3; i++) {
3333         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
3334         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
3335         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
3336     }
3337
3338     width = avio_rb32(pb);       // 16.16 fixed point track width
3339     height = avio_rb32(pb);      // 16.16 fixed point track height
3340     sc->width = width >> 16;
3341     sc->height = height >> 16;
3342
3343     // save the matrix and add rotate metadata when it is not the default
3344     // identity
3345     if (display_matrix[0][0] != (1 << 16) ||
3346         display_matrix[1][1] != (1 << 16) ||
3347         display_matrix[2][2] != (1 << 30) ||
3348         display_matrix[0][1] || display_matrix[0][2] ||
3349         display_matrix[1][0] || display_matrix[1][2] ||
3350         display_matrix[2][0] || display_matrix[2][1]) {
3351         int i, j;
3352         double rotate;
3353
3354         av_freep(&sc->display_matrix);
3355         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
3356         if (!sc->display_matrix)
3357             return AVERROR(ENOMEM);
3358
3359         for (i = 0; i < 3; i++)
3360             for (j = 0; j < 3; j++)
3361                 sc->display_matrix[i * 3 + j] = display_matrix[i][j];
3362
3363         rotate = av_display_rotation_get(sc->display_matrix);
3364         if (!isnan(rotate)) {
3365             char rotate_buf[64];
3366             rotate = -rotate;
3367             if (rotate < 0) // for backward compatibility
3368                 rotate += 360;
3369             snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
3370             av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
3371         }
3372     }
3373
3374     // transform the display width/height according to the matrix
3375     // to keep the same scale, use [width height 1<<16]
3376     if (width && height && sc->display_matrix) {
3377         double disp_transform[2];
3378
3379         for (i = 0; i < 2; i++)
3380             disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
3381
3382         if (disp_transform[0] > 0       && disp_transform[1] > 0 &&
3383             disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
3384             fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
3385             st->sample_aspect_ratio = av_d2q(
3386                 disp_transform[0] / disp_transform[1],
3387                 INT_MAX);
3388     }
3389     return 0;
3390 }
3391
3392 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3393 {
3394     MOVFragment *frag = &c->fragment;
3395     MOVTrackExt *trex = NULL;
3396     MOVFragmentIndex* index = NULL;
3397     int flags, track_id, i, found = 0;
3398
3399     avio_r8(pb); /* version */
3400     flags = avio_rb24(pb);
3401
3402     track_id = avio_rb32(pb);
3403     if (!track_id)
3404         return AVERROR_INVALIDDATA;
3405     frag->track_id = track_id;
3406     for (i = 0; i < c->trex_count; i++)
3407         if (c->trex_data[i].track_id == frag->track_id) {
3408             trex = &c->trex_data[i];
3409             break;
3410         }
3411     if (!trex) {
3412         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
3413         return AVERROR_INVALIDDATA;
3414     }
3415
3416     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
3417                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
3418                              frag->moof_offset : frag->implicit_offset;
3419     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
3420
3421     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
3422                      avio_rb32(pb) : trex->duration;
3423     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
3424                      avio_rb32(pb) : trex->size;
3425     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
3426                      avio_rb32(pb) : trex->flags;
3427     frag->time     = AV_NOPTS_VALUE;
3428     for (i = 0; i < c->fragment_index_count; i++) {
3429         int j;
3430         MOVFragmentIndex* candidate = c->fragment_index_data[i];
3431         if (candidate->track_id == frag->track_id) {
3432             av_log(c->fc, AV_LOG_DEBUG,
3433                    "found fragment index for track %u\n", frag->track_id);
3434             index = candidate;
3435             for (j = index->current_item; j < index->item_count; j++) {
3436                 if (frag->implicit_offset == index->items[j].moof_offset) {
3437                     av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
3438                             "for track %u and moof_offset %"PRId64"\n",
3439                             frag->track_id, index->items[j].moof_offset);
3440                     frag->time = index->items[j].time;
3441                     index->current_item = j + 1;
3442                     found = 1;
3443                     break;
3444                 }
3445             }
3446             if (found)
3447                 break;
3448         }
3449     }
3450     if (index && !found) {
3451         av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
3452                "it doesn't have an (in-order) entry for moof_offset "
3453                "%"PRId64"\n", frag->track_id, frag->implicit_offset);
3454     }
3455     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
3456     return 0;
3457 }
3458
3459 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3460 {
3461     c->chapter_track = avio_rb32(pb);
3462     return 0;
3463 }
3464
3465 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3466 {
3467     MOVTrackExt *trex;
3468     int err;
3469
3470     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
3471         return AVERROR_INVALIDDATA;
3472     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
3473                                  sizeof(*c->trex_data))) < 0) {
3474         c->trex_count = 0;
3475         return err;
3476     }
3477
3478     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
3479
3480     trex = &c->trex_data[c->trex_count++];
3481     avio_r8(pb); /* version */
3482     avio_rb24(pb); /* flags */
3483     trex->track_id = avio_rb32(pb);
3484     trex->stsd_id  = avio_rb32(pb);
3485     trex->duration = avio_rb32(pb);
3486     trex->size     = avio_rb32(pb);
3487     trex->flags    = avio_rb32(pb);
3488     return 0;
3489 }
3490
3491 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3492 {
3493     MOVFragment *frag = &c->fragment;
3494     AVStream *st = NULL;
3495     MOVStreamContext *sc;
3496     int version, i;
3497
3498     for (i = 0; i < c->fc->nb_streams; i++) {
3499         if (c->fc->streams[i]->id == frag->track_id) {
3500             st = c->fc->streams[i];
3501             break;
3502         }
3503     }
3504     if (!st) {
3505         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3506         return AVERROR_INVALIDDATA;
3507     }
3508     sc = st->priv_data;
3509     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
3510         return 0;
3511     version = avio_r8(pb);
3512     avio_rb24(pb); /* flags */
3513     if (version) {
3514         sc->track_end = avio_rb64(pb);
3515     } else {
3516         sc->track_end = avio_rb32(pb);
3517     }
3518     return 0;
3519 }
3520
3521 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3522 {
3523     MOVFragment *frag = &c->fragment;
3524     AVStream *st = NULL;
3525     MOVStreamContext *sc;
3526     MOVStts *ctts_data;
3527     uint64_t offset;
3528     int64_t dts;
3529     int data_offset = 0;
3530     unsigned entries, first_sample_flags = frag->flags;
3531     int flags, distance, i, err;
3532
3533     for (i = 0; i < c->fc->nb_streams; i++) {
3534         if (c->fc->streams[i]->id == frag->track_id) {
3535             st = c->fc->streams[i];
3536             break;
3537         }
3538     }
3539     if (!st) {
3540         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
3541         return AVERROR_INVALIDDATA;
3542     }
3543     sc = st->priv_data;
3544     if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
3545         return 0;
3546     avio_r8(pb); /* version */
3547     flags = avio_rb24(pb);
3548     entries = avio_rb32(pb);
3549     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
3550
3551     /* Always assume the presence of composition time offsets.
3552      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
3553      *  1) in the initial movie, there are no samples.
3554      *  2) in the first movie fragment, there is only one sample without composition time offset.
3555      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
3556     if (!sc->ctts_count && sc->sample_count)
3557     {
3558         /* Complement ctts table if moov atom doesn't have ctts atom. */
3559         ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3560         if (!ctts_data)
3561             return AVERROR(ENOMEM);
3562         sc->ctts_data = ctts_data;
3563         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3564         sc->ctts_data[sc->ctts_count].duration = 0;
3565         sc->ctts_count++;
3566     }
3567     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3568         return AVERROR_INVALIDDATA;
3569     if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3570                                  sizeof(*sc->ctts_data))) < 0) {
3571         sc->ctts_count = 0;
3572         return err;
3573     }
3574     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
3575     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3576     dts    = sc->track_end - sc->time_offset;
3577     offset = frag->base_data_offset + data_offset;
3578     distance = 0;
3579     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3580     for (i = 0; i < entries && !pb->eof_reached; i++) {
3581         unsigned sample_size = frag->size;
3582         int sample_flags = i ? frag->flags : first_sample_flags;
3583         unsigned sample_duration = frag->duration;
3584         int keyframe = 0;
3585
3586         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3587         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
3588         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
3589         sc->ctts_data[sc->ctts_count].count = 1;
3590         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3591                                                   avio_rb32(pb) : 0;
3592         mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
3593         if (frag->time != AV_NOPTS_VALUE) {
3594             if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
3595                 int64_t pts = frag->time;
3596                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3597                         " sc->dts_shift %d ctts.duration %d"
3598                         " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
3599                         sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
3600                         sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
3601                 dts = pts - sc->dts_shift;
3602                 if (flags & MOV_TRUN_SAMPLE_CTS) {
3603                     dts -= sc->ctts_data[sc->ctts_count].duration;
3604                 } else {
3605                     dts -= sc->time_offset;
3606                 }
3607                 av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
3608             } else {
3609                 dts = frag->time - sc->time_offset;
3610                 av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
3611                         ", using it for dts\n", dts);
3612             }
3613             frag->time = AV_NOPTS_VALUE;
3614         }
3615         sc->ctts_count++;
3616         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
3617             keyframe = 1;
3618         else
3619             keyframe =
3620                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3621                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3622         if (keyframe)
3623             distance = 0;
3624         err = av_add_index_entry(st, offset, dts, sample_size, distance,
3625                                  keyframe ? AVINDEX_KEYFRAME : 0);
3626         if (err < 0) {
3627             av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
3628         }
3629         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
3630                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3631                 offset, dts, sample_size, distance, keyframe);
3632         distance++;
3633         dts += sample_duration;
3634         offset += sample_size;
3635         sc->data_size += sample_size;
3636         sc->duration_for_fps += sample_duration;
3637         sc->nb_frames_for_fps ++;
3638     }
3639
3640     if (pb->eof_reached)
3641         return AVERROR_EOF;
3642
3643     frag->implicit_offset = offset;
3644
3645     sc->track_end = dts + sc->time_offset;
3646     if (st->duration < sc->track_end)
3647         st->duration = sc->track_end;
3648
3649     return 0;
3650 }
3651
3652 static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3653 {
3654     int64_t offset = avio_tell(pb) + atom.size, pts;
3655     uint8_t version;
3656     unsigned i, track_id;
3657     AVStream *st = NULL;
3658     MOVStreamContext *sc;
3659     MOVFragmentIndex *index = NULL;
3660     MOVFragmentIndex **tmp;
3661     AVRational timescale;
3662
3663     version = avio_r8(pb);
3664     if (version > 1) {
3665         avpriv_request_sample(c->fc, "sidx version %u", version);
3666         return 0;
3667     }
3668
3669     avio_rb24(pb); // flags
3670
3671     track_id = avio_rb32(pb); // Reference ID
3672     for (i = 0; i < c->fc->nb_streams; i++) {
3673         if (c->fc->streams[i]->id == track_id) {
3674             st = c->fc->streams[i];
3675             break;
3676         }
3677     }
3678     if (!st) {
3679         av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
3680         return 0;
3681     }
3682
3683     sc = st->priv_data;
3684
3685     timescale = av_make_q(1, avio_rb32(pb));
3686
3687     if (version == 0) {
3688         pts = avio_rb32(pb);
3689         offset += avio_rb32(pb);
3690     } else {
3691         pts = avio_rb64(pb);
3692         offset += avio_rb64(pb);
3693     }
3694
3695     avio_rb16(pb); // reserved
3696
3697     index = av_mallocz(sizeof(MOVFragmentIndex));
3698     if (!index)
3699         return AVERROR(ENOMEM);
3700
3701     index->track_id = track_id;
3702
3703     index->item_count = avio_rb16(pb);
3704     index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
3705
3706     if (!index->items) {
3707         av_freep(&index);
3708         return AVERROR(ENOMEM);
3709     }
3710
3711     for (i = 0; i < index->item_count; i++) {
3712         uint32_t size = avio_rb32(pb);
3713         uint32_t duration = avio_rb32(pb);
3714         if (size & 0x80000000) {
3715             avpriv_request_sample(c->fc, "sidx reference_type 1");
3716             av_freep(&index->items);
3717             av_freep(&index);
3718             return AVERROR_PATCHWELCOME;
3719         }
3720         avio_rb32(pb); // sap_flags
3721         index->items[i].moof_offset = offset;
3722         index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
3723         offset += size;
3724         pts += duration;
3725     }
3726
3727     st->duration = sc->track_end = pts;
3728
3729     tmp = av_realloc_array(c->fragment_index_data,
3730                            c->fragment_index_count + 1,
3731                            sizeof(MOVFragmentIndex*));
3732     if (!tmp) {
3733         av_freep(&index->items);
3734         av_freep(&index);
3735         return AVERROR(ENOMEM);
3736     }
3737
3738     c->fragment_index_data = tmp;
3739     c->fragment_index_data[c->fragment_index_count++] = index;
3740
3741     if (offset == avio_size(pb))
3742         c->fragment_index_complete = 1;
3743
3744     return 0;
3745 }
3746
3747 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3748 /* like the files created with Adobe Premiere 5.0, for samples see */
3749 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3750 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3751 {
3752     int err;
3753
3754     if (atom.size < 8)
3755         return 0; /* continue */
3756     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3757         avio_skip(pb, atom.size - 4);
3758         return 0;
3759     }
3760     atom.type = avio_rl32(pb);
3761     atom.size -= 8;
3762     if (atom.type != MKTAG('m','d','a','t')) {
3763         avio_skip(pb, atom.size);
3764         return 0;
3765     }
3766     err = mov_read_mdat(c, pb, atom);
3767     return err;
3768 }
3769
3770 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3771 {
3772 #if CONFIG_ZLIB
3773     AVIOContext ctx;
3774     uint8_t *cmov_data;
3775     uint8_t *moov_data; /* uncompressed data */
3776     long cmov_len, moov_len;
3777     int ret = -1;
3778
3779     avio_rb32(pb); /* dcom atom */
3780     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3781         return AVERROR_INVALIDDATA;
3782     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3783         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
3784         return AVERROR_INVALIDDATA;
3785     }
3786     avio_rb32(pb); /* cmvd atom */
3787     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3788         return AVERROR_INVALIDDATA;
3789     moov_len = avio_rb32(pb); /* uncompressed size */
3790     cmov_len = atom.size - 6 * 4;
3791
3792     cmov_data = av_malloc(cmov_len);
3793     if (!cmov_data)
3794         return AVERROR(ENOMEM);
3795     moov_data = av_malloc(moov_len);
3796     if (!moov_data) {
3797         av_free(cmov_data);
3798         return AVERROR(ENOMEM);
3799     }
3800     ret = ffio_read_size(pb, cmov_data, cmov_len);
3801     if (ret < 0)
3802         goto free_and_return;
3803
3804     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3805         goto free_and_return;
3806     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3807         goto free_and_return;
3808     ctx.seekable = AVIO_SEEKABLE_NORMAL;
3809     atom.type = MKTAG('m','o','o','v');
3810     atom.size = moov_len;
3811     ret = mov_read_default(c, &ctx, atom);
3812 free_and_return:
3813     av_free(moov_data);
3814     av_free(cmov_data);
3815     return ret;
3816 #else
3817     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3818     return AVERROR(ENOSYS);
3819 #endif
3820 }
3821
3822 /* edit list atom */
3823 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3824 {
3825     MOVStreamContext *sc;
3826     int i, edit_count, version;
3827
3828     if (c->fc->nb_streams < 1 || c->ignore_editlist)
3829         return 0;
3830     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3831
3832     version = avio_r8(pb); /* version */
3833     avio_rb24(pb); /* flags */
3834     edit_count = avio_rb32(pb); /* entries */
3835
3836     if (!edit_count)
3837         return 0;
3838     if (sc->elst_data)
3839         av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
3840     av_free(sc->elst_data);
3841     sc->elst_count = 0;
3842     sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
3843     if (!sc->elst_data)
3844         return AVERROR(ENOMEM);
3845
3846     av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
3847     for (i = 0; i < edit_count && !pb->eof_reached; i++) {
3848         MOVElst *e = &sc->elst_data[i];
3849
3850         if (version == 1) {
3851             e->duration = avio_rb64(pb);
3852             e->time     = avio_rb64(pb);
3853         } else {
3854             e->duration = avio_rb32(pb); /* segment duration */
3855             e->time     = (int32_t)avio_rb32(pb); /* media time */
3856         }
3857         e->rate = avio_rb32(pb) / 65536.0;
3858         av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
3859                 e->duration, e->time, e->rate);
3860     }
3861     sc->elst_count = i;
3862
3863     return 0;
3864 }
3865
3866 static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3867 {
3868     MOVStreamContext *sc;
3869
3870     if (c->fc->nb_streams < 1)
3871         return AVERROR_INVALIDDATA;
3872     sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
3873     sc->timecode_track = avio_rb32(pb);
3874     return 0;
3875 }
3876
3877 static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3878 {
3879     int ret;
3880     uint8_t uuid[16];
3881     static const uint8_t uuid_isml_manifest[] = {
3882         0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
3883         0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
3884     };
3885     static const uint8_t uuid_xmp[] = {
3886         0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
3887         0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
3888     };
3889
3890     if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
3891         return AVERROR_INVALIDDATA;
3892
3893     ret = avio_read(pb, uuid, sizeof(uuid));
3894     if (ret < 0) {
3895         return ret;
3896     } else if (ret != sizeof(uuid)) {
3897         return AVERROR_INVALIDDATA;
3898     }
3899     if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
3900         uint8_t *buffer, *ptr;
3901         char *endptr;
3902         size_t len = atom.size - sizeof(uuid);
3903
3904         if (len < 4) {
3905             return AVERROR_INVALIDDATA;
3906         }
3907         ret = avio_skip(pb, 4); // zeroes
3908         len -= 4;
3909
3910         buffer = av_mallocz(len + 1);
3911         if (!buffer) {
3912             return AVERROR(ENOMEM);
3913         }
3914         ret = avio_read(pb, buffer, len);
3915         if (ret < 0) {
3916             av_free(buffer);
3917             return ret;
3918         } else if (ret != len) {
3919             av_free(buffer);
3920             return AVERROR_INVALIDDATA;
3921         }
3922
3923         ptr = buffer;
3924         while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
3925             ptr += sizeof("systemBitrate=\"") - 1;
3926             c->bitrates_count++;
3927             c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
3928             if (!c->bitrates) {
3929                 c->bitrates_count = 0;
3930                 av_free(buffer);
3931                 return AVERROR(ENOMEM);
3932             }
3933             errno = 0;
3934             ret = strtol(ptr, &endptr, 10);
3935             if (ret < 0 || errno || *endptr != '"') {
3936                 c->bitrates[c->bitrates_count - 1] = 0;
3937             } else {
3938                 c->bitrates[c->bitrates_count - 1] = ret;
3939             }
3940         }
3941
3942         av_free(buffer);
3943     } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
3944         uint8_t *buffer;
3945         size_t len = atom.size - sizeof(uuid);
3946
3947         buffer = av_mallocz(len + 1);
3948         if (!buffer) {
3949             return AVERROR(ENOMEM);
3950         }
3951         ret = avio_read(pb, buffer, len);
3952         if (ret < 0) {
3953             av_free(buffer);
3954             return ret;
3955         } else if (ret != len) {
3956             av_free(buffer);
3957             return AVERROR_INVALIDDATA;
3958         }
3959         if (c->export_xmp) {
3960             buffer[len] = '\0';
3961             av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
3962         }
3963         av_free(buffer);
3964     }
3965     return 0;
3966 }
3967
3968 static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3969 {
3970     int ret;
3971     uint8_t content[16];
3972
3973     if (atom.size < 8)
3974         return 0;
3975
3976     ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
3977     if (ret < 0)
3978         return ret;
3979
3980     if (   !c->found_moov
3981         && !c->found_mdat
3982         && !memcmp(content, "Anevia\x1A\x1A", 8)
3983         && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
3984         c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
3985     }
3986
3987     return 0;
3988 }
3989
3990 static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3991 {
3992     uint32_t format = avio_rl32(pb);
3993     MOVStreamContext *sc;
3994     enum AVCodecID id;
3995     AVStream *st;
3996
3997     if (c->fc->nb_streams < 1)
3998         return 0;
3999     st = c->fc->streams[c->fc->nb_streams - 1];
4000     sc = st->priv_data;
4001
4002     switch (sc->format)
4003     {
4004     case MKTAG('e','n','c','v'):        // encrypted video
4005     case MKTAG('e','n','c','a'):        // encrypted audio
4006         id = mov_codec_id(st, format);
4007         if (st->codec->codec_id != AV_CODEC_ID_NONE &&
4008             st->codec->codec_id != id) {
4009             av_log(c->fc, AV_LOG_WARNING,
4010                    "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
4011                    (char*)&format, st->codec->codec_id);
4012             break;
4013         }
4014
4015         st->codec->codec_id = id;
4016         sc->format = format;
4017         break;
4018
4019     default:
4020         if (format != sc->format) {
4021             av_log(c->fc, AV_LOG_WARNING,
4022                    "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
4023                    (char*)&format, (char*)&sc->format);
4024         }
4025         break;
4026     }
4027
4028     return 0;
4029 }
4030
4031 static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4032 {
4033     AVStream *st;
4034     MOVStreamContext *sc;
4035     size_t auxiliary_info_size;
4036
4037     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4038         return 0;
4039
4040     st = c->fc->streams[c->fc->nb_streams - 1];
4041     sc = st->priv_data;
4042
4043     if (sc->cenc.aes_ctr) {
4044         av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
4045         return AVERROR_INVALIDDATA;
4046     }
4047
4048     avio_r8(pb); /* version */
4049     sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
4050
4051     avio_rb32(pb);        /* entries */
4052
4053     if (atom.size < 8) {
4054         av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
4055         return AVERROR_INVALIDDATA;
4056     }
4057
4058     /* save the auxiliary info as is */
4059     auxiliary_info_size = atom.size - 8;
4060
4061     sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
4062     if (!sc->cenc.auxiliary_info) {
4063         return AVERROR(ENOMEM);
4064     }
4065
4066     sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
4067
4068     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
4069
4070     if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
4071         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
4072         return AVERROR_INVALIDDATA;
4073     }
4074
4075     /* initialize the cipher */
4076     sc->cenc.aes_ctr = av_aes_ctr_alloc();
4077     if (!sc->cenc.aes_ctr) {
4078         return AVERROR(ENOMEM);
4079     }
4080
4081     return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
4082 }
4083
4084 static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4085 {
4086     AVStream *st;
4087     MOVStreamContext *sc;
4088     size_t data_size;
4089     int atom_header_size;
4090     int flags;
4091
4092     if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
4093         return 0;
4094
4095     st = c->fc->streams[c->fc->nb_streams - 1];
4096     sc = st->priv_data;
4097
4098     if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
4099         av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
4100         return AVERROR_INVALIDDATA;
4101     }
4102
4103     atom_header_size = 9;
4104
4105     avio_r8(pb); /* version */
4106     flags = avio_rb24(pb);
4107
4108     if ((flags & 0x01) != 0) {
4109         atom_header_size += 8;
4110
4111         avio_rb32(pb);    /* info type */
4112         avio_rb32(pb);    /* info type param */
4113     }
4114
4115     sc->cenc.auxiliary_info_default_size = avio_r8(pb);
4116     avio_rb32(pb);    /* entries */
4117
4118     if (atom.size <= atom_header_size) {
4119         return 0;
4120     }
4121
4122     /* save the auxiliary info sizes as is */
4123     data_size = atom.size - atom_header_size;
4124
4125     sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
4126     if (!sc->cenc.auxiliary_info_sizes) {
4127         return AVERROR(ENOMEM);
4128     }
4129
4130     sc->cenc.auxiliary_info_sizes_count = data_size;
4131
4132     if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
4133         av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
4134         return AVERROR_INVALIDDATA;
4135     }
4136
4137     return 0;
4138 }
4139
4140 static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
4141 {
4142     uint32_t encrypted_bytes;
4143     uint16_t subsample_count;
4144     uint16_t clear_bytes;
4145     uint8_t* input_end = input + size;
4146
4147     /* read the iv */
4148     if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4149         av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
4150         return AVERROR_INVALIDDATA;
4151     }
4152
4153     av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
4154     sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
4155
4156     if (!sc->cenc.use_subsamples)
4157     {
4158         /* decrypt the whole packet */
4159         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
4160         return 0;
4161     }
4162
4163     /* read the subsample count */
4164     if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4165         av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
4166         return AVERROR_INVALIDDATA;
4167     }
4168
4169     subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
4170     sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4171
4172     for (; subsample_count > 0; subsample_count--)
4173     {
4174         if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
4175             av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
4176             return AVERROR_INVALIDDATA;
4177         }
4178
4179         /* read the number of clear / encrypted bytes */
4180         clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
4181         sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
4182         encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
4183         sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
4184
4185         if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
4186             av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
4187             return AVERROR_INVALIDDATA;
4188         }
4189
4190         /* skip the clear bytes */
4191         input += clear_bytes;
4192
4193         /* decrypt the encrypted bytes */
4194         av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
4195         input += encrypted_bytes;
4196     }
4197
4198     if (input < input_end) {
4199         av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
4200         return AVERROR_INVALIDDATA;
4201     }
4202
4203     return 0;
4204 }
4205
4206 static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
4207 {
4208     size_t auxiliary_info_seek_offset = 0;
4209     int i;
4210
4211     if (sc->cenc.auxiliary_info_default_size) {
4212         auxiliary_info_seek_offset = sc->cenc.auxiliary_info_default_size * sc->current_sample;
4213     } else if (sc->cenc.auxiliary_info_sizes) {
4214         if (sc->current_sample > sc->cenc.auxiliary_info_sizes_count) {
4215             av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
4216                 sc->current_sample, sc->cenc.auxiliary_info_sizes_count);
4217             return AVERROR_INVALIDDATA;
4218         }
4219
4220         for (i = 0; i < sc->current_sample; i++) {
4221             auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
4222         }
4223     }
4224
4225     if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
4226         av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
4227             auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
4228         return AVERROR_INVALIDDATA;
4229     }
4230
4231     sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
4232
4233     return 0;
4234 }
4235
4236 static const MOVParseTableEntry mov_default_parse_table[] = {
4237 { MKTAG('A','C','L','R'), mov_read_aclr },
4238 { MKTAG('A','P','R','G'), mov_read_avid },
4239 { MKTAG('A','A','L','P'), mov_read_avid },
4240 { MKTAG('A','R','E','S'), mov_read_ares },
4241 { MKTAG('a','v','s','s'), mov_read_avss },
4242 { MKTAG('c','h','p','l'), mov_read_chpl },
4243 { MKTAG('c','o','6','4'), mov_read_stco },
4244 { MKTAG('c','o','l','r'), mov_read_colr },
4245 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
4246 { MKTAG('d','i','n','f'), mov_read_default },
4247 { MKTAG('D','p','x','E'), mov_read_dpxe },
4248 { MKTAG('d','r','e','f'), mov_read_dref },
4249 { MKTAG('e','d','t','s'), mov_read_default },
4250 { MKTAG('e','l','s','t'), mov_read_elst },
4251 { MKTAG('e','n','d','a'), mov_read_enda },
4252 { MKTAG('f','i','e','l'), mov_read_fiel },
4253 { MKTAG('a','d','r','m'), mov_read_adrm },
4254 { MKTAG('f','t','y','p'), mov_read_ftyp },
4255 { MKTAG('g','l','b','l'), mov_read_glbl },
4256 { MKTAG('h','d','l','r'), mov_read_hdlr },
4257 { MKTAG('i','l','s','t'), mov_read_ilst },
4258 { MKTAG('j','p','2','h'), mov_read_jp2h },
4259 { MKTAG('m','d','a','t'), mov_read_mdat },
4260 { MKTAG('m','d','h','d'), mov_read_mdhd },
4261 { MKTAG('m','d','i','a'), mov_read_default },
4262 { MKTAG('m','e','t','a'), mov_read_meta },
4263 { MKTAG('m','i','n','f'), mov_read_default },
4264 { MKTAG('m','o','o','f'), mov_read_moof },
4265 { MKTAG('m','o','o','v'), mov_read_moov },
4266 { MKTAG('m','v','e','x'), mov_read_default },
4267 { MKTAG('m','v','h','d'), mov_read_mvhd },
4268 { MKTAG('S','M','I',' '), mov_read_svq3 },
4269 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
4270 { MKTAG('a','v','c','C'), mov_read_glbl },
4271 { MKTAG('p','a','s','p'), mov_read_pasp },
4272 { MKTAG('s','i','d','x'), mov_read_sidx },
4273 { MKTAG('s','t','b','l'), mov_read_default },
4274 { MKTAG('s','t','c','o'), mov_read_stco },
4275 { MKTAG('s','t','p','s'), mov_read_stps },
4276 { MKTAG('s','t','r','f'), mov_read_strf },
4277 { MKTAG('s','t','s','c'), mov_read_stsc },
4278 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
4279 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
4280 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
4281 { MKTAG('s','t','t','s'), mov_read_stts },
4282 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
4283 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
4284 { MKTAG('t','f','d','t'), mov_read_tfdt },
4285 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
4286 { MKTAG('t','r','a','k'), mov_read_trak },
4287 { MKTAG('t','r','a','f'), mov_read_default },
4288 { MKTAG('t','r','e','f'), mov_read_default },
4289 { MKTAG('t','m','c','d'), mov_read_tmcd },
4290 { MKTAG('c','h','a','p'), mov_read_chap },
4291 { MKTAG('t','r','e','x'), mov_read_trex },
4292 { MKTAG('t','r','u','n'), mov_read_trun },
4293 { MKTAG('u','d','t','a'), mov_read_default },
4294 { MKTAG('w','a','v','e'), mov_read_wave },
4295 { MKTAG('e','s','d','s'), mov_read_esds },
4296 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
4297 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
4298 { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
4299 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
4300 { MKTAG('w','f','e','x'), mov_read_wfex },
4301 { MKTAG('c','m','o','v'), mov_read_cmov },
4302 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
4303 { MKTAG('d','v','c','1'), mov_read_dvc1 },
4304 { MKTAG('s','b','g','p'), mov_read_sbgp },
4305 { MKTAG('h','v','c','C'), mov_read_glbl },
4306 { MKTAG('u','u','i','d'), mov_read_uuid },
4307 { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
4308 { MKTAG('f','r','e','e'), mov_read_free },
4309 { MKTAG('-','-','-','-'), mov_read_custom },
4310 { MKTAG('s','i','n','f'), mov_read_default },
4311 { MKTAG('f','r','m','a'), mov_read_frma },
4312 { MKTAG('s','e','n','c'), mov_read_senc },
4313 { MKTAG('s','a','i','z'), mov_read_saiz },
4314 { 0, NULL }
4315 };
4316
4317 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
4318 {
4319     int64_t total_size = 0;
4320     MOVAtom a;
4321     int i;
4322
4323     if (c->atom_depth > 10) {
4324         av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
4325         return AVERROR_INVALIDDATA;
4326     }
4327     c->atom_depth ++;
4328
4329     if (atom.size < 0)
4330         atom.size = INT64_MAX;
4331     while (total_size + 8 <= atom.size && !avio_feof(pb)) {
4332         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
4333         a.size = atom.size;
4334         a.type=0;
4335         if (atom.size >= 8) {
4336             a.size = avio_rb32(pb);
4337             a.type = avio_rl32(pb);
4338             if (a.type == MKTAG('f','r','e','e') &&
4339                 a.size >= 8 &&
4340                 c->moov_retry) {
4341                 uint8_t buf[8];
4342                 uint32_t *type = (uint32_t *)buf + 1;
4343                 if (avio_read(pb, buf, 8) != 8)
4344                     return AVERROR_INVALIDDATA;
4345                 avio_seek(pb, -8, SEEK_CUR);
4346                 if (*type == MKTAG('m','v','h','d') ||
4347                     *type == MKTAG('c','m','o','v')) {
4348                     av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
4349                     a.type = MKTAG('m','o','o','v');
4350                 }
4351             }
4352             if (atom.type != MKTAG('r','o','o','t') &&
4353                 atom.type != MKTAG('m','o','o','v'))
4354             {
4355                 if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
4356                 {
4357                     av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
4358                     avio_skip(pb, -8);
4359                     c->atom_depth --;
4360                     return 0;
4361                 }
4362             }
4363             total_size += 8;
4364             if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
4365                 a.size = avio_rb64(pb) - 8;
4366                 total_size += 8;
4367             }
4368         }
4369         av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
4370                 a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
4371         if (a.size == 0) {
4372             a.size = atom.size - total_size + 8;
4373         }
4374         a.size -= 8;
4375         if (a.size < 0)
4376             break;
4377         a.size = FFMIN(a.size, atom.size - total_size);
4378
4379         for (i = 0; mov_default_parse_table[i].type; i++)
4380             if (mov_default_parse_table[i].type == a.type) {
4381                 parse = mov_default_parse_table[i].parse;
4382                 break;
4383             }
4384
4385         // container is user data
4386         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
4387                        atom.type == MKTAG('i','l','s','t')))
4388             parse = mov_read_udta_string;
4389
4390         // Supports parsing the QuickTime Metadata Keys.
4391         // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
4392         if (!parse && c->found_hdlr_mdta &&
4393             atom.type == MKTAG('m','e','t','a') &&
4394             a.type == MKTAG('k','e','y','s')) {
4395             parse = mov_read_keys;
4396         }
4397
4398         if (!parse) { /* skip leaf atoms data */
4399             avio_skip(pb, a.size);
4400         } else {
4401             int64_t start_pos = avio_tell(pb);
4402             int64_t left;
4403             int err = parse(c, pb, a);
4404             if (err < 0) {
4405                 c->atom_depth --;
4406                 return err;
4407             }
4408             if (c->found_moov && c->found_mdat &&
4409                 ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
4410                  start_pos + a.size == avio_size(pb))) {
4411                 if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
4412                     c->next_root_atom = start_pos + a.size;
4413                 c->atom_depth --;
4414                 return 0;
4415             }
4416             left = a.size - avio_tell(pb) + start_pos;
4417             if (left > 0) /* skip garbage at atom end */
4418                 avio_skip(pb, left);
4419             else if (left < 0) {
4420                 av_log(c->fc, AV_LOG_WARNING,
4421                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
4422                        (char*)&a.type, -left);
4423                 avio_seek(pb, left, SEEK_CUR);
4424             }
4425         }
4426
4427         total_size += a.size;
4428     }
4429
4430     if (total_size < atom.size && atom.size < 0x7ffff)
4431         avio_skip(pb, atom.size - total_size);
4432
4433     c->atom_depth --;
4434     return 0;
4435 }
4436
4437 static int mov_probe(AVProbeData *p)
4438 {
4439     int64_t offset;
4440     uint32_t tag;
4441     int score = 0;
4442     int moov_offset = -1;
4443
4444     /* check file header */
4445     offset = 0;
4446     for (;;) {
4447         /* ignore invalid offset */
4448         if ((offset + 8) > (unsigned int)p->buf_size)
4449             break;
4450         tag = AV_RL32(p->buf + offset + 4);
4451         switch(tag) {
4452         /* check for obvious tags */
4453         case MKTAG('m','o','o','v'):
4454             moov_offset = offset + 4;
4455         case MKTAG('m','d','a','t'):
4456         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
4457         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
4458         case MKTAG('f','t','y','p'):
4459             if (AV_RB32(p->buf+offset) < 8 &&
4460                 (AV_RB32(p->buf+offset) != 1 ||
4461                  offset + 12 > (unsigned int)p->buf_size ||
4462                  AV_RB64(p->buf+offset + 8) == 0)) {
4463                 score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4464             } else if (tag == MKTAG('f','t','y','p') &&
4465                        (   AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
4466                         || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
4467                     )) {
4468                 score = FFMAX(score, 5);
4469             } else {
4470                 score = AVPROBE_SCORE_MAX;
4471             }
4472             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4473             break;
4474         /* those are more common words, so rate then a bit less */
4475         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
4476         case MKTAG('w','i','d','e'):
4477         case MKTAG('f','r','e','e'):
4478         case MKTAG('j','u','n','k'):
4479         case MKTAG('p','i','c','t'):
4480             score  = FFMAX(score, AVPROBE_SCORE_MAX - 5);
4481             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4482             break;
4483         case MKTAG(0x82,0x82,0x7f,0x7d):
4484         case MKTAG('s','k','i','p'):
4485         case MKTAG('u','u','i','d'):
4486         case MKTAG('p','r','f','l'):
4487             /* if we only find those cause probedata is too small at least rate them */
4488             score  = FFMAX(score, AVPROBE_SCORE_EXTENSION);
4489             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4490             break;
4491         default:
4492             offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
4493         }
4494     }
4495     if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
4496         /* moov atom in the header - we should make sure that this is not a
4497          * MOV-packed MPEG-PS */
4498         offset = moov_offset;
4499
4500         while(offset < (p->buf_size - 16)){ /* Sufficient space */
4501                /* We found an actual hdlr atom */
4502             if(AV_RL32(p->buf + offset     ) == MKTAG('h','d','l','r') &&
4503                AV_RL32(p->buf + offset +  8) == MKTAG('m','h','l','r') &&
4504                AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
4505                 av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
4506                 /* We found a media handler reference atom describing an
4507                  * MPEG-PS-in-MOV, return a
4508                  * low score to force expanding the probe window until
4509                  * mpegps_probe finds what it needs */
4510                 return 5;
4511             }else
4512                 /* Keep looking */
4513                 offset+=2;
4514         }
4515     }
4516
4517     return score;
4518 }
4519
4520 // must be done after parsing all trak because there's no order requirement
4521 static void mov_read_chapters(AVFormatContext *s)
4522 {
4523     MOVContext *mov = s->priv_data;
4524     AVStream *st = NULL;
4525     MOVStreamContext *sc;
4526     int64_t cur_pos;
4527     int i;
4528
4529     for (i = 0; i < s->nb_streams; i++)
4530         if (s->streams[i]->id == mov->chapter_track) {
4531             st = s->streams[i];
4532             break;
4533         }
4534     if (!st) {
4535         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
4536         return;
4537     }
4538
4539     st->discard = AVDISCARD_ALL;
4540     sc = st->priv_data;
4541     cur_pos = avio_tell(sc->pb);
4542
4543     for (i = 0; i < st->nb_index_entries; i++) {
4544         AVIndexEntry *sample = &st->index_entries[i];
4545         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
4546         uint8_t *title;
4547         uint16_t ch;
4548         int len, title_len;
4549
4550         if (end < sample->timestamp) {
4551             av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
4552             end = AV_NOPTS_VALUE;
4553         }
4554
4555         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
4556             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
4557             goto finish;
4558         }
4559
4560         // the first two bytes are the length of the title
4561         len = avio_rb16(sc->pb);
4562         if (len > sample->size-2)
4563             continue;
4564         title_len = 2*len + 1;
4565         if (!(title = av_mallocz(title_len)))
4566             goto finish;
4567
4568         // The samples could theoretically be in any encoding if there's an encd
4569         // atom following, but in practice are only utf-8 or utf-16, distinguished
4570         // instead by the presence of a BOM
4571         if (!len) {
4572             title[0] = 0;
4573         } else {
4574             ch = avio_rb16(sc->pb);
4575             if (ch == 0xfeff)
4576                 avio_get_str16be(sc->pb, len, title, title_len);
4577             else if (ch == 0xfffe)
4578                 avio_get_str16le(sc->pb, len, title, title_len);
4579             else {
4580                 AV_WB16(title, ch);
4581                 if (len == 1 || len == 2)
4582                     title[len] = 0;
4583                 else
4584                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
4585             }
4586         }
4587
4588         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
4589         av_freep(&title);
4590     }
4591 finish:
4592     avio_seek(sc->pb, cur_pos, SEEK_SET);
4593 }
4594
4595 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
4596                                              uint32_t value, int flags)
4597 {
4598     AVTimecode tc;
4599     char buf[AV_TIMECODE_STR_SIZE];
4600     AVRational rate = {st->codec->time_base.den,
4601                        st->codec->time_base.num};
4602     int ret = av_timecode_init(&tc, rate, flags, 0, s);
4603     if (ret < 0)
4604         return ret;
4605     av_dict_set(&st->metadata, "timecode",
4606                 av_timecode_make_string(&tc, buf, value), 0);
4607     return 0;
4608 }
4609
4610 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
4611 {
4612     MOVStreamContext *sc = st->priv_data;
4613     int flags = 0;
4614     int64_t cur_pos = avio_tell(sc->pb);
4615     uint32_t value;
4616
4617     if (!st->nb_index_entries)
4618         return -1;
4619
4620     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
4621     value = avio_rb32(s->pb);
4622
4623     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
4624     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
4625     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
4626
4627     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
4628      * not the case) and thus assume "frame number format" instead of QT one.
4629      * No sample with tmcd track can be found with a QT timecode at the moment,
4630      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
4631      * format). */
4632     parse_timecode_in_framenum_format(s, st, value, flags);
4633
4634     avio_seek(sc->pb, cur_pos, SEEK_SET);
4635     return 0;
4636 }
4637
4638 static int mov_read_close(AVFormatContext *s)
4639 {
4640     MOVContext *mov = s->priv_data;
4641     int i, j;
4642
4643     for (i = 0; i < s->nb_streams; i++) {
4644         AVStream *st = s->streams[i];
4645         MOVStreamContext *sc = st->priv_data;
4646
4647         if (!sc)
4648             continue;
4649
4650         av_freep(&sc->ctts_data);
4651         for (j = 0; j < sc->drefs_count; j++) {
4652             av_freep(&sc->drefs[j].path);
4653             av_freep(&sc->drefs[j].dir);
4654         }
4655         av_freep(&sc->drefs);
4656
4657         sc->drefs_count = 0;
4658
4659         if (!sc->pb_is_copied)
4660             ff_format_io_close(s, &sc->pb);
4661
4662         sc->pb = NULL;
4663         av_freep(&sc->chunk_offsets);
4664         av_freep(&sc->stsc_data);
4665         av_freep(&sc->sample_sizes);
4666         av_freep(&sc->keyframes);
4667         av_freep(&sc->stts_data);
4668         av_freep(&sc->stps_data);
4669         av_freep(&sc->elst_data);
4670         av_freep(&sc->rap_group);
4671         av_freep(&sc->display_matrix);
4672
4673         av_freep(&sc->cenc.auxiliary_info);
4674         av_freep(&sc->cenc.auxiliary_info_sizes);
4675         av_aes_ctr_free(sc->cenc.aes_ctr);
4676     }
4677
4678     if (mov->dv_demux) {
4679         avformat_free_context(mov->dv_fctx);
4680         mov->dv_fctx = NULL;
4681     }
4682
4683     if (mov->meta_keys) {
4684         for (i = 1; i < mov->meta_keys_count; i++) {
4685             av_freep(&mov->meta_keys[i]);
4686         }
4687         av_freep(&mov->meta_keys);
4688     }
4689
4690     av_freep(&mov->trex_data);
4691     av_freep(&mov->bitrates);
4692
4693     for (i = 0; i < mov->fragment_index_count; i++) {
4694         MOVFragmentIndex* index = mov->fragment_index_data[i];
4695         av_freep(&index->items);
4696         av_freep(&mov->fragment_index_data[i]);
4697     }
4698     av_freep(&mov->fragment_index_data);
4699
4700     av_freep(&mov->aes_decrypt);
4701
4702     return 0;
4703 }
4704
4705 static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
4706 {
4707     int i;
4708
4709     for (i = 0; i < s->nb_streams; i++) {
4710         AVStream *st = s->streams[i];
4711         MOVStreamContext *sc = st->priv_data;
4712
4713         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4714             sc->timecode_track == tmcd_id)
4715             return 1;
4716     }
4717     return 0;
4718 }
4719
4720 /* look for a tmcd track not referenced by any video track, and export it globally */
4721 static void export_orphan_timecode(AVFormatContext *s)
4722 {
4723     int i;
4724
4725     for (i = 0; i < s->nb_streams; i++) {
4726         AVStream *st = s->streams[i];
4727
4728         if (st->codec->codec_tag  == MKTAG('t','m','c','d') &&
4729             !tmcd_is_referenced(s, i + 1)) {
4730             AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
4731             if (tcr) {
4732                 av_dict_set(&s->metadata, "timecode", tcr->value, 0);
4733                 break;
4734             }
4735         }
4736     }
4737 }
4738
4739 static int read_tfra(MOVContext *mov, AVIOContext *f)
4740 {
4741     MOVFragmentIndex* index = NULL;
4742     int version, fieldlength, i, j;
4743     int64_t pos = avio_tell(f);
4744     uint32_t size = avio_rb32(f);
4745     void *tmp;
4746
4747     if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
4748         return 1;
4749     }
4750     av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
4751     index = av_mallocz(sizeof(MOVFragmentIndex));
4752     if (!index) {
4753         return AVERROR(ENOMEM);
4754     }
4755
4756     tmp = av_realloc_array(mov->fragment_index_data,
4757                            mov->fragment_index_count + 1,
4758                            sizeof(MOVFragmentIndex*));
4759     if (!tmp) {
4760         av_freep(&index);
4761         return AVERROR(ENOMEM);
4762     }
4763     mov->fragment_index_data = tmp;
4764     mov->fragment_index_data[mov->fragment_index_count++] = index;
4765
4766     version = avio_r8(f);
4767     avio_rb24(f);
4768     index->track_id = avio_rb32(f);
4769     fieldlength = avio_rb32(f);
4770     index->item_count = avio_rb32(f);
4771     index->items = av_mallocz_array(
4772             index->item_count, sizeof(MOVFragmentIndexItem));
4773     if (!index->items) {
4774         index->item_count = 0;
4775         return AVERROR(ENOMEM);
4776     }
4777     for (i = 0; i < index->item_count; i++) {
4778         int64_t time, offset;
4779         if (version == 1) {
4780             time   = avio_rb64(f);
4781             offset = avio_rb64(f);
4782         } else {
4783             time   = avio_rb32(f);
4784             offset = avio_rb32(f);
4785         }
4786         index->items[i].time = time;
4787         index->items[i].moof_offset = offset;
4788         for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
4789             avio_r8(f);
4790         for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
4791             avio_r8(f);
4792         for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
4793             avio_r8(f);
4794     }
4795
4796     avio_seek(f, pos + size, SEEK_SET);
4797     return 0;
4798 }
4799
4800 static int mov_read_mfra(MOVContext *c, AVIOContext *f)
4801 {
4802     int64_t stream_size = avio_size(f);
4803     int64_t original_pos = avio_tell(f);
4804     int64_t seek_ret;
4805     int32_t mfra_size;
4806     int ret = -1;
4807     if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
4808         ret = seek_ret;
4809         goto fail;
4810     }
4811     mfra_size = avio_rb32(f);
4812     if (mfra_size < 0 || mfra_size > stream_size) {
4813         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
4814         goto fail;
4815     }
4816     if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
4817         ret = seek_ret;
4818         goto fail;
4819     }
4820     if (avio_rb32(f) != mfra_size) {
4821         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
4822         goto fail;
4823     }
4824     if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
4825         av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
4826         goto fail;
4827     }
4828     av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
4829     do {
4830         ret = read_tfra(c, f);
4831         if (ret < 0)
4832             goto fail;
4833     } while (!ret);
4834     ret = 0;
4835 fail:
4836     seek_ret = avio_seek(f, original_pos, SEEK_SET);
4837     if (seek_ret < 0) {
4838         av_log(c->fc, AV_LOG_ERROR,
4839                "failed to seek back after looking for mfra\n");
4840         ret = seek_ret;
4841     }
4842     return ret;
4843 }
4844
4845 static int mov_read_header(AVFormatContext *s)
4846 {
4847     MOVContext *mov = s->priv_data;
4848     AVIOContext *pb = s->pb;
4849     int j, err;
4850     MOVAtom atom = { AV_RL32("root") };
4851     int i;
4852
4853     if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
4854         av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
4855             mov->decryption_key_len, AES_CTR_KEY_SIZE);
4856         return AVERROR(EINVAL);
4857     }
4858
4859     mov->fc = s;
4860     mov->trak_index = -1;
4861     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
4862     if (pb->seekable)
4863         atom.size = avio_size(pb);
4864     else
4865         atom.size = INT64_MAX;
4866
4867     /* check MOV header */
4868     do {
4869     if (mov->moov_retry)
4870         avio_seek(pb, 0, SEEK_SET);
4871     if ((err = mov_read_default(mov, pb, atom)) < 0) {
4872         av_log(s, AV_LOG_ERROR, "error reading header\n");
4873         mov_read_close(s);
4874         return err;
4875     }
4876     } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
4877     if (!mov->found_moov) {
4878         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
4879         mov_read_close(s);
4880         return AVERROR_INVALIDDATA;
4881     }
4882     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
4883
4884     if (pb->seekable) {
4885         if (mov->chapter_track > 0 && !mov->ignore_chapters)
4886             mov_read_chapters(s);
4887         for (i = 0; i < s->nb_streams; i++)
4888             if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
4889                 mov_read_timecode_track(s, s->streams[i]);
4890     }
4891
4892     /* copy timecode metadata from tmcd tracks to the related video streams */
4893     for (i = 0; i < s->nb_streams; i++) {
4894         AVStream *st = s->streams[i];
4895         MOVStreamContext *sc = st->priv_data;
4896         if (sc->timecode_track > 0) {
4897             AVDictionaryEntry *tcr;
4898             int tmcd_st_id = -1;
4899
4900             for (j = 0; j < s->nb_streams; j++)
4901                 if (s->streams[j]->id == sc->timecode_track)
4902                     tmcd_st_id = j;
4903
4904             if (tmcd_st_id < 0 || tmcd_st_id == i)
4905                 continue;
4906             tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
4907             if (tcr)
4908                 av_dict_set(&st->metadata, "timecode", tcr->value, 0);
4909         }
4910     }
4911     export_orphan_timecode(s);
4912
4913     for (i = 0; i < s->nb_streams; i++) {
4914         AVStream *st = s->streams[i];
4915         MOVStreamContext *sc = st->priv_data;
4916         fix_timescale(mov, sc);
4917         if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
4918             st->skip_samples = sc->start_pad;
4919         }
4920         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
4921             av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
4922                       sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
4923         if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4924             if (st->codec->width <= 0 || st->codec->height <= 0) {
4925                 st->codec->width  = sc->width;
4926                 st->codec->height = sc->height;
4927             }
4928             if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
4929                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
4930                     return err;
4931             }
4932         }
4933         if (mov->handbrake_version &&
4934             mov->handbrake_version <= 1000000*0 + 1000*10 + 2 &&  // 0.10.2
4935             st->codec->codec_id == AV_CODEC_ID_MP3
4936         ) {
4937             av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
4938             st->need_parsing = AVSTREAM_PARSE_FULL;
4939         }
4940     }
4941
4942     if (mov->trex_data) {
4943         for (i = 0; i < s->nb_streams; i++) {
4944             AVStream *st = s->streams[i];
4945             MOVStreamContext *sc = st->priv_data;
4946             if (st->duration > 0)
4947                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
4948         }
4949     }
4950
4951     if (mov->use_mfra_for > 0) {
4952         for (i = 0; i < s->nb_streams; i++) {
4953             AVStream *st = s->streams[i];
4954             MOVStreamContext *sc = st->priv_data;
4955             if (sc->duration_for_fps > 0) {
4956                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
4957                     sc->duration_for_fps;
4958             }
4959         }
4960     }
4961
4962     for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
4963         if (mov->bitrates[i]) {
4964             s->streams[i]->codec->bit_rate = mov->bitrates[i];
4965         }
4966     }
4967
4968     ff_rfps_calculate(s);
4969
4970     for (i = 0; i < s->nb_streams; i++) {
4971         AVStream *st = s->streams[i];
4972         MOVStreamContext *sc = st->priv_data;
4973
4974         switch (st->codec->codec_type) {
4975         case AVMEDIA_TYPE_AUDIO:
4976             err = ff_replaygain_export(st, s->metadata);
4977             if (err < 0) {
4978                 mov_read_close(s);
4979                 return err;
4980             }
4981             break;
4982         case AVMEDIA_TYPE_VIDEO:
4983             if (sc->display_matrix) {
4984                 AVPacketSideData *sd, *tmp;
4985
4986                 tmp = av_realloc_array(st->side_data,
4987                                        st->nb_side_data + 1, sizeof(*tmp));
4988                 if (!tmp)
4989                     return AVERROR(ENOMEM);
4990
4991                 st->side_data = tmp;
4992                 st->nb_side_data++;
4993
4994                 sd = &st->side_data[st->nb_side_data - 1];
4995                 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
4996                 sd->size = sizeof(int32_t) * 9;
4997                 sd->data = (uint8_t*)sc->display_matrix;
4998                 sc->display_matrix = NULL;
4999             }
5000             break;
5001         }
5002     }
5003     ff_configure_buffers_for_index(s, AV_TIME_BASE);
5004
5005     return 0;
5006 }
5007
5008 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
5009 {
5010     AVIndexEntry *sample = NULL;
5011     int64_t best_dts = INT64_MAX;
5012     int i;
5013     for (i = 0; i < s->nb_streams; i++) {
5014         AVStream *avst = s->streams[i];
5015         MOVStreamContext *msc = avst->priv_data;
5016         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
5017             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
5018             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
5019             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
5020             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
5021                 (s->pb->seekable &&
5022                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
5023                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
5024                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
5025                 sample = current_sample;
5026                 best_dts = dts;
5027                 *st = avst;
5028             }
5029         }
5030     }
5031     return sample;
5032 }
5033
5034 static int should_retry(AVIOContext *pb, int error_code) {
5035     if (error_code == AVERROR_EOF || avio_feof(pb))
5036         return 0;
5037
5038     return 1;
5039 }
5040
5041 static int mov_switch_root(AVFormatContext *s, int64_t target)
5042 {
5043     MOVContext *mov = s->priv_data;
5044     int i, j;
5045     int already_read = 0;
5046
5047     if (avio_seek(s->pb, target, SEEK_SET) != target) {
5048         av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
5049         return AVERROR_INVALIDDATA;
5050     }
5051
5052     mov->next_root_atom = 0;
5053
5054     for (i = 0; i < mov->fragment_index_count; i++) {
5055         MOVFragmentIndex *index = mov->fragment_index_data[i];
5056         int found = 0;
5057         for (j = 0; j < index->item_count; j++) {
5058             MOVFragmentIndexItem *item = &index->items[j];
5059             if (found) {
5060                 mov->next_root_atom = item->moof_offset;
5061                 break; // Advance to next index in outer loop
5062             } else if (item->moof_offset == target) {
5063                 index->current_item = FFMIN(j, index->current_item);
5064                 if (item->headers_read)
5065                     already_read = 1;
5066                 item->headers_read = 1;
5067                 found = 1;
5068             }
5069         }
5070         if (!found)
5071             index->current_item = 0;
5072     }
5073
5074     if (already_read)
5075         return 0;
5076
5077     mov->found_mdat = 0;
5078
5079     if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
5080         avio_feof(s->pb))
5081         return AVERROR_EOF;
5082     av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
5083
5084     return 1;
5085 }
5086
5087 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
5088 {
5089     MOVContext *mov = s->priv_data;
5090     MOVStreamContext *sc;
5091     AVIndexEntry *sample;
5092     AVStream *st = NULL;
5093     int ret;
5094     mov->fc = s;
5095  retry:
5096     sample = mov_find_next_sample(s, &st);
5097     if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
5098         if (!mov->next_root_atom)
5099             return AVERROR_EOF;
5100         if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
5101             return ret;
5102         goto retry;
5103     }
5104     sc = st->priv_data;
5105     /* must be done just before reading, to avoid infinite loop on sample */
5106     sc->current_sample++;
5107
5108     if (mov->next_root_atom) {
5109         sample->pos = FFMIN(sample->pos, mov->next_root_atom);
5110         sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
5111     }
5112
5113     if (st->discard != AVDISCARD_ALL) {
5114         int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
5115         if (ret64 != sample->pos) {
5116             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
5117                    sc->ffindex, sample->pos);
5118             sc->current_sample -= should_retry(sc->pb, ret64);
5119             return AVERROR_INVALIDDATA;
5120         }
5121         ret = av_get_packet(sc->pb, pkt, sample->size);
5122         if (ret < 0) {
5123             sc->current_sample -= should_retry(sc->pb, ret);
5124             return ret;
5125         }
5126         if (sc->has_palette) {
5127             uint8_t *pal;
5128
5129             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
5130             if (!pal) {
5131                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
5132             } else {
5133                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
5134                 sc->has_palette = 0;
5135             }
5136         }
5137 #if CONFIG_DV_DEMUXER
5138         if (mov->dv_demux && sc->dv_audio_container) {
5139             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
5140             av_freep(&pkt->data);
5141             pkt->size = 0;
5142             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
5143             if (ret < 0)
5144                 return ret;
5145         }
5146 #endif
5147     }
5148
5149     pkt->stream_index = sc->ffindex;
5150     pkt->dts = sample->timestamp;
5151     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
5152         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
5153         /* update ctts context */
5154         sc->ctts_sample++;
5155         if (sc->ctts_index < sc->ctts_count &&
5156             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
5157             sc->ctts_index++;
5158             sc->ctts_sample = 0;
5159         }
5160         if (sc->wrong_dts)
5161             pkt->dts = AV_NOPTS_VALUE;
5162     } else {
5163         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
5164             st->index_entries[sc->current_sample].timestamp : st->duration;
5165         pkt->duration = next_dts - pkt->dts;
5166         pkt->pts = pkt->dts;
5167     }
5168     if (st->discard == AVDISCARD_ALL)
5169         goto retry;
5170     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
5171     pkt->pos = sample->pos;
5172
5173     if (mov->aax_mode)
5174         aax_filter(pkt->data, pkt->size, mov);
5175
5176     if (sc->cenc.aes_ctr) {
5177         ret = cenc_filter(mov, sc, pkt->data, pkt->size);
5178         if (ret) {
5179             return ret;
5180         }
5181     }
5182
5183     return 0;
5184 }
5185
5186 static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
5187 {
5188     MOVContext *mov = s->priv_data;
5189     int i, j;
5190
5191     if (!mov->fragment_index_complete)
5192         return 0;
5193
5194     for (i = 0; i < mov->fragment_index_count; i++) {
5195         if (mov->fragment_index_data[i]->track_id == st->id) {
5196             MOVFragmentIndex *index = mov->fragment_index_data[i];
5197             for (j = index->item_count - 1; j >= 0; j--) {
5198                 if (index->items[j].time <= timestamp) {
5199                     if (index->items[j].headers_read)
5200                         return 0;
5201
5202                     return mov_switch_root(s, index->items[j].moof_offset);
5203                 }
5204             }
5205         }
5206     }
5207
5208     return 0;
5209 }
5210
5211 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
5212 {
5213     MOVStreamContext *sc = st->priv_data;
5214     int sample, time_sample;
5215     int i;
5216
5217     int ret = mov_seek_fragment(s, st, timestamp);
5218     if (ret < 0)
5219         return ret;
5220
5221     sample = av_index_search_timestamp(st, timestamp, flags);
5222     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
5223     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
5224         sample = 0;
5225     if (sample < 0) /* not sure what to do */
5226         return AVERROR_INVALIDDATA;
5227     sc->current_sample = sample;
5228     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
5229     /* adjust ctts index */
5230     if (sc->ctts_data) {
5231         time_sample = 0;
5232         for (i = 0; i < sc->ctts_count; i++) {
5233             int next = time_sample + sc->ctts_data[i].count;
5234             if (next > sc->current_sample) {
5235                 sc->ctts_index = i;
5236                 sc->ctts_sample = sc->current_sample - time_sample;
5237                 break;
5238             }
5239             time_sample = next;
5240         }
5241     }
5242
5243     ret = mov_seek_auxiliary_info(s, sc);
5244     if (ret < 0) {
5245         return ret;
5246     }
5247
5248     return sample;
5249 }
5250
5251 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
5252 {
5253     MOVContext *mc = s->priv_data;
5254     AVStream *st;
5255     int sample;
5256     int i;
5257
5258     if (stream_index >= s->nb_streams)
5259         return AVERROR_INVALIDDATA;
5260
5261     st = s->streams[stream_index];
5262     sample = mov_seek_stream(s, st, sample_time, flags);
5263     if (sample < 0)
5264         return sample;
5265
5266     if (mc->seek_individually) {
5267         /* adjust seek timestamp to found sample timestamp */
5268         int64_t seek_timestamp = st->index_entries[sample].timestamp;
5269
5270         for (i = 0; i < s->nb_streams; i++) {
5271             int64_t timestamp;
5272             MOVStreamContext *sc = s->streams[i]->priv_data;
5273             st = s->streams[i];
5274             st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
5275
5276             if (stream_index == i)
5277                 continue;
5278
5279             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
5280             mov_seek_stream(s, st, timestamp, flags);
5281         }
5282     } else {
5283         for (i = 0; i < s->nb_streams; i++) {
5284             MOVStreamContext *sc;
5285             st = s->streams[i];
5286             sc = st->priv_data;
5287             sc->current_sample = 0;
5288         }
5289         while (1) {
5290             MOVStreamContext *sc;
5291             AVIndexEntry *entry = mov_find_next_sample(s, &st);
5292             if (!entry)
5293                 return AVERROR_INVALIDDATA;
5294             sc = st->priv_data;
5295             if (sc->ffindex == stream_index && sc->current_sample == sample)
5296                 break;
5297             sc->current_sample++;
5298         }
5299     }
5300     return 0;
5301 }
5302
5303 #define OFFSET(x) offsetof(MOVContext, x)
5304 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
5305 static const AVOption mov_options[] = {
5306     {"use_absolute_path",
5307         "allow using absolute path when opening alias, this is a possible security issue",
5308         OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
5309         0, 1, FLAGS},
5310     {"seek_streams_individually",
5311         "Seek each stream individually to the to the closest point",
5312         OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
5313         0, 1, FLAGS},
5314     {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
5315         0, 1, FLAGS},
5316     {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
5317         0, 1, FLAGS},
5318     {"use_mfra_for",
5319         "use mfra for fragment timestamps",
5320         OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
5321         -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
5322         "use_mfra_for"},
5323     {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
5324         FLAGS, "use_mfra_for" },
5325     {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
5326         FLAGS, "use_mfra_for" },
5327     {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
5328         FLAGS, "use_mfra_for" },
5329     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
5330         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5331     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
5332         AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
5333     { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
5334         AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5335     { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
5336         "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
5337         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
5338         .flags = AV_OPT_FLAG_DECODING_PARAM },
5339     { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
5340     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
5341         {.i64 = 0}, 0, 1, FLAGS },
5342
5343     { NULL },
5344 };
5345
5346 static const AVClass mov_class = {
5347     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
5348     .item_name  = av_default_item_name,
5349     .option     = mov_options,
5350     .version    = LIBAVUTIL_VERSION_INT,
5351 };
5352
5353 AVInputFormat ff_mov_demuxer = {
5354     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
5355     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
5356     .priv_class     = &mov_class,
5357     .priv_data_size = sizeof(MOVContext),
5358     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
5359     .read_probe     = mov_probe,
5360     .read_header    = mov_read_header,
5361     .read_packet    = mov_read_packet,
5362     .read_close     = mov_read_close,
5363     .read_seek      = mov_read_seek,
5364     .flags          = AVFMT_NO_BYTE_SEEK,
5365 };