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