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