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