]> git.sesse.net Git - ffmpeg/blob - libavformat/mov.c
examples/decode_video: switch to the new decoding API
[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          // so is dv (sigh)
1787          codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
1788          (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
1789                                 : codec_tag != MKTAG('j','p','e','g')))) {
1790         /* Multiple fourcc, we skip JPEG. This is not correct, we should
1791          * export it as a separate AVStream but this needs a few changes
1792          * in the MOV demuxer, patch welcome. */
1793
1794         av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
1795         avio_skip(pb, size);
1796         return 1;
1797     }
1798
1799     return 0;
1800 }
1801
1802 int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
1803 {
1804     AVStream *st;
1805     MOVStreamContext *sc;
1806     int pseudo_stream_id;
1807
1808     if (c->fc->nb_streams < 1)
1809         return 0;
1810     st = c->fc->streams[c->fc->nb_streams-1];
1811     sc = st->priv_data;
1812
1813     for (pseudo_stream_id = 0;
1814          pseudo_stream_id < entries && !pb->eof_reached;
1815          pseudo_stream_id++) {
1816         //Parsing Sample description table
1817         enum AVCodecID id;
1818         int ret, dref_id = 1;
1819         MOVAtom a = { AV_RL32("stsd") };
1820         int64_t start_pos = avio_tell(pb);
1821         int64_t size    = avio_rb32(pb); /* size */
1822         uint32_t format = avio_rl32(pb); /* data format */
1823
1824         if (size >= 16) {
1825             avio_rb32(pb); /* reserved */
1826             avio_rb16(pb); /* reserved */
1827             dref_id = avio_rb16(pb);
1828         } else {
1829             av_log(c->fc, AV_LOG_ERROR,
1830                    "invalid size %"PRId64" in stsd\n", size);
1831             return AVERROR_INVALIDDATA;
1832         }
1833
1834         if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
1835                                    size - (avio_tell(pb) - start_pos)))
1836             continue;
1837
1838         sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
1839         sc->dref_id= dref_id;
1840
1841         id = mov_codec_id(st, format);
1842
1843         av_log(c->fc, AV_LOG_TRACE,
1844                "size=%"PRId64" format=0x%08"PRIx32" codec_type=%d\n",
1845                size, format, st->codecpar->codec_type);
1846
1847         if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
1848             st->codecpar->codec_id = id;
1849             mov_parse_stsd_video(c, pb, st, sc);
1850         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
1851             st->codecpar->codec_id = id;
1852             mov_parse_stsd_audio(c, pb, st, sc);
1853         } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
1854             st->codecpar->codec_id = id;
1855             mov_parse_stsd_subtitle(c, pb, st, sc,
1856                                     size - (avio_tell(pb) - start_pos));
1857         } else {
1858             ret = mov_parse_stsd_data(c, pb, st, sc,
1859                                       size - (avio_tell(pb) - start_pos));
1860             if (ret < 0)
1861                 return ret;
1862         }
1863         /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
1864         a.size = size - (avio_tell(pb) - start_pos);
1865         if (a.size > 8) {
1866             if ((ret = mov_read_default(c, pb, a)) < 0)
1867                 return ret;
1868         } else if (a.size > 0)
1869             avio_skip(pb, a.size);
1870
1871         if (sc->extradata) {
1872             int extra_size = st->codecpar->extradata_size;
1873
1874             /* Move the current stream extradata to the stream context one. */
1875             sc->extradata_size[pseudo_stream_id] = extra_size;
1876             sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
1877             if (!sc->extradata[pseudo_stream_id])
1878                 return AVERROR(ENOMEM);
1879             memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
1880             av_freep(&st->codecpar->extradata);
1881             st->codecpar->extradata_size = 0;
1882         }
1883     }
1884
1885     if (pb->eof_reached)
1886         return AVERROR_EOF;
1887
1888     return mov_finalize_stsd_codec(c, pb, st, sc);
1889 }
1890
1891 static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1892 {
1893     AVStream *st;
1894     MOVStreamContext *sc;
1895     int ret, entries;
1896
1897     if (c->fc->nb_streams < 1)
1898         return 0;
1899     st = c->fc->streams[c->fc->nb_streams - 1];
1900     sc = st->priv_data;
1901
1902     avio_r8(pb); /* version */
1903     avio_rb24(pb); /* flags */
1904     entries = avio_rb32(pb);
1905
1906     /* Prepare space for hosting multiple extradata. */
1907     sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
1908     if (!sc->extradata)
1909         return AVERROR(ENOMEM);
1910
1911     sc->stsd_count = entries;
1912     sc->extradata_size = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata_size));
1913     if (!sc->extradata_size)
1914         return AVERROR(ENOMEM);
1915
1916     ret = ff_mov_read_stsd_entries(c, pb, sc->stsd_count);
1917     if (ret < 0)
1918         return ret;
1919
1920     /* Restore back the primary extradata. */
1921     av_free(st->codecpar->extradata);
1922     st->codecpar->extradata_size = sc->extradata_size[0];
1923     st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
1924     if (!st->codecpar->extradata)
1925         return AVERROR(ENOMEM);
1926     memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
1927
1928     return 0;
1929 }
1930
1931 static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1932 {
1933     AVStream *st;
1934     MOVStreamContext *sc;
1935     unsigned int i, entries;
1936
1937     if (c->fc->nb_streams < 1)
1938         return 0;
1939     st = c->fc->streams[c->fc->nb_streams-1];
1940     sc = st->priv_data;
1941
1942     avio_r8(pb); /* version */
1943     avio_rb24(pb); /* flags */
1944
1945     entries = avio_rb32(pb);
1946
1947     av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
1948
1949     if (!entries)
1950         return 0;
1951     if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
1952         return AVERROR_INVALIDDATA;
1953     sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1954     if (!sc->stsc_data)
1955         return AVERROR(ENOMEM);
1956
1957     for (i = 0; i < entries && !pb->eof_reached; i++) {
1958         sc->stsc_data[i].first = avio_rb32(pb);
1959         sc->stsc_data[i].count = avio_rb32(pb);
1960         sc->stsc_data[i].id = avio_rb32(pb);
1961         if (sc->stsc_data[i].id <= 0 || sc->stsc_data[i].id > sc->stsd_count) {
1962             sc->stsc_data[i].id = 1;
1963             if (c->fc->error_recognition & AV_EF_EXPLODE) {
1964                 av_log(c->fc, AV_LOG_ERROR, "Invalid stsc index.\n");
1965                 return AVERROR_INVALIDDATA;
1966             }
1967         }
1968     }
1969
1970     sc->stsc_count = i;
1971
1972     if (pb->eof_reached)
1973         return AVERROR_EOF;
1974
1975     return 0;
1976 }
1977
1978 static inline int mov_stsc_index_valid(int index, int count)
1979 {
1980     return index + 1 < count;
1981 }
1982
1983 /* Compute the samples value for the stsc entry at the given index. */
1984 static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
1985 {
1986     int chunk_count;
1987
1988     if (mov_stsc_index_valid(index, sc->stsc_count))
1989         chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
1990     else
1991         chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
1992
1993     return sc->stsc_data[index].count * chunk_count;
1994 }
1995
1996 static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
1997 {
1998     AVStream *st;
1999     MOVStreamContext *sc;
2000     unsigned i, entries;
2001
2002     if (c->fc->nb_streams < 1)
2003         return 0;
2004     st = c->fc->streams[c->fc->nb_streams-1];
2005     sc = st->priv_data;
2006
2007     avio_rb32(pb); // version + flags
2008
2009     entries = avio_rb32(pb);
2010     if (entries >= UINT_MAX / sizeof(*sc->stps_data))
2011         return AVERROR_INVALIDDATA;
2012     sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
2013     if (!sc->stps_data)
2014         return AVERROR(ENOMEM);
2015
2016     for (i = 0; i < entries && !pb->eof_reached; i++) {
2017         sc->stps_data[i] = avio_rb32(pb);
2018     }
2019
2020     sc->stps_count = i;
2021
2022     if (pb->eof_reached)
2023         return AVERROR_EOF;
2024
2025     return 0;
2026 }
2027
2028 static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2029 {
2030     AVStream *st;
2031     MOVStreamContext *sc;
2032     unsigned int i, entries;
2033
2034     if (c->fc->nb_streams < 1)
2035         return 0;
2036     st = c->fc->streams[c->fc->nb_streams-1];
2037     sc = st->priv_data;
2038
2039     avio_r8(pb); /* version */
2040     avio_rb24(pb); /* flags */
2041
2042     entries = avio_rb32(pb);
2043
2044     av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
2045
2046     if (!entries)
2047     {
2048         sc->keyframe_absent = 1;
2049         return 0;
2050     }
2051     if (entries >= UINT_MAX / sizeof(int))
2052         return AVERROR_INVALIDDATA;
2053     av_freep(&sc->keyframes);
2054     sc->keyframes = av_malloc(entries * sizeof(int));
2055     if (!sc->keyframes)
2056         return AVERROR(ENOMEM);
2057
2058     for (i = 0; i < entries && !pb->eof_reached; i++) {
2059         sc->keyframes[i] = avio_rb32(pb);
2060     }
2061
2062     sc->keyframe_count = i;
2063
2064     if (pb->eof_reached)
2065         return AVERROR_EOF;
2066
2067     return 0;
2068 }
2069
2070 static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2071 {
2072     AVStream *st;
2073     MOVStreamContext *sc;
2074     unsigned int i, entries, sample_size, field_size, num_bytes;
2075     GetBitContext gb;
2076     unsigned char* buf;
2077     int ret;
2078
2079     if (c->fc->nb_streams < 1)
2080         return 0;
2081     st = c->fc->streams[c->fc->nb_streams-1];
2082     sc = st->priv_data;
2083
2084     avio_r8(pb); /* version */
2085     avio_rb24(pb); /* flags */
2086
2087     if (atom.type == MKTAG('s','t','s','z')) {
2088         sample_size = avio_rb32(pb);
2089         if (!sc->sample_size) /* do not overwrite value computed in stsd */
2090             sc->sample_size = sample_size;
2091         field_size = 32;
2092     } else {
2093         sample_size = 0;
2094         avio_rb24(pb); /* reserved */
2095         field_size = avio_r8(pb);
2096     }
2097     entries = avio_rb32(pb);
2098
2099     av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
2100
2101     sc->sample_count = entries;
2102     if (sample_size)
2103         return 0;
2104
2105     if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
2106         av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
2107         return AVERROR_INVALIDDATA;
2108     }
2109
2110     if (!entries)
2111         return 0;
2112     if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
2113         return AVERROR_INVALIDDATA;
2114     sc->sample_sizes = av_malloc(entries * sizeof(int));
2115     if (!sc->sample_sizes)
2116         return AVERROR(ENOMEM);
2117
2118     num_bytes = (entries*field_size+4)>>3;
2119
2120     buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
2121     if (!buf) {
2122         av_freep(&sc->sample_sizes);
2123         return AVERROR(ENOMEM);
2124     }
2125
2126     ret = ffio_read_size(pb, buf, num_bytes);
2127     if (ret < 0) {
2128         av_freep(&sc->sample_sizes);
2129         av_free(buf);
2130         return ret;
2131     }
2132
2133     init_get_bits(&gb, buf, 8*num_bytes);
2134
2135     for (i = 0; i < entries && !pb->eof_reached; i++) {
2136         sc->sample_sizes[i] = get_bits_long(&gb, field_size);
2137         sc->data_size += sc->sample_sizes[i];
2138     }
2139
2140     sc->sample_count = i;
2141
2142     av_free(buf);
2143
2144     if (pb->eof_reached)
2145         return AVERROR_EOF;
2146
2147     return 0;
2148 }
2149
2150 static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2151 {
2152     AVStream *st;
2153     MOVStreamContext *sc;
2154     unsigned int i, entries;
2155     int64_t duration=0;
2156     int64_t total_sample_count=0;
2157
2158     if (c->fc->nb_streams < 1)
2159         return 0;
2160     st = c->fc->streams[c->fc->nb_streams-1];
2161     sc = st->priv_data;
2162
2163     avio_r8(pb); /* version */
2164     avio_rb24(pb); /* flags */
2165     entries = avio_rb32(pb);
2166
2167     av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
2168             c->fc->nb_streams-1, entries);
2169
2170     if (!entries)
2171         return 0;
2172     if (entries >= UINT_MAX / sizeof(*sc->stts_data))
2173         return AVERROR(EINVAL);
2174
2175     av_free(sc->stts_data);
2176     sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
2177     if (!sc->stts_data)
2178         return AVERROR(ENOMEM);
2179
2180     for (i = 0; i < entries && !pb->eof_reached; i++) {
2181         int sample_duration;
2182         int sample_count;
2183
2184         sample_count=avio_rb32(pb);
2185         sample_duration = avio_rb32(pb);
2186         if (sample_count < 0) {
2187             av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
2188             return AVERROR_INVALIDDATA;
2189         }
2190         sc->stts_data[i].count= sample_count;
2191         sc->stts_data[i].duration= sample_duration;
2192
2193         av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
2194                 sample_count, sample_duration);
2195
2196         duration+=(int64_t)sample_duration*sample_count;
2197         total_sample_count+=sample_count;
2198     }
2199
2200     sc->stts_count = i;
2201
2202     if (pb->eof_reached)
2203         return AVERROR_EOF;
2204
2205     st->nb_frames= total_sample_count;
2206     if (duration)
2207         st->duration= duration;
2208     sc->track_end = duration;
2209     return 0;
2210 }
2211
2212 static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2213 {
2214     AVStream *st;
2215     MOVStreamContext *sc;
2216     unsigned int i, entries;
2217
2218     if (c->fc->nb_streams < 1)
2219         return 0;
2220     st = c->fc->streams[c->fc->nb_streams-1];
2221     sc = st->priv_data;
2222
2223     avio_r8(pb); /* version */
2224     avio_rb24(pb); /* flags */
2225     entries = avio_rb32(pb);
2226
2227     av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
2228
2229     av_freep(&sc->ctts_data);
2230
2231     if (!entries)
2232         return 0;
2233     if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
2234         return AVERROR_INVALIDDATA;
2235     sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
2236     if (!sc->ctts_data)
2237         return AVERROR(ENOMEM);
2238
2239     for (i = 0; i < entries && !pb->eof_reached; i++) {
2240         int count    =avio_rb32(pb);
2241         int duration =avio_rb32(pb);
2242
2243         sc->ctts_data[i].count   = count;
2244         sc->ctts_data[i].duration= duration;
2245         if (duration < 0)
2246             sc->dts_shift = FFMAX(sc->dts_shift, -duration);
2247     }
2248
2249     sc->ctts_count = i;
2250
2251     if (pb->eof_reached)
2252         return AVERROR_EOF;
2253
2254     av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
2255
2256     return 0;
2257 }
2258
2259 static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2260 {
2261     AVStream *st;
2262     MOVStreamContext *sc;
2263     unsigned int i, entries;
2264     uint8_t version;
2265     uint32_t grouping_type;
2266
2267     if (c->fc->nb_streams < 1)
2268         return 0;
2269     st = c->fc->streams[c->fc->nb_streams-1];
2270     sc = st->priv_data;
2271
2272     version = avio_r8(pb); /* version */
2273     avio_rb24(pb); /* flags */
2274     grouping_type = avio_rl32(pb);
2275     if (grouping_type != MKTAG( 'r','a','p',' '))
2276         return 0; /* only support 'rap ' grouping */
2277     if (version == 1)
2278         avio_rb32(pb); /* grouping_type_parameter */
2279
2280     entries = avio_rb32(pb);
2281     if (!entries)
2282         return 0;
2283     if (entries >= UINT_MAX / sizeof(*sc->rap_group))
2284         return AVERROR_INVALIDDATA;
2285     sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
2286     if (!sc->rap_group)
2287         return AVERROR(ENOMEM);
2288
2289     for (i = 0; i < entries && !pb->eof_reached; i++) {
2290         sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
2291         sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
2292     }
2293
2294     sc->rap_group_count = i;
2295
2296     return pb->eof_reached ? AVERROR_EOF : 0;
2297 }
2298
2299 static void mov_build_index(MOVContext *mov, AVStream *st)
2300 {
2301     MOVStreamContext *sc = st->priv_data;
2302     int64_t current_offset;
2303     int64_t current_dts = 0;
2304     unsigned int stts_index = 0;
2305     unsigned int stsc_index = 0;
2306     unsigned int stss_index = 0;
2307     unsigned int stps_index = 0;
2308     unsigned int i, j;
2309     uint64_t stream_size = 0;
2310
2311     /* adjust first dts according to edit list */
2312     if (sc->time_offset && mov->time_scale > 0) {
2313         if (sc->time_offset < 0)
2314             sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
2315         current_dts = -sc->time_offset;
2316     }
2317
2318     /* only use old uncompressed audio chunk demuxing when stts specifies it */
2319     if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2320           sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
2321         unsigned int current_sample = 0;
2322         unsigned int stts_sample = 0;
2323         unsigned int sample_size;
2324         unsigned int distance = 0;
2325         unsigned int rap_group_index = 0;
2326         unsigned int rap_group_sample = 0;
2327         int rap_group_present = sc->rap_group_count && sc->rap_group;
2328         int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
2329
2330         current_dts -= sc->dts_shift;
2331
2332         if (!sc->sample_count)
2333             return;
2334         if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2335             return;
2336         if (av_reallocp_array(&st->index_entries,
2337                               st->nb_index_entries + sc->sample_count,
2338                               sizeof(*st->index_entries)) < 0) {
2339             st->nb_index_entries = 0;
2340             return;
2341         }
2342         st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
2343
2344         for (i = 0; i < sc->chunk_count; i++) {
2345             current_offset = sc->chunk_offsets[i];
2346             while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
2347                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2348                 stsc_index++;
2349             for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
2350                 int keyframe = 0;
2351                 if (current_sample >= sc->sample_count) {
2352                     av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
2353                     return;
2354                 }
2355
2356                 if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
2357                     keyframe = 1;
2358                     if (stss_index + 1 < sc->keyframe_count)
2359                         stss_index++;
2360                 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
2361                     keyframe = 1;
2362                     if (stps_index + 1 < sc->stps_count)
2363                         stps_index++;
2364                 }
2365                 if (rap_group_present && rap_group_index < sc->rap_group_count) {
2366                     if (sc->rap_group[rap_group_index].index > 0)
2367                         keyframe = 1;
2368                     if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
2369                         rap_group_sample = 0;
2370                         rap_group_index++;
2371                     }
2372                 }
2373                 if (keyframe)
2374                     distance = 0;
2375                 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
2376                 if (sc->pseudo_stream_id == -1 ||
2377                    sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
2378                     AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
2379                     e->pos = current_offset;
2380                     e->timestamp = current_dts;
2381                     e->size = sample_size;
2382                     e->min_distance = distance;
2383                     e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
2384                     av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
2385                            "size %u, distance %u, keyframe %d\n", st->index, current_sample,
2386                            current_offset, current_dts, sample_size, distance, keyframe);
2387                 }
2388
2389                 current_offset += sample_size;
2390                 stream_size += sample_size;
2391                 current_dts += sc->stts_data[stts_index].duration;
2392                 distance++;
2393                 stts_sample++;
2394                 current_sample++;
2395                 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
2396                     stts_sample = 0;
2397                     stts_index++;
2398                 }
2399             }
2400         }
2401         if (st->duration > 0)
2402             st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
2403     } else {
2404         unsigned chunk_samples, total = 0;
2405
2406         // compute total chunk count
2407         for (i = 0; i < sc->stsc_count; i++) {
2408             unsigned count, chunk_count;
2409
2410             chunk_samples = sc->stsc_data[i].count;
2411             if (i != sc->stsc_count - 1 &&
2412                 sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
2413                 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
2414                 return;
2415             }
2416
2417             if (sc->samples_per_frame >= 160) { // gsm
2418                 count = chunk_samples / sc->samples_per_frame;
2419             } else if (sc->samples_per_frame > 1) {
2420                 unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
2421                 count = (chunk_samples+samples-1) / samples;
2422             } else {
2423                 count = (chunk_samples+1023) / 1024;
2424             }
2425
2426             if (mov_stsc_index_valid(i, sc->stsc_count))
2427                 chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
2428             else
2429                 chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
2430             total += chunk_count * count;
2431         }
2432
2433         av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
2434         if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
2435             return;
2436         if (av_reallocp_array(&st->index_entries,
2437                               st->nb_index_entries + total,
2438                               sizeof(*st->index_entries)) < 0) {
2439             st->nb_index_entries = 0;
2440             return;
2441         }
2442         st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
2443
2444         // populate index
2445         for (i = 0; i < sc->chunk_count; i++) {
2446             current_offset = sc->chunk_offsets[i];
2447             if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
2448                 i + 1 == sc->stsc_data[stsc_index + 1].first)
2449                 stsc_index++;
2450             chunk_samples = sc->stsc_data[stsc_index].count;
2451
2452             while (chunk_samples > 0) {
2453                 AVIndexEntry *e;
2454                 unsigned size, samples;
2455
2456                 if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
2457                     avpriv_request_sample(mov->fc,
2458                            "Zero bytes per frame, but %d samples per frame",
2459                            sc->samples_per_frame);
2460                     return;
2461                 }
2462
2463                 if (sc->samples_per_frame >= 160) { // gsm
2464                     samples = sc->samples_per_frame;
2465                     size = sc->bytes_per_frame;
2466                 } else {
2467                     if (sc->samples_per_frame > 1) {
2468                         samples = FFMIN((1024 / sc->samples_per_frame)*
2469                                         sc->samples_per_frame, chunk_samples);
2470                         size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
2471                     } else {
2472                         samples = FFMIN(1024, chunk_samples);
2473                         size = samples * sc->sample_size;
2474                     }
2475                 }
2476
2477                 if (st->nb_index_entries >= total) {
2478                     av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
2479                     return;
2480                 }
2481                 e = &st->index_entries[st->nb_index_entries++];
2482                 e->pos = current_offset;
2483                 e->timestamp = current_dts;
2484                 e->size = size;
2485                 e->min_distance = 0;
2486                 e->flags = AVINDEX_KEYFRAME;
2487                 av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
2488                        "size %u, duration %u\n", st->index, i, current_offset, current_dts,
2489                        size, samples);
2490
2491                 current_offset += size;
2492                 current_dts += samples;
2493                 chunk_samples -= samples;
2494             }
2495         }
2496     }
2497 }
2498
2499 static int mov_open_dref(AVFormatContext *s, AVIOContext **pb, char *src,
2500                          MOVDref *ref)
2501 {
2502     /* try relative path, we do not try the absolute because it can leak information about our
2503        system to an attacker */
2504     if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
2505         char filename[1024];
2506         char *src_path;
2507         int i, l;
2508
2509         /* find a source dir */
2510         src_path = strrchr(src, '/');
2511         if (src_path)
2512             src_path++;
2513         else
2514             src_path = src;
2515
2516         /* find a next level down to target */
2517         for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
2518             if (ref->path[l] == '/') {
2519                 if (i == ref->nlvl_to - 1)
2520                     break;
2521                 else
2522                     i++;
2523             }
2524
2525         /* compose filename if next level down to target was found */
2526         if (i == ref->nlvl_to - 1 && src_path - src  < sizeof(filename)) {
2527             memcpy(filename, src, src_path - src);
2528             filename[src_path - src] = 0;
2529
2530             for (i = 1; i < ref->nlvl_from; i++)
2531                 av_strlcat(filename, "../", 1024);
2532
2533             av_strlcat(filename, ref->path + l + 1, 1024);
2534
2535             if (!s->io_open(s, pb, filename, AVIO_FLAG_READ, NULL))
2536                 return 0;
2537         }
2538     }
2539
2540     return AVERROR(ENOENT);
2541 }
2542
2543 static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2544 {
2545     AVStream *st;
2546     MOVStreamContext *sc;
2547     int ret;
2548
2549     st = avformat_new_stream(c->fc, NULL);
2550     if (!st) return AVERROR(ENOMEM);
2551     st->id = c->fc->nb_streams;
2552     sc = av_mallocz(sizeof(MOVStreamContext));
2553     if (!sc) return AVERROR(ENOMEM);
2554
2555     st->priv_data = sc;
2556     st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
2557     sc->ffindex = st->index;
2558
2559     if ((ret = mov_read_default(c, pb, atom)) < 0)
2560         return ret;
2561
2562     /* sanity checks */
2563     if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
2564                             (!sc->sample_size && !sc->sample_count))) {
2565         av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
2566                st->index);
2567         return 0;
2568     }
2569
2570     if (sc->time_scale <= 0) {
2571         av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
2572         sc->time_scale = c->time_scale;
2573         if (sc->time_scale <= 0)
2574             sc->time_scale = 1;
2575     }
2576
2577     avpriv_set_pts_info(st, 64, 1, sc->time_scale);
2578
2579     mov_build_index(c, st);
2580
2581     if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
2582         MOVDref *dref = &sc->drefs[sc->dref_id - 1];
2583         if (c->enable_drefs) {
2584             if (mov_open_dref(c->fc, &sc->pb, c->fc->filename, dref) < 0)
2585                 av_log(c->fc, AV_LOG_ERROR,
2586                        "stream %d, error opening alias: path='%s', dir='%s', "
2587                        "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"\n",
2588                        st->index, dref->path, dref->dir, dref->filename,
2589                        dref->volume, dref->nlvl_from, dref->nlvl_to);
2590         } else {
2591             av_log(c->fc, AV_LOG_WARNING,
2592                    "Skipped opening external track: "
2593                    "stream %d, alias: path='%s', dir='%s', "
2594                    "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"."
2595                    "Set enable_drefs to allow this.\n",
2596                    st->index, dref->path, dref->dir, dref->filename,
2597                    dref->volume, dref->nlvl_from, dref->nlvl_to);
2598         }
2599     } else
2600         sc->pb = c->fc->pb;
2601
2602     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2603         if (!st->sample_aspect_ratio.num &&
2604             (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
2605             st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
2606                                              ((double)st->codecpar->width * sc->height), INT_MAX);
2607         }
2608     }
2609
2610     // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
2611     if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
2612         TAG_IS_AVCI(st->codecpar->codec_tag)) {
2613         ret = ff_generate_avci_extradata(st);
2614         if (ret < 0)
2615             return ret;
2616     }
2617
2618     switch (st->codecpar->codec_id) {
2619 #if CONFIG_H261_DECODER
2620     case AV_CODEC_ID_H261:
2621 #endif
2622 #if CONFIG_H263_DECODER
2623     case AV_CODEC_ID_H263:
2624 #endif
2625 #if CONFIG_MPEG4_DECODER
2626     case AV_CODEC_ID_MPEG4:
2627 #endif
2628         st->codecpar->width = 0; /* let decoder init width/height */
2629         st->codecpar->height= 0;
2630         break;
2631     case AV_CODEC_ID_MP3:
2632         st->need_parsing = AVSTREAM_PARSE_FULL;
2633         break;
2634     }
2635
2636     /* Do not need those anymore. */
2637     av_freep(&sc->chunk_offsets);
2638     av_freep(&sc->sample_sizes);
2639     av_freep(&sc->keyframes);
2640     av_freep(&sc->stts_data);
2641     av_freep(&sc->stps_data);
2642     av_freep(&sc->rap_group);
2643
2644     return 0;
2645 }
2646
2647 static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2648 {
2649     int ret;
2650     c->itunes_metadata = 1;
2651     ret = mov_read_default(c, pb, atom);
2652     c->itunes_metadata = 0;
2653     return ret;
2654 }
2655
2656 static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int64_t size)
2657 {
2658     int64_t end = avio_tell(pb) + size;
2659     uint8_t *key = NULL, *val = NULL;
2660     int i;
2661
2662     for (i = 0; i < 2; i++) {
2663         uint8_t **p;
2664         uint32_t len, tag;
2665         int ret;
2666
2667         if (end - avio_tell(pb) <= 12)
2668             break;
2669
2670         len = avio_rb32(pb);
2671         tag = avio_rl32(pb);
2672         avio_skip(pb, 4); // flags
2673
2674         if (len < 12 || len - 12 > end - avio_tell(pb))
2675             break;
2676         len -= 12;
2677
2678         if (tag == MKTAG('n', 'a', 'm', 'e'))
2679             p = &key;
2680         else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
2681             avio_skip(pb, 4);
2682             len -= 4;
2683             p = &val;
2684         } else
2685             break;
2686
2687         *p = av_malloc(len + 1);
2688         if (!*p)
2689             break;
2690         ret = ffio_read_size(pb, *p, len);
2691         if (ret < 0) {
2692             av_freep(p);
2693             return ret;
2694         }
2695         (*p)[len] = 0;
2696     }
2697
2698     if (key && val) {
2699         av_dict_set(&c->fc->metadata, key, val,
2700                     AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
2701         key = val = NULL;
2702     }
2703
2704     avio_seek(pb, end, SEEK_SET);
2705     av_freep(&key);
2706     av_freep(&val);
2707     return 0;
2708 }
2709
2710 static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2711 {
2712     int64_t end = avio_tell(pb) + atom.size;
2713     uint32_t tag, len;
2714
2715     if (atom.size < 8)
2716         goto fail;
2717
2718     len = avio_rb32(pb);
2719     tag = avio_rl32(pb);
2720
2721     if (len > atom.size)
2722         goto fail;
2723
2724     if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
2725         uint8_t domain[128];
2726         int domain_len;
2727
2728         avio_skip(pb, 4); // flags
2729         len -= 12;
2730
2731         domain_len = avio_get_str(pb, len, domain, sizeof(domain));
2732         avio_skip(pb, len - domain_len);
2733         if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
2734             return mov_read_replaygain(c, pb, end - avio_tell(pb));
2735     }
2736
2737 fail:
2738     av_log(c->fc, AV_LOG_VERBOSE,
2739            "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
2740     return 0;
2741 }
2742
2743 static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2744 {
2745     while (atom.size > 8) {
2746         uint32_t tag = avio_rl32(pb);
2747         atom.size -= 4;
2748         if (tag == MKTAG('h','d','l','r')) {
2749             avio_seek(pb, -8, SEEK_CUR);
2750             atom.size += 8;
2751             return mov_read_default(c, pb, atom);
2752         }
2753     }
2754     return 0;
2755 }
2756
2757 // return 1 when matrix is identity, 0 otherwise
2758 #define IS_MATRIX_IDENT(matrix)            \
2759     ( (matrix)[0][0] == (1 << 16) &&       \
2760       (matrix)[1][1] == (1 << 16) &&       \
2761       (matrix)[2][2] == (1 << 30) &&       \
2762      !(matrix)[0][1] && !(matrix)[0][2] && \
2763      !(matrix)[1][0] && !(matrix)[1][2] && \
2764      !(matrix)[2][0] && !(matrix)[2][1])
2765
2766 static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2767 {
2768     int i, j, e;
2769     int width;
2770     int height;
2771     int64_t disp_transform[2];
2772     int display_matrix[3][3];
2773     int res_display_matrix[3][3] = { { 0 } };
2774     AVStream *st;
2775     MOVStreamContext *sc;
2776     int version;
2777     int flags;
2778
2779     if (c->fc->nb_streams < 1)
2780         return 0;
2781     st = c->fc->streams[c->fc->nb_streams-1];
2782     sc = st->priv_data;
2783
2784     version = avio_r8(pb);
2785     flags = avio_rb24(pb);
2786     st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
2787
2788     if (version == 1) {
2789         avio_rb64(pb);
2790         avio_rb64(pb);
2791     } else {
2792         avio_rb32(pb); /* creation time */
2793         avio_rb32(pb); /* modification time */
2794     }
2795     st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
2796     avio_rb32(pb); /* reserved */
2797
2798     /* highlevel (considering edits) duration in movie timebase */
2799     (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
2800     avio_rb32(pb); /* reserved */
2801     avio_rb32(pb); /* reserved */
2802
2803     avio_rb16(pb); /* layer */
2804     avio_rb16(pb); /* alternate group */
2805     avio_rb16(pb); /* volume */
2806     avio_rb16(pb); /* reserved */
2807
2808     //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
2809     // they're kept in fixed point format through all calculations
2810     // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
2811     // side data, but the scale factor is not needed to calculate aspect ratio
2812     for (i = 0; i < 3; i++) {
2813         display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point
2814         display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point
2815         display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point
2816     }
2817
2818     width = avio_rb32(pb);       // 16.16 fixed point track width
2819     height = avio_rb32(pb);      // 16.16 fixed point track height
2820     sc->width = width >> 16;
2821     sc->height = height >> 16;
2822
2823     // apply the moov display matrix (after the tkhd one)
2824     for (i = 0; i < 3; i++) {
2825         const int sh[3] = { 16, 16, 30 };
2826         for (j = 0; j < 3; j++) {
2827             for (e = 0; e < 3; e++) {
2828                 res_display_matrix[i][j] +=
2829                     ((int64_t) display_matrix[i][e] *
2830                      c->movie_display_matrix[e][j]) >> sh[e];
2831             }
2832         }
2833     }
2834
2835     // save the matrix when it is not the default identity
2836     if (!IS_MATRIX_IDENT(res_display_matrix)) {
2837         av_freep(&sc->display_matrix);
2838         sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
2839         if (!sc->display_matrix)
2840             return AVERROR(ENOMEM);
2841
2842         for (i = 0; i < 3; i++)
2843             for (j = 0; j < 3; j++)
2844                 sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
2845     }
2846
2847     // transform the display width/height according to the matrix
2848     // skip this when the display matrix is the identity one
2849     // to keep the same scale, use [width height 1<<16]
2850     if (width && height && sc->display_matrix) {
2851         for (i = 0; i < 2; i++)
2852             disp_transform[i] =
2853                 (int64_t)  width  * sc->display_matrix[0 + i] +
2854                 (int64_t)  height * sc->display_matrix[3 + i] +
2855                 ((int64_t) sc->display_matrix[6 + i] << 16);
2856
2857         //sample aspect ratio is new width/height divided by old width/height
2858         if (disp_transform[0] > 0 && disp_transform[1] > 0)
2859             st->sample_aspect_ratio = av_d2q(
2860                 ((double) disp_transform[0] * height) /
2861                 ((double) disp_transform[1] * width), INT_MAX);
2862     }
2863     return 0;
2864 }
2865
2866 static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2867 {
2868     MOVFragment *frag = &c->fragment;
2869     MOVTrackExt *trex = NULL;
2870     int flags, track_id, i;
2871
2872     avio_r8(pb); /* version */
2873     flags = avio_rb24(pb);
2874
2875     track_id = avio_rb32(pb);
2876     if (!track_id)
2877         return AVERROR_INVALIDDATA;
2878     frag->track_id = track_id;
2879     for (i = 0; i < c->trex_count; i++)
2880         if (c->trex_data[i].track_id == frag->track_id) {
2881             trex = &c->trex_data[i];
2882             break;
2883         }
2884     if (!trex) {
2885         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
2886         return AVERROR_INVALIDDATA;
2887     }
2888
2889     frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
2890                              avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
2891                              frag->moof_offset : frag->implicit_offset;
2892     frag->stsd_id  = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
2893
2894     frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
2895                      avio_rb32(pb) : trex->duration;
2896     frag->size     = flags & MOV_TFHD_DEFAULT_SIZE ?
2897                      avio_rb32(pb) : trex->size;
2898     frag->flags    = flags & MOV_TFHD_DEFAULT_FLAGS ?
2899                      avio_rb32(pb) : trex->flags;
2900     av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
2901     return 0;
2902 }
2903
2904 static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2905 {
2906     c->chapter_track = avio_rb32(pb);
2907     return 0;
2908 }
2909
2910 static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2911 {
2912     MOVTrackExt *trex;
2913     int err;
2914
2915     if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
2916         return AVERROR_INVALIDDATA;
2917     if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
2918                                  sizeof(*c->trex_data))) < 0) {
2919         c->trex_count = 0;
2920         return err;
2921     }
2922     trex = &c->trex_data[c->trex_count++];
2923     avio_r8(pb); /* version */
2924     avio_rb24(pb); /* flags */
2925     trex->track_id = avio_rb32(pb);
2926     trex->stsd_id  = avio_rb32(pb);
2927     trex->duration = avio_rb32(pb);
2928     trex->size     = avio_rb32(pb);
2929     trex->flags    = avio_rb32(pb);
2930     return 0;
2931 }
2932
2933 static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2934 {
2935     MOVFragment *frag = &c->fragment;
2936     AVStream *st = NULL;
2937     MOVStreamContext *sc;
2938     int version, i;
2939
2940     for (i = 0; i < c->fc->nb_streams; i++) {
2941         if (c->fc->streams[i]->id == frag->track_id) {
2942             st = c->fc->streams[i];
2943             break;
2944         }
2945     }
2946     if (!st) {
2947         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
2948         return AVERROR_INVALIDDATA;
2949     }
2950     sc = st->priv_data;
2951     if (sc->pseudo_stream_id + 1 != frag->stsd_id)
2952         return 0;
2953     version = avio_r8(pb);
2954     avio_rb24(pb); /* flags */
2955     if (version) {
2956         sc->track_end = avio_rb64(pb);
2957     } else {
2958         sc->track_end = avio_rb32(pb);
2959     }
2960     return 0;
2961 }
2962
2963 static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
2964 {
2965     MOVFragment *frag = &c->fragment;
2966     AVStream *st = NULL;
2967     MOVStreamContext *sc;
2968     MOVStts *ctts_data;
2969     uint64_t offset;
2970     int64_t dts;
2971     int data_offset = 0;
2972     unsigned entries, first_sample_flags = frag->flags;
2973     int flags, distance, i, err;
2974
2975     for (i = 0; i < c->fc->nb_streams; i++) {
2976         if (c->fc->streams[i]->id == frag->track_id) {
2977             st = c->fc->streams[i];
2978             break;
2979         }
2980     }
2981     if (!st) {
2982         av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
2983         return AVERROR_INVALIDDATA;
2984     }
2985     sc = st->priv_data;
2986     if (sc->pseudo_stream_id+1 != frag->stsd_id)
2987         return 0;
2988     avio_r8(pb); /* version */
2989     flags = avio_rb24(pb);
2990     entries = avio_rb32(pb);
2991     av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
2992
2993     /* Always assume the presence of composition time offsets.
2994      * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
2995      *  1) in the initial movie, there are no samples.
2996      *  2) in the first movie fragment, there is only one sample without composition time offset.
2997      *  3) in the subsequent movie fragments, there are samples with composition time offset. */
2998     if (!sc->ctts_count && sc->sample_count)
2999     {
3000         /* Complement ctts table if moov atom doesn't have ctts atom. */
3001         ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
3002         if (!ctts_data)
3003             return AVERROR(ENOMEM);
3004         sc->ctts_data = ctts_data;
3005         sc->ctts_data[sc->ctts_count].count = sc->sample_count;
3006         sc->ctts_data[sc->ctts_count].duration = 0;
3007         sc->ctts_count++;
3008     }
3009     if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
3010         return AVERROR_INVALIDDATA;
3011     if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
3012                                  sizeof(*sc->ctts_data))) < 0) {
3013         sc->ctts_count = 0;
3014         return err;
3015     }
3016     if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);
3017     if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
3018     dts    = sc->track_end - sc->time_offset;
3019     offset = frag->base_data_offset + data_offset;
3020     distance = 0;
3021     av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
3022     for (i = 0; i < entries && !pb->eof_reached; i++) {
3023         unsigned sample_size = frag->size;
3024         int sample_flags = i ? frag->flags : first_sample_flags;
3025         unsigned sample_duration = frag->duration;
3026         int keyframe = 0;
3027
3028         if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
3029         if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);
3030         if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);
3031         sc->ctts_data[sc->ctts_count].count = 1;
3032         sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
3033                                                   avio_rb32(pb) : 0;
3034         sc->ctts_count++;
3035         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
3036             keyframe = 1;
3037         else
3038             keyframe =
3039                 !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
3040                                   MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
3041         if (keyframe)
3042             distance = 0;
3043         av_add_index_entry(st, offset, dts, sample_size, distance,
3044                            keyframe ? AVINDEX_KEYFRAME : 0);
3045         av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
3046                "size %u, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
3047                offset, dts, sample_size, distance, keyframe);
3048         distance++;
3049         dts += sample_duration;
3050         offset += sample_size;
3051         sc->data_size += sample_size;
3052     }
3053
3054     if (pb->eof_reached)
3055         return AVERROR_EOF;
3056
3057     frag->implicit_offset = offset;
3058     st->duration = sc->track_end = dts + sc->time_offset;
3059     return 0;
3060 }
3061
3062 /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
3063 /* like the files created with Adobe Premiere 5.0, for samples see */
3064 /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
3065 static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3066 {
3067     int err;
3068
3069     if (atom.size < 8)
3070         return 0; /* continue */
3071     if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
3072         avio_skip(pb, atom.size - 4);
3073         return 0;
3074     }
3075     atom.type = avio_rl32(pb);
3076     atom.size -= 8;
3077     if (atom.type != MKTAG('m','d','a','t')) {
3078         avio_skip(pb, atom.size);
3079         return 0;
3080     }
3081     err = mov_read_mdat(c, pb, atom);
3082     return err;
3083 }
3084
3085 static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3086 {
3087 #if CONFIG_ZLIB
3088     AVIOContext ctx;
3089     uint8_t *cmov_data;
3090     uint8_t *moov_data; /* uncompressed data */
3091     long cmov_len, moov_len;
3092     int ret = -1;
3093
3094     avio_rb32(pb); /* dcom atom */
3095     if (avio_rl32(pb) != MKTAG('d','c','o','m'))
3096         return AVERROR_INVALIDDATA;
3097     if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
3098         av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
3099         return AVERROR_INVALIDDATA;
3100     }
3101     avio_rb32(pb); /* cmvd atom */
3102     if (avio_rl32(pb) != MKTAG('c','m','v','d'))
3103         return AVERROR_INVALIDDATA;
3104     moov_len = avio_rb32(pb); /* uncompressed size */
3105     cmov_len = atom.size - 6 * 4;
3106
3107     cmov_data = av_malloc(cmov_len);
3108     if (!cmov_data)
3109         return AVERROR(ENOMEM);
3110     moov_data = av_malloc(moov_len);
3111     if (!moov_data) {
3112         av_free(cmov_data);
3113         return AVERROR(ENOMEM);
3114     }
3115     ret = ffio_read_size(pb, cmov_data, cmov_len);
3116     if (ret < 0)
3117         goto free_and_return;
3118
3119     if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
3120         goto free_and_return;
3121     if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
3122         goto free_and_return;
3123     atom.type = MKTAG('m','o','o','v');
3124     atom.size = moov_len;
3125     ret = mov_read_default(c, &ctx, atom);
3126 free_and_return:
3127     av_free(moov_data);
3128     av_free(cmov_data);
3129     return ret;
3130 #else
3131     av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
3132     return AVERROR(ENOSYS);
3133 #endif
3134 }
3135
3136 /* edit list atom */
3137 static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3138 {
3139     MOVStreamContext *sc;
3140     int i, edit_count, version;
3141
3142     if (c->fc->nb_streams < 1)
3143         return 0;
3144     sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
3145
3146     version = avio_r8(pb); /* version */
3147     avio_rb24(pb); /* flags */
3148     edit_count = avio_rb32(pb); /* entries */
3149
3150     if ((uint64_t)edit_count*12+8 > atom.size)
3151         return AVERROR_INVALIDDATA;
3152
3153     for (i=0; i<edit_count; i++){
3154         int64_t time;
3155         int64_t duration;
3156         if (version == 1) {
3157             duration = avio_rb64(pb);
3158             time     = avio_rb64(pb);
3159         } else {
3160             duration = avio_rb32(pb); /* segment duration */
3161             time     = (int32_t)avio_rb32(pb); /* media time */
3162         }
3163         avio_rb32(pb); /* Media rate */
3164         if (i == 0 && time >= -1) {
3165             sc->time_offset = time != -1 ? time : -duration;
3166         }
3167     }
3168
3169     if (edit_count > 1)
3170         av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
3171                "a/v desync might occur, patch welcome\n");
3172
3173     av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
3174     return 0;
3175 }
3176
3177 static const MOVParseTableEntry mov_default_parse_table[] = {
3178 { MKTAG('a','v','s','s'), mov_read_extradata },
3179 { MKTAG('c','h','p','l'), mov_read_chpl },
3180 { MKTAG('c','o','6','4'), mov_read_stco },
3181 { MKTAG('c','o','l','r'), mov_read_colr },
3182 { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
3183 { MKTAG('d','i','n','f'), mov_read_default },
3184 { MKTAG('d','r','e','f'), mov_read_dref },
3185 { MKTAG('e','d','t','s'), mov_read_default },
3186 { MKTAG('e','l','s','t'), mov_read_elst },
3187 { MKTAG('e','n','d','a'), mov_read_enda },
3188 { MKTAG('f','i','e','l'), mov_read_fiel },
3189 { MKTAG('f','t','y','p'), mov_read_ftyp },
3190 { MKTAG('g','l','b','l'), mov_read_glbl },
3191 { MKTAG('h','d','l','r'), mov_read_hdlr },
3192 { MKTAG('i','l','s','t'), mov_read_ilst },
3193 { MKTAG('j','p','2','h'), mov_read_extradata },
3194 { MKTAG('m','d','a','t'), mov_read_mdat },
3195 { MKTAG('m','d','h','d'), mov_read_mdhd },
3196 { MKTAG('m','d','i','a'), mov_read_default },
3197 { MKTAG('m','e','t','a'), mov_read_meta },
3198 { MKTAG('m','i','n','f'), mov_read_default },
3199 { MKTAG('m','o','o','f'), mov_read_moof },
3200 { MKTAG('m','o','o','v'), mov_read_moov },
3201 { MKTAG('m','v','e','x'), mov_read_default },
3202 { MKTAG('m','v','h','d'), mov_read_mvhd },
3203 { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
3204 { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
3205 { MKTAG('a','v','c','C'), mov_read_glbl },
3206 { MKTAG('p','a','s','p'), mov_read_pasp },
3207 { MKTAG('s','t','b','l'), mov_read_default },
3208 { MKTAG('s','t','c','o'), mov_read_stco },
3209 { MKTAG('s','t','p','s'), mov_read_stps },
3210 { MKTAG('s','t','r','f'), mov_read_strf },
3211 { MKTAG('s','t','s','c'), mov_read_stsc },
3212 { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
3213 { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
3214 { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
3215 { MKTAG('s','t','t','s'), mov_read_stts },
3216 { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
3217 { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
3218 { MKTAG('t','f','d','t'), mov_read_tfdt },
3219 { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
3220 { MKTAG('t','r','a','k'), mov_read_trak },
3221 { MKTAG('t','r','a','f'), mov_read_default },
3222 { MKTAG('t','r','e','f'), mov_read_default },
3223 { MKTAG('c','h','a','p'), mov_read_chap },
3224 { MKTAG('t','r','e','x'), mov_read_trex },
3225 { MKTAG('t','r','u','n'), mov_read_trun },
3226 { MKTAG('u','d','t','a'), mov_read_default },
3227 { MKTAG('w','a','v','e'), mov_read_wave },
3228 { MKTAG('e','s','d','s'), mov_read_esds },
3229 { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
3230 { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
3231 { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
3232 { MKTAG('w','f','e','x'), mov_read_wfex },
3233 { MKTAG('c','m','o','v'), mov_read_cmov },
3234 { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
3235 { MKTAG('d','v','c','1'), mov_read_dvc1 },
3236 { MKTAG('s','b','g','p'), mov_read_sbgp },
3237 { MKTAG('h','v','c','C'), mov_read_glbl },
3238 { MKTAG('-','-','-','-'), mov_read_custom },
3239 { 0, NULL }
3240 };
3241
3242 static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
3243 {
3244     int64_t total_size = 0;
3245     MOVAtom a;
3246     int i;
3247
3248     if (atom.size < 0)
3249         atom.size = INT64_MAX;
3250     while (total_size + 8 < atom.size && !pb->eof_reached) {
3251         int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
3252         a.size = atom.size;
3253         a.type=0;
3254         if (atom.size >= 8) {
3255             a.size = avio_rb32(pb);
3256             a.type = avio_rl32(pb);
3257         }
3258         av_log(c->fc, AV_LOG_TRACE, "type: %08"PRIx32" '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
3259                a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
3260         total_size += 8;
3261         if (a.size == 1) { /* 64 bit extended size */
3262             a.size = avio_rb64(pb) - 8;
3263             total_size += 8;
3264         }
3265         if (a.size == 0) {
3266             a.size = atom.size - total_size;
3267             if (a.size <= 8)
3268                 break;
3269         }
3270         a.size -= 8;
3271         if (a.size < 0)
3272             break;
3273         a.size = FFMIN(a.size, atom.size - total_size);
3274
3275         for (i = 0; mov_default_parse_table[i].type; i++)
3276             if (mov_default_parse_table[i].type == a.type) {
3277                 parse = mov_default_parse_table[i].parse;
3278                 break;
3279             }
3280
3281         // container is user data
3282         if (!parse && (atom.type == MKTAG('u','d','t','a') ||
3283                        atom.type == MKTAG('i','l','s','t')))
3284             parse = mov_read_udta_string;
3285
3286         if (!parse) { /* skip leaf atoms data */
3287             avio_skip(pb, a.size);
3288         } else {
3289             int64_t start_pos = avio_tell(pb);
3290             int64_t left;
3291             int err = parse(c, pb, a);
3292             if (err < 0)
3293                 return err;
3294             if (c->found_moov && c->found_mdat &&
3295                 ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
3296                  start_pos + a.size == avio_size(pb))) {
3297                 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX)
3298                     c->next_root_atom = start_pos + a.size;
3299                 return 0;
3300             }
3301             left = a.size - avio_tell(pb) + start_pos;
3302             if (left > 0) /* skip garbage at atom end */
3303                 avio_skip(pb, left);
3304             else if (left < 0) {
3305                 av_log(c->fc, AV_LOG_WARNING,
3306                        "overread end of atom '%.4s' by %"PRId64" bytes\n",
3307                        (char*)&a.type, -left);
3308                 avio_seek(pb, left, SEEK_CUR);
3309             }
3310         }
3311
3312         total_size += a.size;
3313     }
3314
3315     if (total_size < atom.size && atom.size < 0x7ffff)
3316         avio_skip(pb, atom.size - total_size);
3317
3318     return 0;
3319 }
3320
3321 static int mov_probe(AVProbeData *p)
3322 {
3323     unsigned int offset;
3324     uint32_t tag;
3325     int score = 0;
3326
3327     /* check file header */
3328     offset = 0;
3329     for (;;) {
3330         /* ignore invalid offset */
3331         if ((offset + 8) > (unsigned int)p->buf_size)
3332             return score;
3333         tag = AV_RL32(p->buf + offset + 4);
3334         switch(tag) {
3335         /* check for obvious tags */
3336         case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
3337         case MKTAG('m','o','o','v'):
3338         case MKTAG('m','d','a','t'):
3339         case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
3340         case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
3341         case MKTAG('f','t','y','p'):
3342             return AVPROBE_SCORE_MAX;
3343         /* those are more common words, so rate then a bit less */
3344         case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
3345         case MKTAG('w','i','d','e'):
3346         case MKTAG('f','r','e','e'):
3347         case MKTAG('j','u','n','k'):
3348         case MKTAG('p','i','c','t'):
3349             return AVPROBE_SCORE_MAX - 5;
3350         case MKTAG(0x82,0x82,0x7f,0x7d):
3351         case MKTAG('s','k','i','p'):
3352         case MKTAG('u','u','i','d'):
3353         case MKTAG('p','r','f','l'):
3354             offset = AV_RB32(p->buf+offset) + offset;
3355             /* if we only find those cause probedata is too small at least rate them */
3356             score = AVPROBE_SCORE_EXTENSION;
3357             break;
3358         default:
3359             /* unrecognized tag */
3360             return score;
3361         }
3362     }
3363 }
3364
3365 // must be done after parsing all trak because there's no order requirement
3366 static void mov_read_chapters(AVFormatContext *s)
3367 {
3368     MOVContext *mov = s->priv_data;
3369     AVStream *st = NULL;
3370     MOVStreamContext *sc;
3371     int64_t cur_pos;
3372     int i;
3373
3374     for (i = 0; i < s->nb_streams; i++)
3375         if (s->streams[i]->id == mov->chapter_track) {
3376             st = s->streams[i];
3377             break;
3378         }
3379     if (!st) {
3380         av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
3381         return;
3382     }
3383
3384     st->discard = AVDISCARD_ALL;
3385     sc = st->priv_data;
3386     cur_pos = avio_tell(sc->pb);
3387
3388     for (i = 0; i < st->nb_index_entries; i++) {
3389         AVIndexEntry *sample = &st->index_entries[i];
3390         int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
3391         uint8_t *title;
3392         uint16_t ch;
3393         int len, title_len;
3394
3395         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3396             av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
3397             goto finish;
3398         }
3399
3400         // the first two bytes are the length of the title
3401         len = avio_rb16(sc->pb);
3402         if (len > sample->size-2)
3403             continue;
3404         title_len = 2*len + 1;
3405         if (!(title = av_mallocz(title_len)))
3406             goto finish;
3407
3408         // The samples could theoretically be in any encoding if there's an encd
3409         // atom following, but in practice are only utf-8 or utf-16, distinguished
3410         // instead by the presence of a BOM
3411         if (!len) {
3412             title[0] = 0;
3413         } else {
3414             ch = avio_rb16(sc->pb);
3415             if (ch == 0xfeff)
3416                 avio_get_str16be(sc->pb, len, title, title_len);
3417             else if (ch == 0xfffe)
3418                 avio_get_str16le(sc->pb, len, title, title_len);
3419             else {
3420                 AV_WB16(title, ch);
3421                 if (len == 1 || len == 2)
3422                     title[len] = 0;
3423                 else
3424                     avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
3425             }
3426         }
3427
3428         avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
3429         av_freep(&title);
3430     }
3431 finish:
3432     avio_seek(sc->pb, cur_pos, SEEK_SET);
3433 }
3434
3435 static int mov_read_close(AVFormatContext *s)
3436 {
3437     MOVContext *mov = s->priv_data;
3438     int i, j;
3439
3440     for (i = 0; i < s->nb_streams; i++) {
3441         AVStream *st = s->streams[i];
3442         MOVStreamContext *sc = st->priv_data;
3443
3444         av_freep(&sc->ctts_data);
3445         for (j = 0; j < sc->drefs_count; j++) {
3446             av_freep(&sc->drefs[j].path);
3447             av_freep(&sc->drefs[j].dir);
3448         }
3449         av_freep(&sc->drefs);
3450         if (sc->pb && sc->pb != s->pb)
3451             ff_format_io_close(s, &sc->pb);
3452
3453         av_freep(&sc->chunk_offsets);
3454         av_freep(&sc->stsc_data);
3455         av_freep(&sc->sample_sizes);
3456         av_freep(&sc->keyframes);
3457         av_freep(&sc->stts_data);
3458         av_freep(&sc->stps_data);
3459         av_freep(&sc->rap_group);
3460         av_freep(&sc->display_matrix);
3461
3462         for (j = 0; j < sc->stsd_count; j++)
3463             av_free(sc->extradata[j]);
3464         av_freep(&sc->extradata);
3465         av_freep(&sc->extradata_size);
3466     }
3467
3468     if (mov->dv_demux) {
3469         avformat_free_context(mov->dv_fctx);
3470         mov->dv_fctx = NULL;
3471     }
3472
3473     av_freep(&mov->trex_data);
3474
3475     return 0;
3476 }
3477
3478 static int mov_read_header(AVFormatContext *s)
3479 {
3480     MOVContext *mov = s->priv_data;
3481     AVIOContext *pb = s->pb;
3482     int err;
3483     MOVAtom atom = { AV_RL32("root") };
3484     int i;
3485
3486     mov->fc = s;
3487     /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
3488     if (pb->seekable & AVIO_SEEKABLE_NORMAL)
3489         atom.size = avio_size(pb);
3490     else
3491         atom.size = INT64_MAX;
3492
3493     /* check MOV header */
3494     if ((err = mov_read_default(mov, pb, atom)) < 0) {
3495         av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
3496         mov_read_close(s);
3497         return err;
3498     }
3499     if (!mov->found_moov) {
3500         av_log(s, AV_LOG_ERROR, "moov atom not found\n");
3501         mov_read_close(s);
3502         return AVERROR_INVALIDDATA;
3503     }
3504     av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
3505
3506     if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mov->chapter_track > 0)
3507         mov_read_chapters(s);
3508
3509     for (i = 0; i < s->nb_streams; i++) {
3510         AVStream *st = s->streams[i];
3511         MOVStreamContext *sc = st->priv_data;
3512
3513         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
3514             if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
3515                 st->codecpar->width  = sc->width;
3516                 st->codecpar->height = sc->height;
3517             }
3518             if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
3519                 if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
3520                     return err;
3521             }
3522         }
3523     }
3524
3525     if (mov->trex_data) {
3526         for (i = 0; i < s->nb_streams; i++) {
3527             AVStream *st = s->streams[i];
3528             MOVStreamContext *sc = st->priv_data;
3529             if (st->duration > 0)
3530                 st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
3531         }
3532     }
3533
3534     for (i = 0; i < s->nb_streams; i++) {
3535         AVStream *st = s->streams[i];
3536         MOVStreamContext *sc = st->priv_data;
3537
3538         switch (st->codecpar->codec_type) {
3539         case AVMEDIA_TYPE_AUDIO:
3540             err = ff_replaygain_export(st, s->metadata);
3541             if (err < 0) {
3542                 mov_read_close(s);
3543                 return err;
3544             }
3545             break;
3546         case AVMEDIA_TYPE_VIDEO:
3547             if (sc->display_matrix) {
3548                 AVPacketSideData *sd, *tmp;
3549
3550                 tmp = av_realloc_array(st->side_data,
3551                                        st->nb_side_data + 1, sizeof(*tmp));
3552                 if (!tmp)
3553                     return AVERROR(ENOMEM);
3554
3555                 st->side_data = tmp;
3556                 st->nb_side_data++;
3557
3558                 sd = &st->side_data[st->nb_side_data - 1];
3559                 sd->type = AV_PKT_DATA_DISPLAYMATRIX;
3560                 sd->size = sizeof(int32_t) * 9;
3561                 sd->data = (uint8_t*)sc->display_matrix;
3562                 sc->display_matrix = NULL;
3563             }
3564             break;
3565         }
3566     }
3567
3568     return 0;
3569 }
3570
3571 static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
3572 {
3573     AVIndexEntry *sample = NULL;
3574     int64_t best_dts = INT64_MAX;
3575     int i;
3576     for (i = 0; i < s->nb_streams; i++) {
3577         AVStream *avst = s->streams[i];
3578         MOVStreamContext *msc = avst->priv_data;
3579         if (msc->pb && msc->current_sample < avst->nb_index_entries) {
3580             AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
3581             int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
3582             av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
3583             if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
3584                 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
3585                  ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
3586                  ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
3587                   (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
3588                 sample = current_sample;
3589                 best_dts = dts;
3590                 *st = avst;
3591             }
3592         }
3593     }
3594     return sample;
3595 }
3596
3597 static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
3598 {
3599     uint8_t *side, *extradata;
3600     int extradata_size;
3601
3602     /* Save the current index. */
3603     sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
3604
3605     /* Notify the decoder that extradata changed. */
3606     extradata_size = sc->extradata_size[sc->last_stsd_index];
3607     extradata = sc->extradata[sc->last_stsd_index];
3608     if (extradata_size > 0 && extradata) {
3609         side = av_packet_new_side_data(pkt,
3610                                        AV_PKT_DATA_NEW_EXTRADATA,
3611                                        extradata_size);
3612         if (!side)
3613             return AVERROR(ENOMEM);
3614         memcpy(side, extradata, extradata_size);
3615     }
3616
3617     return 0;
3618 }
3619
3620 static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
3621 {
3622     MOVContext *mov = s->priv_data;
3623     MOVStreamContext *sc;
3624     AVIndexEntry *sample;
3625     AVStream *st = NULL;
3626     int ret;
3627  retry:
3628     sample = mov_find_next_sample(s, &st);
3629     if (!sample) {
3630         mov->found_mdat = 0;
3631         if (!mov->next_root_atom)
3632             return AVERROR_EOF;
3633         avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
3634         mov->next_root_atom = 0;
3635         if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
3636             s->pb->eof_reached)
3637             return AVERROR_EOF;
3638         av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
3639         goto retry;
3640     }
3641     sc = st->priv_data;
3642     /* must be done just before reading, to avoid infinite loop on sample */
3643     sc->current_sample++;
3644
3645     if (st->discard != AVDISCARD_ALL) {
3646         if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
3647             av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
3648                    sc->ffindex, sample->pos);
3649             return AVERROR_INVALIDDATA;
3650         }
3651         ret = av_get_packet(sc->pb, pkt, sample->size);
3652         if (ret < 0)
3653             return ret;
3654         if (sc->has_palette) {
3655             uint8_t *pal;
3656
3657             pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
3658             if (!pal) {
3659                 av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
3660             } else {
3661                 memcpy(pal, sc->palette, AVPALETTE_SIZE);
3662                 sc->has_palette = 0;
3663             }
3664         }
3665 #if CONFIG_DV_DEMUXER
3666         if (mov->dv_demux && sc->dv_audio_container) {
3667             avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
3668             av_free(pkt->data);
3669             pkt->size = 0;
3670             ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
3671             if (ret < 0)
3672                 return ret;
3673         }
3674 #endif
3675     }
3676
3677     pkt->stream_index = sc->ffindex;
3678     pkt->dts = sample->timestamp;
3679     if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
3680         pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
3681         /* update ctts context */
3682         sc->ctts_sample++;
3683         if (sc->ctts_index < sc->ctts_count &&
3684             sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
3685             sc->ctts_index++;
3686             sc->ctts_sample = 0;
3687         }
3688     } else {
3689         int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
3690             st->index_entries[sc->current_sample].timestamp : st->duration;
3691         pkt->duration = next_dts - pkt->dts;
3692         pkt->pts = pkt->dts;
3693     }
3694     if (st->discard == AVDISCARD_ALL)
3695         goto retry;
3696     pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
3697     pkt->pos = sample->pos;
3698     av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
3699             pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
3700
3701     /* Multiple stsd handling. */
3702     if (sc->stsc_data) {
3703         /* Keep track of the stsc index for the given sample, then check
3704         * if the stsd index is different from the last used one. */
3705         sc->stsc_sample++;
3706         if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
3707             mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
3708             sc->stsc_index++;
3709             sc->stsc_sample = 0;
3710         /* Do not check indexes after a switch. */
3711         } else if (sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
3712             ret = mov_change_extradata(sc, pkt);
3713             if (ret < 0)
3714                 return ret;
3715         }
3716     }
3717
3718     return 0;
3719 }
3720
3721 static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
3722 {
3723     MOVStreamContext *sc = st->priv_data;
3724     int sample, time_sample;
3725     int i;
3726
3727     sample = av_index_search_timestamp(st, timestamp, flags);
3728     av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
3729     if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
3730         sample = 0;
3731     if (sample < 0) /* not sure what to do */
3732         return AVERROR_INVALIDDATA;
3733     sc->current_sample = sample;
3734     av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
3735     /* adjust ctts index */
3736     if (sc->ctts_data) {
3737         time_sample = 0;
3738         for (i = 0; i < sc->ctts_count; i++) {
3739             int next = time_sample + sc->ctts_data[i].count;
3740             if (next > sc->current_sample) {
3741                 sc->ctts_index = i;
3742                 sc->ctts_sample = sc->current_sample - time_sample;
3743                 break;
3744             }
3745             time_sample = next;
3746         }
3747     }
3748
3749     /* adjust stsd index */
3750     time_sample = 0;
3751     for (i = 0; i < sc->stsc_count; i++) {
3752         int next = time_sample + mov_get_stsc_samples(sc, i);
3753         if (next > sc->current_sample) {
3754             sc->stsc_index = i;
3755             sc->stsc_sample = sc->current_sample - time_sample;
3756             break;
3757         }
3758         time_sample = next;
3759     }
3760
3761     return sample;
3762 }
3763
3764 static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
3765 {
3766     MOVContext *mc = s->priv_data;
3767     AVStream *st;
3768     int sample;
3769     int i;
3770
3771     if (stream_index >= s->nb_streams)
3772         return AVERROR_INVALIDDATA;
3773     if (sample_time < 0)
3774         sample_time = 0;
3775
3776     st = s->streams[stream_index];
3777     sample = mov_seek_stream(s, st, sample_time, flags);
3778     if (sample < 0)
3779         return sample;
3780
3781     if (mc->seek_individually) {
3782         /* adjust seek timestamp to found sample timestamp */
3783         int64_t seek_timestamp = st->index_entries[sample].timestamp;
3784
3785         for (i = 0; i < s->nb_streams; i++) {
3786             int64_t timestamp;
3787             st = s->streams[i];
3788             if (stream_index == i)
3789                 continue;
3790
3791             timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
3792             mov_seek_stream(s, st, timestamp, flags);
3793         }
3794     } else {
3795         for (i = 0; i < s->nb_streams; i++) {
3796             MOVStreamContext *sc;
3797             st = s->streams[i];
3798             sc = st->priv_data;
3799             sc->current_sample = 0;
3800         }
3801         while (1) {
3802             MOVStreamContext *sc;
3803             AVIndexEntry *entry = mov_find_next_sample(s, &st);
3804             if (!entry)
3805                 return AVERROR_INVALIDDATA;
3806             sc = st->priv_data;
3807             if (sc->ffindex == stream_index && sc->current_sample == sample)
3808                 break;
3809             sc->current_sample++;
3810         }
3811     }
3812     return 0;
3813 }
3814
3815 #define OFFSET(x) offsetof(MOVContext, x)
3816 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
3817 static const AVOption mov_options[] = {
3818     {"seek_streams_individually",
3819         "Seek each stream individually to the to the closest point",
3820         OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
3821         0, 1, FLAGS},
3822     { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
3823         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3824     { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
3825         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3826     { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs),
3827         AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
3828     { NULL },
3829 };
3830
3831 static const AVClass mov_class = {
3832     .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
3833     .item_name  = av_default_item_name,
3834     .option     = mov_options,
3835     .version    = LIBAVUTIL_VERSION_INT,
3836 };
3837
3838 AVInputFormat ff_mov_demuxer = {
3839     .name           = "mov,mp4,m4a,3gp,3g2,mj2",
3840     .long_name      = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
3841     .priv_class     = &mov_class,
3842     .priv_data_size = sizeof(MOVContext),
3843     .extensions     = "mov,mp4,m4a,3gp,3g2,mj2",
3844     .read_probe     = mov_probe,
3845     .read_header    = mov_read_header,
3846     .read_packet    = mov_read_packet,
3847     .read_close     = mov_read_close,
3848     .read_seek      = mov_read_seek,
3849 };