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