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