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