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