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