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