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