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