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