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