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