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