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