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