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