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