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