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