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