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