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