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