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