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