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