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