]> 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         st->codec->block_align = sc->bytes_per_frame;
1544         break;
1545     case CODEC_ID_ALAC:
1546         if (st->codec->extradata_size == 36) {
1547             st->codec->channels   = AV_RB8 (st->codec->extradata+21);
1548             st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
1549         }
1550         break;
1551     case CODEC_ID_AC3:
1552         st->need_parsing = AVSTREAM_PARSE_FULL;
1553         break;
1554     case CODEC_ID_MPEG1VIDEO:
1555         st->need_parsing = AVSTREAM_PARSE_FULL;
1556         break;
1557     case CODEC_ID_VC1:
1558         st->need_parsing = AVSTREAM_PARSE_FULL;
1559         break;
1560     default:
1561         break;
1562     }
1563
1564     return 0;
1565 }
1566
1567 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1568 {
1569     int entries;
1570
1571     avio_r8(pb); /* version */
1572     avio_rb24(pb); /* flags */
1573     entries = avio_rb32(pb);
1574
1575     return ff_mov_read_stsd_entries(c, pb, entries);
1576 }
1577
1578 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1579 {
1580     AVStream *st;
1581     MOVStreamContext *sc;
1582     unsigned int i, entries;
1583
1584     if (c->fc->nb_streams < 1)
1585         return 0;
1586     st = c->fc->streams[c->fc->nb_streams-1];
1587     sc = st->priv_data;
1588
1589     avio_r8(pb); /* version */
1590     avio_rb24(pb); /* flags */
1591
1592     entries = avio_rb32(pb);
1593
1594     av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1595
1596     if (!entries)
1597         return 0;
1598     if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1599         return AVERROR_INVALIDDATA;
1600     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1601     if (!sc->stsc_data)
1602         return AVERROR(ENOMEM);
1603     sc->stsc_count = entries;
1604
1605     for (i=0; i<entries; i++) {
1606         sc->stsc_data[i].first = avio_rb32(pb);
1607         sc->stsc_data[i].count = avio_rb32(pb);
1608         sc->stsc_data[i].id = avio_rb32(pb);
1609     }
1610     return 0;
1611 }
1612
1613 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1614 {
1615     AVStream *st;
1616     MOVStreamContext *sc;
1617     unsigned i, entries;
1618
1619     if (c->fc->nb_streams < 1)
1620         return 0;
1621     st = c->fc->streams[c->fc->nb_streams-1];
1622     sc = st->priv_data;
1623
1624     avio_rb32(pb); // version + flags
1625
1626     entries = avio_rb32(pb);
1627     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1628         return AVERROR_INVALIDDATA;
1629     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1630     if (!sc->stps_data)
1631         return AVERROR(ENOMEM);
1632     sc->stps_count = entries;
1633
1634     for (i = 0; i < entries; i++) {
1635         sc->stps_data[i] = avio_rb32(pb);
1636         //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
1637     }
1638
1639     return 0;
1640 }
1641
1642 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1643 {
1644     AVStream *st;
1645     MOVStreamContext *sc;
1646     unsigned int i, entries;
1647
1648     if (c->fc->nb_streams < 1)
1649         return 0;
1650     st = c->fc->streams[c->fc->nb_streams-1];
1651     sc = st->priv_data;
1652
1653     avio_r8(pb); /* version */
1654     avio_rb24(pb); /* flags */
1655
1656     entries = avio_rb32(pb);
1657
1658     av_dlog(c->fc, "keyframe_count = %d\n", entries);
1659
1660     if (!entries)
1661     {
1662         sc->keyframe_absent = 1;
1663         return 0;
1664     }
1665     if (entries >= UINT_MAX / sizeof(int))
1666         return AVERROR_INVALIDDATA;
1667     sc->keyframes = av_malloc(entries * sizeof(int));
1668     if (!sc->keyframes)
1669         return AVERROR(ENOMEM);
1670     sc->keyframe_count = entries;
1671
1672     for (i=0; i<entries; i++) {
1673         sc->keyframes[i] = avio_rb32(pb);
1674         //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
1675     }
1676     return 0;
1677 }
1678
1679 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1680 {
1681     AVStream *st;
1682     MOVStreamContext *sc;
1683     unsigned int i, entries, sample_size, field_size, num_bytes;
1684     GetBitContext gb;
1685     unsigned char* buf;
1686
1687     if (c->fc->nb_streams < 1)
1688         return 0;
1689     st = c->fc->streams[c->fc->nb_streams-1];
1690     sc = st->priv_data;
1691
1692     avio_r8(pb); /* version */
1693     avio_rb24(pb); /* flags */
1694
1695     if (atom.type == MKTAG('s','t','s','z')) {
1696         sample_size = avio_rb32(pb);
1697         if (!sc->sample_size) /* do not overwrite value computed in stsd */
1698             sc->sample_size = sample_size;
1699         sc->alt_sample_size = sample_size;
1700         field_size = 32;
1701     } else {
1702         sample_size = 0;
1703         avio_rb24(pb); /* reserved */
1704         field_size = avio_r8(pb);
1705     }
1706     entries = avio_rb32(pb);
1707
1708     av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
1709
1710     sc->sample_count = entries;
1711     if (sample_size)
1712         return 0;
1713
1714     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1715         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1716         return AVERROR_INVALIDDATA;
1717     }
1718
1719     if (!entries)
1720         return 0;
1721     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
1722         return AVERROR_INVALIDDATA;
1723     sc->sample_sizes = av_malloc(entries * sizeof(int));
1724     if (!sc->sample_sizes)
1725         return AVERROR(ENOMEM);
1726
1727     num_bytes = (entries*field_size+4)>>3;
1728
1729     buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
1730     if (!buf) {
1731         av_freep(&sc->sample_sizes);
1732         return AVERROR(ENOMEM);
1733     }
1734
1735     if (avio_read(pb, buf, num_bytes) < num_bytes) {
1736         av_freep(&sc->sample_sizes);
1737         av_free(buf);
1738         return AVERROR_INVALIDDATA;
1739     }
1740
1741     init_get_bits(&gb, buf, 8*num_bytes);
1742
1743     for (i = 0; i < entries; i++) {
1744         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1745         sc->data_size += sc->sample_sizes[i];
1746     }
1747
1748     av_free(buf);
1749     return 0;
1750 }
1751
1752 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1753 {
1754     AVStream *st;
1755     MOVStreamContext *sc;
1756     unsigned int i, entries;
1757     int64_t duration=0;
1758     int64_t total_sample_count=0;
1759
1760     if (c->fc->nb_streams < 1)
1761         return 0;
1762     st = c->fc->streams[c->fc->nb_streams-1];
1763     sc = st->priv_data;
1764
1765     avio_r8(pb); /* version */
1766     avio_rb24(pb); /* flags */
1767     entries = avio_rb32(pb);
1768
1769     av_dlog(c->fc, "track[%i].stts.entries = %i\n",
1770             c->fc->nb_streams-1, entries);
1771
1772     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
1773         return -1;
1774
1775     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
1776     if (!sc->stts_data)
1777         return AVERROR(ENOMEM);
1778
1779     sc->stts_count = entries;
1780
1781     for (i=0; i<entries; i++) {
1782         int sample_duration;
1783         int sample_count;
1784
1785         sample_count=avio_rb32(pb);
1786         sample_duration = avio_rb32(pb);
1787         /* sample_duration < 0 is invalid based on the spec */
1788         if (sample_duration < 0) {
1789             av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
1790             sample_duration = 1;
1791         }
1792         sc->stts_data[i].count= sample_count;
1793         sc->stts_data[i].duration= sample_duration;
1794
1795         av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
1796                 sample_count, sample_duration);
1797
1798         duration+=(int64_t)sample_duration*sample_count;
1799         total_sample_count+=sample_count;
1800     }
1801
1802     st->nb_frames= total_sample_count;
1803     if (duration)
1804         st->duration= duration;
1805     sc->track_end = duration;
1806     return 0;
1807 }
1808
1809 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1810 {
1811     AVStream *st;
1812     MOVStreamContext *sc;
1813     unsigned int i, entries;
1814
1815     if (c->fc->nb_streams < 1)
1816         return 0;
1817     st = c->fc->streams[c->fc->nb_streams-1];
1818     sc = st->priv_data;
1819
1820     avio_r8(pb); /* version */
1821     avio_rb24(pb); /* flags */
1822     entries = avio_rb32(pb);
1823
1824     av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1825
1826     if (!entries)
1827         return 0;
1828     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
1829         return AVERROR_INVALIDDATA;
1830     sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
1831     if (!sc->ctts_data)
1832         return AVERROR(ENOMEM);
1833     sc->ctts_count = entries;
1834
1835     for (i=0; i<entries; i++) {
1836         int count    =avio_rb32(pb);
1837         int duration =avio_rb32(pb);
1838
1839         sc->ctts_data[i].count   = count;
1840         sc->ctts_data[i].duration= duration;
1841
1842         if (FFABS(duration) > (1<<28) && i+2<entries) {
1843             av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
1844             av_freep(&sc->ctts_data);
1845             sc->ctts_count = 0;
1846             return 0;
1847         }
1848
1849         if (duration < 0 && i+2<entries)
1850             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
1851     }
1852
1853     av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
1854
1855     return 0;
1856 }
1857
1858 static void mov_build_index(MOVContext *mov, AVStream *st)
1859 {
1860     MOVStreamContext *sc = st->priv_data;
1861     int64_t current_offset;
1862     int64_t current_dts = 0;
1863     unsigned int stts_index = 0;
1864     unsigned int stsc_index = 0;
1865     unsigned int stss_index = 0;
1866     unsigned int stps_index = 0;
1867     unsigned int i, j;
1868     uint64_t stream_size = 0;
1869     AVIndexEntry *mem;
1870
1871     /* adjust first dts according to edit list */
1872     if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
1873         if (sc->empty_duration)
1874             sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
1875         sc->time_offset = sc->start_time - sc->empty_duration;
1876         current_dts = -sc->time_offset;
1877         if (sc->ctts_count>0 && sc->stts_count>0 &&
1878             sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
1879             /* more than 16 frames delay, dts are likely wrong
1880                this happens with files created by iMovie */
1881             sc->wrong_dts = 1;
1882             st->codec->has_b_frames = 1;
1883         }
1884     }
1885
1886     /* only use old uncompressed audio chunk demuxing when stts specifies it */
1887     if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
1888           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1889         unsigned int current_sample = 0;
1890         unsigned int stts_sample = 0;
1891         unsigned int sample_size;
1892         unsigned int distance = 0;
1893         int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
1894
1895         current_dts -= sc->dts_shift;
1896
1897         if (!sc->sample_count || st->nb_index_entries)
1898             return;
1899         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1900             return;
1901         mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
1902         if (!mem)
1903             return;
1904         st->index_entries = mem;
1905         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
1906
1907         for (i = 0; i < sc->chunk_count; i++) {
1908             current_offset = sc->chunk_offsets[i];
1909             while (stsc_index + 1 < sc->stsc_count &&
1910                 i + 1 == sc->stsc_data[stsc_index + 1].first)
1911                 stsc_index++;
1912             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
1913                 int keyframe = 0;
1914                 if (current_sample >= sc->sample_count) {
1915                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
1916                     return;
1917                 }
1918
1919                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
1920                     keyframe = 1;
1921                     if (stss_index + 1 < sc->keyframe_count)
1922                         stss_index++;
1923                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1924                     keyframe = 1;
1925                     if (stps_index + 1 < sc->stps_count)
1926                         stps_index++;
1927                 }
1928                 if (keyframe)
1929                     distance = 0;
1930                 sample_size = sc->alt_sample_size > 0 ? sc->alt_sample_size : sc->sample_sizes[current_sample];
1931                 if (sc->pseudo_stream_id == -1 ||
1932                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1933                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
1934                     e->pos = current_offset;
1935                     e->timestamp = current_dts;
1936                     e->size = sample_size;
1937                     e->min_distance = distance;
1938                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
1939                     av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1940                             "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1941                             current_offset, current_dts, sample_size, distance, keyframe);
1942                 }
1943
1944                 current_offset += sample_size;
1945                 stream_size += sample_size;
1946                 current_dts += sc->stts_data[stts_index].duration;
1947                 distance++;
1948                 stts_sample++;
1949                 current_sample++;
1950                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1951                     stts_sample = 0;
1952                     stts_index++;
1953                 }
1954             }
1955         }
1956         if (st->duration > 0)
1957             st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
1958     } else {
1959         unsigned chunk_samples, total = 0;
1960
1961         // compute total chunk count
1962         for (i = 0; i < sc->stsc_count; i++) {
1963             unsigned count, chunk_count;
1964
1965             chunk_samples = sc->stsc_data[i].count;
1966             if (i != sc->stsc_count - 1 &&
1967                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1968                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1969                 return;
1970             }
1971
1972             if (sc->samples_per_frame >= 160) { // gsm
1973                 count = chunk_samples / sc->samples_per_frame;
1974             } else if (sc->samples_per_frame > 1) {
1975                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
1976                 count = (chunk_samples+samples-1) / samples;
1977             } else {
1978                 count = (chunk_samples+1023) / 1024;
1979             }
1980
1981             if (i < sc->stsc_count - 1)
1982                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
1983             else
1984                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
1985             total += chunk_count * count;
1986         }
1987
1988         av_dlog(mov->fc, "chunk count %d\n", total);
1989         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
1990             return;
1991         mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
1992         if (!mem)
1993             return;
1994         st->index_entries = mem;
1995         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
1996
1997         // populate index
1998         for (i = 0; i < sc->chunk_count; i++) {
1999             current_offset = sc->chunk_offsets[i];
2000             if (stsc_index + 1 < sc->stsc_count &&
2001                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2002                 stsc_index++;
2003             chunk_samples = sc->stsc_data[stsc_index].count;
2004
2005             while (chunk_samples > 0) {
2006                 AVIndexEntry *e;
2007                 unsigned size, samples;
2008
2009                 if (sc->samples_per_frame >= 160) { // gsm
2010                     samples = sc->samples_per_frame;
2011                     size = sc->bytes_per_frame;
2012                 } else {
2013                     if (sc->samples_per_frame > 1) {
2014                         samples = FFMIN((1024 / sc->samples_per_frame)*
2015                                         sc->samples_per_frame, chunk_samples);
2016                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2017                     } else {
2018                         samples = FFMIN(1024, chunk_samples);
2019                         size = samples * sc->sample_size;
2020                     }
2021                 }
2022
2023                 if (st->nb_index_entries >= total) {
2024                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
2025                     return;
2026                 }
2027                 e = &st->index_entries[st->nb_index_entries++];
2028                 e->pos = current_offset;
2029                 e->timestamp = current_dts;
2030                 e->size = size;
2031                 e->min_distance = 0;
2032                 e->flags = AVINDEX_KEYFRAME;
2033                 av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
2034                         "size %d, duration %d\n", st->index, i, current_offset, current_dts,
2035                         size, samples);
2036
2037                 current_offset += size;
2038                 current_dts += samples;
2039                 chunk_samples -= samples;
2040             }
2041         }
2042     }
2043 }
2044
2045 static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
2046                          AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
2047 {
2048     /* try relative path, we do not try the absolute because it can leak information about our
2049        system to an attacker */
2050     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2051         char filename[1024];
2052         const char *src_path;
2053         int i, l;
2054
2055         /* find a source dir */
2056         src_path = strrchr(src, '/');
2057         if (src_path)
2058             src_path++;
2059         else
2060             src_path = src;
2061
2062         /* find a next level down to target */
2063         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2064             if (ref->path[l] == '/') {
2065                 if (i == ref->nlvl_to - 1)
2066                     break;
2067                 else
2068                     i++;
2069             }
2070
2071         /* compose filename if next level down to target was found */
2072         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
2073             memcpy(filename, src, src_path - src);
2074             filename[src_path - src] = 0;
2075
2076             for (i = 1; i < ref->nlvl_from; i++)
2077                 av_strlcat(filename, "../", 1024);
2078
2079             av_strlcat(filename, ref->path + l + 1, 1024);
2080
2081             if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
2082                 return 0;
2083         }
2084     } else if (use_absolute_path) {
2085         av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
2086                "this is a possible security issue\n");
2087         if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
2088             return 0;
2089     }
2090
2091     return AVERROR(ENOENT);
2092 }
2093
2094 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2095 {
2096     AVStream *st;
2097     MOVStreamContext *sc;
2098     int ret;
2099
2100     st = avformat_new_stream(c->fc, NULL);
2101     if (!st) return AVERROR(ENOMEM);
2102     st->id = c->fc->nb_streams;
2103     sc = av_mallocz(sizeof(MOVStreamContext));
2104     if (!sc) return AVERROR(ENOMEM);
2105
2106     st->priv_data = sc;
2107     st->codec->codec_type = AVMEDIA_TYPE_DATA;
2108     sc->ffindex = st->index;
2109
2110     if ((ret = mov_read_default(c, pb, atom)) < 0)
2111         return ret;
2112
2113     /* sanity checks */
2114     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2115                             (!sc->sample_size && !sc->sample_count))) {
2116         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2117                st->index);
2118         return 0;
2119     }
2120
2121     if (sc->time_scale <= 0) {
2122         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2123         sc->time_scale = c->time_scale;
2124         if (sc->time_scale <= 0)
2125             sc->time_scale = 1;
2126     }
2127
2128     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2129
2130     mov_build_index(c, st);
2131
2132     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2133         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2134         if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
2135             c->use_absolute_path, c->fc) < 0)
2136             av_log(c->fc, AV_LOG_ERROR,
2137                    "stream %d, error opening alias: path='%s', dir='%s', "
2138                    "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
2139                    st->index, dref->path, dref->dir, dref->filename,
2140                    dref->volume, dref->nlvl_from, dref->nlvl_to);
2141     } else
2142         sc->pb = c->fc->pb;
2143
2144     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2145         if (!st->sample_aspect_ratio.num &&
2146             (st->codec->width != sc->width || st->codec->height != sc->height)) {
2147             st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
2148                                              ((double)st->codec->width * sc->height), INT_MAX);
2149         }
2150
2151         av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
2152                   sc->time_scale*st->nb_frames, st->duration, INT_MAX);
2153
2154         if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
2155             av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
2156                       sc->time_scale, sc->stts_data[0].duration, INT_MAX);
2157     }
2158
2159     switch (st->codec->codec_id) {
2160 #if CONFIG_H261_DECODER
2161     case CODEC_ID_H261:
2162 #endif
2163 #if CONFIG_H263_DECODER
2164     case CODEC_ID_H263:
2165 #endif
2166 #if CONFIG_H264_DECODER
2167     case CODEC_ID_H264:
2168 #endif
2169 #if CONFIG_MPEG4_DECODER
2170     case CODEC_ID_MPEG4:
2171 #endif
2172         st->codec->width = 0; /* let decoder init width/height */
2173         st->codec->height= 0;
2174         break;
2175     }
2176
2177     /* Do not need those anymore. */
2178     av_freep(&sc->chunk_offsets);
2179     av_freep(&sc->stsc_data);
2180     av_freep(&sc->sample_sizes);
2181     av_freep(&sc->keyframes);
2182     av_freep(&sc->stts_data);
2183     av_freep(&sc->stps_data);
2184
2185     return 0;
2186 }
2187
2188 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2189 {
2190     int ret;
2191     c->itunes_metadata = 1;
2192     ret = mov_read_default(c, pb, atom);
2193     c->itunes_metadata = 0;
2194     return ret;
2195 }
2196
2197 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2198 {
2199     while (atom.size > 8) {
2200         uint32_t tag = avio_rl32(pb);
2201         atom.size -= 4;
2202         if (tag == MKTAG('h','d','l','r')) {
2203             avio_seek(pb, -8, SEEK_CUR);
2204             atom.size += 8;
2205             return mov_read_default(c, pb, atom);
2206         }
2207     }
2208     return 0;
2209 }
2210
2211 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2212 {
2213     int i;
2214     int width;
2215     int height;
2216     int64_t disp_transform[2];
2217     int display_matrix[3][2];
2218     AVStream *st;
2219     MOVStreamContext *sc;
2220     int version;
2221
2222     if (c->fc->nb_streams < 1)
2223         return 0;
2224     st = c->fc->streams[c->fc->nb_streams-1];
2225     sc = st->priv_data;
2226
2227     version = avio_r8(pb);
2228     avio_rb24(pb); /* flags */
2229     /*
2230     MOV_TRACK_ENABLED 0x0001
2231     MOV_TRACK_IN_MOVIE 0x0002
2232     MOV_TRACK_IN_PREVIEW 0x0004
2233     MOV_TRACK_IN_POSTER 0x0008
2234     */
2235
2236     if (version == 1) {
2237         avio_rb64(pb);
2238         avio_rb64(pb);
2239     } else {
2240         avio_rb32(pb); /* creation time */
2241         avio_rb32(pb); /* modification time */
2242     }
2243     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2244     avio_rb32(pb); /* reserved */
2245
2246     /* highlevel (considering edits) duration in movie timebase */
2247     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2248     avio_rb32(pb); /* reserved */
2249     avio_rb32(pb); /* reserved */
2250
2251     avio_rb16(pb); /* layer */
2252     avio_rb16(pb); /* alternate group */
2253     avio_rb16(pb); /* volume */
2254     avio_rb16(pb); /* reserved */
2255
2256     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2257     // they're kept in fixed point format through all calculations
2258     // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
2259     for (i = 0; i < 3; i++) {
2260         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
2261         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
2262         avio_rb32(pb);           // 2.30 fixed point (not used)
2263     }
2264
2265     width = avio_rb32(pb);       // 16.16 fixed point track width
2266     height = avio_rb32(pb);      // 16.16 fixed point track height
2267     sc->width = width >> 16;
2268     sc->height = height >> 16;
2269
2270     //Assign clockwise rotate values based on transform matrix so that
2271     //we can compensate for iPhone orientation during capture.
2272
2273     if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
2274          av_dict_set(&st->metadata, "rotate", "90", 0);
2275     }
2276
2277     if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
2278          av_dict_set(&st->metadata, "rotate", "180", 0);
2279     }
2280
2281     if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
2282          av_dict_set(&st->metadata, "rotate", "270", 0);
2283     }
2284
2285     // transform the display width/height according to the matrix
2286     // skip this if the display matrix is the default identity matrix
2287     // or if it is rotating the picture, ex iPhone 3GS
2288     // to keep the same scale, use [width height 1<<16]
2289     if (width && height &&
2290         ((display_matrix[0][0] != 65536  ||
2291           display_matrix[1][1] != 65536) &&
2292          !display_matrix[0][1] &&
2293          !display_matrix[1][0] &&
2294          !display_matrix[2][0] && !display_matrix[2][1])) {
2295         for (i = 0; i < 2; i++)
2296             disp_transform[i] =
2297                 (int64_t)  width  * display_matrix[0][i] +
2298                 (int64_t)  height * display_matrix[1][i] +
2299                 ((int64_t) display_matrix[2][i] << 16);
2300
2301         //sample aspect ratio is new width/height divided by old width/height
2302         st->sample_aspect_ratio = av_d2q(
2303             ((double) disp_transform[0] * height) /
2304             ((double) disp_transform[1] * width), INT_MAX);
2305     }
2306     return 0;
2307 }
2308
2309 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2310 {
2311     MOVFragment *frag = &c->fragment;
2312     MOVTrackExt *trex = NULL;
2313     int flags, track_id, i;
2314
2315     avio_r8(pb); /* version */
2316     flags = avio_rb24(pb);
2317
2318     track_id = avio_rb32(pb);
2319     if (!track_id)
2320         return AVERROR_INVALIDDATA;
2321     frag->track_id = track_id;
2322     for (i = 0; i < c->trex_count; i++)
2323         if (c->trex_data[i].track_id == frag->track_id) {
2324             trex = &c->trex_data[i];
2325             break;
2326         }
2327     if (!trex) {
2328         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2329         return AVERROR_INVALIDDATA;
2330     }
2331
2332     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2333                              avio_rb64(pb) : frag->moof_offset;
2334     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2335
2336     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2337                      avio_rb32(pb) : trex->duration;
2338     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
2339                      avio_rb32(pb) : trex->size;
2340     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
2341                      avio_rb32(pb) : trex->flags;
2342     av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
2343     return 0;
2344 }
2345
2346 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2347 {
2348     c->chapter_track = avio_rb32(pb);
2349     return 0;
2350 }
2351
2352 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2353 {
2354     MOVTrackExt *trex;
2355
2356     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2357         return AVERROR_INVALIDDATA;
2358     trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
2359     if (!trex)
2360         return AVERROR(ENOMEM);
2361
2362     c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
2363
2364     c->trex_data = trex;
2365     trex = &c->trex_data[c->trex_count++];
2366     avio_r8(pb); /* version */
2367     avio_rb24(pb); /* flags */
2368     trex->track_id = avio_rb32(pb);
2369     trex->stsd_id  = avio_rb32(pb);
2370     trex->duration = avio_rb32(pb);
2371     trex->size     = avio_rb32(pb);
2372     trex->flags    = avio_rb32(pb);
2373     return 0;
2374 }
2375
2376 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2377 {
2378     MOVFragment *frag = &c->fragment;
2379     AVStream *st = NULL;
2380     MOVStreamContext *sc;
2381     MOVStts *ctts_data;
2382     uint64_t offset;
2383     int64_t dts;
2384     int data_offset = 0;
2385     unsigned entries, first_sample_flags = frag->flags;
2386     int flags, distance, i, found_keyframe = 0;
2387
2388     for (i = 0; i < c->fc->nb_streams; i++) {
2389         if (c->fc->streams[i]->id == frag->track_id) {
2390             st = c->fc->streams[i];
2391             break;
2392         }
2393     }
2394     if (!st) {
2395         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
2396         return AVERROR_INVALIDDATA;
2397     }
2398     sc = st->priv_data;
2399     if (sc->pseudo_stream_id+1 != frag->stsd_id)
2400         return 0;
2401     avio_r8(pb); /* version */
2402     flags = avio_rb24(pb);
2403     entries = avio_rb32(pb);
2404     av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
2405
2406     /* Always assume the presence of composition time offsets.
2407      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2408      *  1) in the initial movie, there are no samples.
2409      *  2) in the first movie fragment, there is only one sample without composition time offset.
2410      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
2411     if (!sc->ctts_count && sc->sample_count)
2412     {
2413         /* Complement ctts table if moov atom doesn't have ctts atom. */
2414         ctts_data = av_malloc(sizeof(*sc->ctts_data));
2415         if (!ctts_data)
2416             return AVERROR(ENOMEM);
2417         sc->ctts_data = ctts_data;
2418         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
2419         sc->ctts_data[sc->ctts_count].duration = 0;
2420         sc->ctts_count++;
2421     }
2422     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
2423         return AVERROR_INVALIDDATA;
2424     ctts_data = av_realloc(sc->ctts_data,
2425                            (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
2426     if (!ctts_data)
2427         return AVERROR(ENOMEM);
2428     sc->ctts_data = ctts_data;
2429
2430     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
2431     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
2432     dts    = sc->track_end - sc->time_offset;
2433     offset = frag->base_data_offset + data_offset;
2434     distance = 0;
2435     av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
2436     for (i = 0; i < entries; i++) {
2437         unsigned sample_size = frag->size;
2438         int sample_flags = i ? frag->flags : first_sample_flags;
2439         unsigned sample_duration = frag->duration;
2440         int keyframe = 0;
2441
2442         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
2443         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
2444         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
2445         sc->ctts_data[sc->ctts_count].count = 1;
2446         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
2447                                                   avio_rb32(pb) : 0;
2448         sc->ctts_count++;
2449         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2450             keyframe = 1;
2451         else if (!found_keyframe)
2452             keyframe = found_keyframe =
2453                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
2454                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
2455         if (keyframe)
2456             distance = 0;
2457         av_add_index_entry(st, offset, dts, sample_size, distance,
2458                            keyframe ? AVINDEX_KEYFRAME : 0);
2459         av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
2460                 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
2461                 offset, dts, sample_size, distance, keyframe);
2462         distance++;
2463         dts += sample_duration;
2464         offset += sample_size;
2465         sc->data_size += sample_size;
2466     }
2467     frag->moof_offset = offset;
2468     st->duration = sc->track_end = dts + sc->time_offset;
2469     return 0;
2470 }
2471
2472 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
2473 /* like the files created with Adobe Premiere 5.0, for samples see */
2474 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
2475 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2476 {
2477     int err;
2478
2479     if (atom.size < 8)
2480         return 0; /* continue */
2481     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
2482         avio_skip(pb, atom.size - 4);
2483         return 0;
2484     }
2485     atom.type = avio_rl32(pb);
2486     atom.size -= 8;
2487     if (atom.type != MKTAG('m','d','a','t')) {
2488         avio_skip(pb, atom.size);
2489         return 0;
2490     }
2491     err = mov_read_mdat(c, pb, atom);
2492     return err;
2493 }
2494
2495 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2496 {
2497 #if CONFIG_ZLIB
2498     AVIOContext ctx;
2499     uint8_t *cmov_data;
2500     uint8_t *moov_data; /* uncompressed data */
2501     long cmov_len, moov_len;
2502     int ret = -1;
2503
2504     avio_rb32(pb); /* dcom atom */
2505     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
2506         return AVERROR_INVALIDDATA;
2507     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
2508         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
2509         return AVERROR_INVALIDDATA;
2510     }
2511     avio_rb32(pb); /* cmvd atom */
2512     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
2513         return AVERROR_INVALIDDATA;
2514     moov_len = avio_rb32(pb); /* uncompressed size */
2515     cmov_len = atom.size - 6 * 4;
2516
2517     cmov_data = av_malloc(cmov_len);
2518     if (!cmov_data)
2519         return AVERROR(ENOMEM);
2520     moov_data = av_malloc(moov_len);
2521     if (!moov_data) {
2522         av_free(cmov_data);
2523         return AVERROR(ENOMEM);
2524     }
2525     avio_read(pb, cmov_data, cmov_len);
2526     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
2527         goto free_and_return;
2528     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
2529         goto free_and_return;
2530     atom.type = MKTAG('m','o','o','v');
2531     atom.size = moov_len;
2532     ret = mov_read_default(c, &ctx, atom);
2533 free_and_return:
2534     av_free(moov_data);
2535     av_free(cmov_data);
2536     return ret;
2537 #else
2538     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
2539     return AVERROR(ENOSYS);
2540 #endif
2541 }
2542
2543 /* edit list atom */
2544 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2545 {
2546     MOVStreamContext *sc;
2547     int i, edit_count, version, edit_start_index = 0;
2548
2549     if (c->fc->nb_streams < 1)
2550         return 0;
2551     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
2552
2553     version = avio_r8(pb); /* version */
2554     avio_rb24(pb); /* flags */
2555     edit_count = avio_rb32(pb); /* entries */
2556
2557     if ((uint64_t)edit_count*12+8 > atom.size)
2558         return AVERROR_INVALIDDATA;
2559
2560     for (i=0; i<edit_count; i++){
2561         int64_t time;
2562         int64_t duration;
2563         if (version == 1) {
2564             duration = avio_rb64(pb);
2565             time     = avio_rb64(pb);
2566         } else {
2567             duration = avio_rb32(pb); /* segment duration */
2568             time     = (int32_t)avio_rb32(pb); /* media time */
2569         }
2570         avio_rb32(pb); /* Media rate */
2571         if (i == 0 && time == -1) {
2572             sc->empty_duration = duration;
2573             edit_start_index = 1;
2574         } else if (i == edit_start_index && time >= 0)
2575             sc->start_time = time;
2576     }
2577
2578     if (edit_count > 1)
2579         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
2580                "a/v desync might occur, patch welcome\n");
2581
2582     av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
2583     return 0;
2584 }
2585
2586 static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2587 {
2588     if (atom.size < 16)
2589         return 0;
2590     avio_skip(pb, 4);
2591     ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
2592     return 0;
2593 }
2594
2595 static const MOVParseTableEntry mov_default_parse_table[] = {
2596 { MKTAG('A','P','R','G'), mov_read_aprg },
2597 { MKTAG('a','v','s','s'), mov_read_avss },
2598 { MKTAG('c','h','p','l'), mov_read_chpl },
2599 { MKTAG('c','o','6','4'), mov_read_stco },
2600 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
2601 { MKTAG('d','i','n','f'), mov_read_default },
2602 { MKTAG('d','r','e','f'), mov_read_dref },
2603 { MKTAG('e','d','t','s'), mov_read_default },
2604 { MKTAG('e','l','s','t'), mov_read_elst },
2605 { MKTAG('e','n','d','a'), mov_read_enda },
2606 { MKTAG('f','i','e','l'), mov_read_fiel },
2607 { MKTAG('f','t','y','p'), mov_read_ftyp },
2608 { MKTAG('g','l','b','l'), mov_read_glbl },
2609 { MKTAG('h','d','l','r'), mov_read_hdlr },
2610 { MKTAG('i','l','s','t'), mov_read_ilst },
2611 { MKTAG('j','p','2','h'), mov_read_jp2h },
2612 { MKTAG('m','d','a','t'), mov_read_mdat },
2613 { MKTAG('m','d','h','d'), mov_read_mdhd },
2614 { MKTAG('m','d','i','a'), mov_read_default },
2615 { MKTAG('m','e','t','a'), mov_read_meta },
2616 { MKTAG('m','i','n','f'), mov_read_default },
2617 { MKTAG('m','o','o','f'), mov_read_moof },
2618 { MKTAG('m','o','o','v'), mov_read_moov },
2619 { MKTAG('m','v','e','x'), mov_read_default },
2620 { MKTAG('m','v','h','d'), mov_read_mvhd },
2621 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
2622 { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
2623 { MKTAG('a','v','c','C'), mov_read_glbl },
2624 { MKTAG('p','a','s','p'), mov_read_pasp },
2625 { MKTAG('s','t','b','l'), mov_read_default },
2626 { MKTAG('s','t','c','o'), mov_read_stco },
2627 { MKTAG('s','t','p','s'), mov_read_stps },
2628 { MKTAG('s','t','r','f'), mov_read_strf },
2629 { MKTAG('s','t','s','c'), mov_read_stsc },
2630 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
2631 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
2632 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
2633 { MKTAG('s','t','t','s'), mov_read_stts },
2634 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
2635 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
2636 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
2637 { MKTAG('t','r','a','k'), mov_read_trak },
2638 { MKTAG('t','r','a','f'), mov_read_default },
2639 { MKTAG('t','r','e','f'), mov_read_default },
2640 { MKTAG('c','h','a','p'), mov_read_chap },
2641 { MKTAG('t','r','e','x'), mov_read_trex },
2642 { MKTAG('t','r','u','n'), mov_read_trun },
2643 { MKTAG('u','d','t','a'), mov_read_default },
2644 { MKTAG('w','a','v','e'), mov_read_wave },
2645 { MKTAG('e','s','d','s'), mov_read_esds },
2646 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
2647 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
2648 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2649 { MKTAG('w','f','e','x'), mov_read_wfex },
2650 { MKTAG('c','m','o','v'), mov_read_cmov },
2651 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
2652 { MKTAG('d','v','c','1'), mov_read_dvc1 },
2653 { 0, NULL }
2654 };
2655
2656 static int mov_probe(AVProbeData *p)
2657 {
2658     unsigned int offset;
2659     uint32_t tag;
2660     int score = 0;
2661
2662     /* check file header */
2663     offset = 0;
2664     for (;;) {
2665         /* ignore invalid offset */
2666         if ((offset + 8) > (unsigned int)p->buf_size)
2667             return score;
2668         tag = AV_RL32(p->buf + offset + 4);
2669         switch(tag) {
2670         /* check for obvious tags */
2671         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2672         case MKTAG('m','o','o','v'):
2673         case MKTAG('m','d','a','t'):
2674         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2675         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
2676         case MKTAG('f','t','y','p'):
2677             return AVPROBE_SCORE_MAX;
2678         /* those are more common words, so rate then a bit less */
2679         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2680         case MKTAG('w','i','d','e'):
2681         case MKTAG('f','r','e','e'):
2682         case MKTAG('j','u','n','k'):
2683         case MKTAG('p','i','c','t'):
2684             return AVPROBE_SCORE_MAX - 5;
2685         case MKTAG(0x82,0x82,0x7f,0x7d):
2686         case MKTAG('s','k','i','p'):
2687         case MKTAG('u','u','i','d'):
2688         case MKTAG('p','r','f','l'):
2689             offset = AV_RB32(p->buf+offset) + offset;
2690             /* if we only find those cause probedata is too small at least rate them */
2691             score = AVPROBE_SCORE_MAX - 50;
2692             break;
2693         default:
2694             /* unrecognized tag */
2695             return score;
2696         }
2697     }
2698 }
2699
2700 // must be done after parsing all trak because there's no order requirement
2701 static void mov_read_chapters(AVFormatContext *s)
2702 {
2703     MOVContext *mov = s->priv_data;
2704     AVStream *st = NULL;
2705     MOVStreamContext *sc;
2706     int64_t cur_pos;
2707     int i;
2708
2709     for (i = 0; i < s->nb_streams; i++)
2710         if (s->streams[i]->id == mov->chapter_track) {
2711             st = s->streams[i];
2712             break;
2713         }
2714     if (!st) {
2715         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
2716         return;
2717     }
2718
2719     st->discard = AVDISCARD_ALL;
2720     sc = st->priv_data;
2721     cur_pos = avio_tell(sc->pb);
2722
2723     for (i = 0; i < st->nb_index_entries; i++) {
2724         AVIndexEntry *sample = &st->index_entries[i];
2725         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
2726         uint8_t *title;
2727         uint16_t ch;
2728         int len, title_len;
2729
2730         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2731             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
2732             goto finish;
2733         }
2734
2735         // the first two bytes are the length of the title
2736         len = avio_rb16(sc->pb);
2737         if (len > sample->size-2)
2738             continue;
2739         title_len = 2*len + 1;
2740         if (!(title = av_mallocz(title_len)))
2741             goto finish;
2742
2743         // The samples could theoretically be in any encoding if there's an encd
2744         // atom following, but in practice are only utf-8 or utf-16, distinguished
2745         // instead by the presence of a BOM
2746         if (!len) {
2747             title[0] = 0;
2748         } else {
2749             ch = avio_rb16(sc->pb);
2750             if (ch == 0xfeff)
2751                 avio_get_str16be(sc->pb, len, title, title_len);
2752             else if (ch == 0xfffe)
2753                 avio_get_str16le(sc->pb, len, title, title_len);
2754             else {
2755                 AV_WB16(title, ch);
2756                 if (len == 1 || len == 2)
2757                     title[len] = 0;
2758                 else
2759                     avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
2760             }
2761         }
2762
2763         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
2764         av_freep(&title);
2765     }
2766 finish:
2767     avio_seek(sc->pb, cur_pos, SEEK_SET);
2768 }
2769
2770 static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
2771                                              uint32_t value, int flags)
2772 {
2773     AVTimecode tc;
2774     char buf[AV_TIMECODE_STR_SIZE];
2775     AVRational rate = {st->codec->time_base.den,
2776                        st->codec->time_base.num};
2777     int ret = av_timecode_init(&tc, rate, flags, 0, s);
2778     if (ret < 0)
2779         return ret;
2780     av_dict_set(&st->metadata, "timecode",
2781                 av_timecode_make_string(&tc, buf, value), 0);
2782     return 0;
2783 }
2784
2785 static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
2786 {
2787     MOVStreamContext *sc = st->priv_data;
2788     int flags = 0;
2789     int64_t cur_pos = avio_tell(sc->pb);
2790     uint32_t value;
2791
2792     if (!st->nb_index_entries)
2793         return -1;
2794
2795     avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
2796     value = avio_rb32(s->pb);
2797
2798     if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
2799     if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
2800     if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
2801
2802     /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
2803      * not the case) and thus assume "frame number format" instead of QT one.
2804      * No sample with tmcd track can be found with a QT timecode at the moment,
2805      * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
2806      * format). */
2807     parse_timecode_in_framenum_format(s, st, value, flags);
2808
2809     avio_seek(sc->pb, cur_pos, SEEK_SET);
2810     return 0;
2811 }
2812
2813 static int mov_read_close(AVFormatContext *s)
2814 {
2815     MOVContext *mov = s->priv_data;
2816     int i, j;
2817
2818     for (i = 0; i < s->nb_streams; i++) {
2819         AVStream *st = s->streams[i];
2820         MOVStreamContext *sc = st->priv_data;
2821
2822         av_freep(&sc->ctts_data);
2823         for (j = 0; j < sc->drefs_count; j++) {
2824             av_freep(&sc->drefs[j].path);
2825             av_freep(&sc->drefs[j].dir);
2826         }
2827         av_freep(&sc->drefs);
2828         if (sc->pb && sc->pb != s->pb)
2829             avio_close(sc->pb);
2830         sc->pb = NULL;
2831         av_freep(&sc->chunk_offsets);
2832         av_freep(&sc->keyframes);
2833         av_freep(&sc->sample_sizes);
2834         av_freep(&sc->stps_data);
2835         av_freep(&sc->stsc_data);
2836         av_freep(&sc->stts_data);
2837     }
2838
2839     if (mov->dv_demux) {
2840         for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
2841             av_freep(&mov->dv_fctx->streams[i]->codec);
2842             av_freep(&mov->dv_fctx->streams[i]);
2843         }
2844         av_freep(&mov->dv_fctx);
2845         av_freep(&mov->dv_demux);
2846     }
2847
2848     av_freep(&mov->trex_data);
2849
2850     return 0;
2851 }
2852
2853 static int mov_read_header(AVFormatContext *s)
2854 {
2855     MOVContext *mov = s->priv_data;
2856     AVIOContext *pb = s->pb;
2857     int err;
2858     MOVAtom atom = { AV_RL32("root") };
2859
2860     mov->fc = s;
2861     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2862     if (pb->seekable)
2863         atom.size = avio_size(pb);
2864     else
2865         atom.size = INT64_MAX;
2866
2867     /* check MOV header */
2868     if ((err = mov_read_default(mov, pb, atom)) < 0) {
2869         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2870         mov_read_close(s);
2871         return err;
2872     }
2873     if (!mov->found_moov) {
2874         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
2875         mov_read_close(s);
2876         return AVERROR_INVALIDDATA;
2877     }
2878     av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
2879
2880     if (pb->seekable) {
2881         int i;
2882         if (mov->chapter_track > 0)
2883             mov_read_chapters(s);
2884         for (i = 0; i < s->nb_streams; i++)
2885             if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
2886                 mov_read_timecode_track(s, s->streams[i]);
2887     }
2888
2889     if (mov->trex_data) {
2890         int i;
2891         for (i = 0; i < s->nb_streams; i++) {
2892             AVStream *st = s->streams[i];
2893             MOVStreamContext *sc = st->priv_data;
2894             if (st->duration)
2895                 st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
2896         }
2897     }
2898
2899     return 0;
2900 }
2901
2902 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2903 {
2904     AVIndexEntry *sample = NULL;
2905     int64_t best_dts = INT64_MAX;
2906     int i;
2907     for (i = 0; i < s->nb_streams; i++) {
2908         AVStream *avst = s->streams[i];
2909         MOVStreamContext *msc = avst->priv_data;
2910         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
2911             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
2912             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
2913             av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
2914             if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
2915                 (s->pb->seekable &&
2916                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
2917                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2918                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2919                 sample = current_sample;
2920                 best_dts = dts;
2921                 *st = avst;
2922             }
2923         }
2924     }
2925     return sample;
2926 }
2927
2928 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2929 {
2930     MOVContext *mov = s->priv_data;
2931     MOVStreamContext *sc;
2932     AVIndexEntry *sample;
2933     AVStream *st = NULL;
2934     int ret;
2935     mov->fc = s;
2936  retry:
2937     sample = mov_find_next_sample(s, &st);
2938     if (!sample) {
2939         mov->found_mdat = 0;
2940         if (!mov->next_root_atom)
2941             return AVERROR_EOF;
2942         avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
2943         mov->next_root_atom = 0;
2944         if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
2945             url_feof(s->pb))
2946             return AVERROR_EOF;
2947         av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
2948         goto retry;
2949     }
2950     sc = st->priv_data;
2951     /* must be done just before reading, to avoid infinite loop on sample */
2952     sc->current_sample++;
2953
2954     if (st->discard != AVDISCARD_ALL) {
2955         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2956             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2957                    sc->ffindex, sample->pos);
2958             return AVERROR_INVALIDDATA;
2959         }
2960         ret = av_get_packet(sc->pb, pkt, sample->size);
2961         if (ret < 0)
2962             return ret;
2963         if (sc->has_palette) {
2964             uint8_t *pal;
2965
2966             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
2967             if (!pal) {
2968                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
2969             } else {
2970                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
2971                 sc->has_palette = 0;
2972             }
2973         }
2974 #if CONFIG_DV_DEMUXER
2975         if (mov->dv_demux && sc->dv_audio_container) {
2976             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
2977             av_free(pkt->data);
2978             pkt->size = 0;
2979             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
2980             if (ret < 0)
2981                 return ret;
2982         }
2983 #endif
2984     }
2985
2986     pkt->stream_index = sc->ffindex;
2987     pkt->dts = sample->timestamp;
2988     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
2989         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
2990         /* update ctts context */
2991         sc->ctts_sample++;
2992         if (sc->ctts_index < sc->ctts_count &&
2993             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2994             sc->ctts_index++;
2995             sc->ctts_sample = 0;
2996         }
2997         if (sc->wrong_dts)
2998             pkt->dts = AV_NOPTS_VALUE;
2999     } else {
3000         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3001             st->index_entries[sc->current_sample].timestamp : st->duration;
3002         pkt->duration = next_dts - pkt->dts;
3003         pkt->pts = pkt->dts;
3004     }
3005     if (st->discard == AVDISCARD_ALL)
3006         goto retry;
3007     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3008     pkt->pos = sample->pos;
3009     av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
3010             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3011     return 0;
3012 }
3013
3014 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3015 {
3016     MOVStreamContext *sc = st->priv_data;
3017     int sample, time_sample;
3018     int i;
3019
3020     sample = av_index_search_timestamp(st, timestamp, flags);
3021     av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3022     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3023         sample = 0;
3024     if (sample < 0) /* not sure what to do */
3025         return AVERROR_INVALIDDATA;
3026     sc->current_sample = sample;
3027     av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
3028     /* adjust ctts index */
3029     if (sc->ctts_data) {
3030         time_sample = 0;
3031         for (i = 0; i < sc->ctts_count; i++) {
3032             int next = time_sample + sc->ctts_data[i].count;
3033             if (next > sc->current_sample) {
3034                 sc->ctts_index = i;
3035                 sc->ctts_sample = sc->current_sample - time_sample;
3036                 break;
3037             }
3038             time_sample = next;
3039         }
3040     }
3041     return sample;
3042 }
3043
3044 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3045 {
3046     AVStream *st;
3047     int64_t seek_timestamp, timestamp;
3048     int sample;
3049     int i;
3050
3051     if (stream_index >= s->nb_streams)
3052         return AVERROR_INVALIDDATA;
3053     if (sample_time < 0)
3054         sample_time = 0;
3055
3056     st = s->streams[stream_index];
3057     sample = mov_seek_stream(s, st, sample_time, flags);
3058     if (sample < 0)
3059         return sample;
3060
3061     /* adjust seek timestamp to found sample timestamp */
3062     seek_timestamp = st->index_entries[sample].timestamp;
3063
3064     for (i = 0; i < s->nb_streams; i++) {
3065         st = s->streams[i];
3066         if (stream_index == i)
3067             continue;
3068
3069         timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3070         mov_seek_stream(s, st, timestamp, flags);
3071     }
3072     return 0;
3073 }
3074
3075 static const AVOption options[] = {
3076     {"use_absolute_path",
3077         "allow using absolute path when opening alias, this is a possible security issue",
3078         offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
3079         0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
3080     {NULL}
3081 };
3082 static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
3083
3084
3085 AVInputFormat ff_mov_demuxer = {
3086     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
3087     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
3088     .priv_data_size = sizeof(MOVContext),
3089     .read_probe     = mov_probe,
3090     .read_header    = mov_read_header,
3091     .read_packet    = mov_read_packet,
3092     .read_close     = mov_read_close,
3093     .read_seek      = mov_read_seek,
3094     .priv_class     = &class,
3095 };