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