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