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