Fix indention after last commit.
[libav.git] / libavformat / mov.c
CommitLineData
6cea494e 1/*
7fbde343 2 * MOV demuxer
406792e7 3 * Copyright (c) 2001 Fabrice Bellard
7c4502c8 4 * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
6cea494e 5 *
b78e7197
DB
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
19720f15
FB
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
b78e7197 11 * version 2.1 of the License, or (at your option) any later version.
6cea494e 12 *
b78e7197 13 * FFmpeg is distributed in the hope that it will be useful,
6cea494e 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
6cea494e 17 *
19720f15 18 * You should have received a copy of the GNU Lesser General Public
b78e7197 19 * License along with FFmpeg; if not, write to the Free Software
5509bffa 20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6cea494e 21 */
d957696f
MN
22
23#include <limits.h>
115329f1 24
bfc2a19d 25//#define DEBUG
873358e5
BC
26//#define DEBUG_METADATA
27//#define MOV_EXPORT_ALL_METADATA
4e5ef14f 28
6a5d31ac 29#include "libavutil/intreadwrite.h"
49674dd0 30#include "libavutil/avstring.h"
6cea494e 31#include "avformat.h"
9d9f4119 32#include "riff.h"
e40ee6a2 33#include "isom.h"
245976da
DB
34#include "libavcodec/mpeg4audio.h"
35#include "libavcodec/mpegaudiodata.h"
9106a698 36#include "libavcodec/get_bits.h"
6cea494e 37
b250f9c6 38#if CONFIG_ZLIB
0147f198
FR
39#include <zlib.h>
40#endif
41
6cea494e
ZK
42/*
43 * First version by Francois Revol revol@free.fr
115329f1 44 * Seek function by Gael Chardon gael.dev@4now.net
5ca1d879 45 *
6cea494e 46 * Features and limitations:
5ca1d879 47 * - reads most of the QT files I have (at least the structure),
6cea494e 48 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
6cea494e 49 * - the code is quite ugly... maybe I won't do it recursive next time :-)
5ca1d879 50 *
6cea494e
ZK
51 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
52 * when coding this :) (it's a writer anyway)
5ca1d879 53 *
6cea494e
ZK
54 * Reference documents:
55 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
56 * Apple:
baf25c9d 57 * http://developer.apple.com/documentation/QuickTime/QTFF/
15c8dbe7 58 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
6cea494e
ZK
59 * QuickTime is a trademark of Apple (AFAIK :))
60 */
61
b595afaa
MM
62#include "qtpalette.h"
63
baf25c9d 64
cd7352d5
MN
65#undef NDEBUG
66#include <assert.h>
67
6cea494e
ZK
68/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
69
70/* those functions parse an atom */
71/* return code:
e3c4740f 72 0: continue to parse next atom
d9526386 73 <0: error occurred, exit
e3c4740f 74*/
6cea494e
ZK
75/* links atom IDs to parse functions */
76typedef struct MOVParseTableEntry {
0c1a9eda 77 uint32_t type;
c3e92a6c 78 int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
6cea494e
ZK
79} MOVParseTableEntry;
80
73d07c27
BC
81static const MOVParseTableEntry mov_default_parse_table[];
82
c6026e43
BC
83static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
84{
85 char buf[16];
86
87 get_be16(pb); // unknown
88 snprintf(buf, sizeof(buf), "%d", get_be16(pb));
89 av_metadata_set(&c->fc->metadata, "track", buf);
90
91 get_be16(pb); // total tracks
92
93 return 0;
94}
95
0fb44a4e
BC
96static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
97{
98#ifdef MOV_EXPORT_ALL_METADATA
99 char tmp_key[5];
100#endif
101 char str[1024], key2[16], language[4] = {0};
102 const char *key = NULL;
103 uint16_t str_size;
c6026e43 104 int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
0fb44a4e
BC
105
106 switch (atom.type) {
107 case MKTAG(0xa9,'n','a','m'): key = "title"; break;
108 case MKTAG(0xa9,'a','u','t'):
55d2e32a
BC
109 case MKTAG(0xa9,'A','R','T'): key = "author"; break;
110 case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
0fb44a4e
BC
111 case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
112 case MKTAG(0xa9,'c','m','t'):
113 case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
114 case MKTAG(0xa9,'a','l','b'): key = "album"; break;
115 case MKTAG(0xa9,'d','a','y'): key = "year"; break;
116 case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
117 case MKTAG(0xa9,'t','o','o'):
a4cb56aa 118 case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
c6026e43
BC
119 case MKTAG( 't','r','k','n'): key = "track";
120 parse = mov_metadata_trkn; break;
0fb44a4e
BC
121 }
122
123 if (c->itunes_metadata && atom.size > 8) {
124 int data_size = get_be32(pb);
125 int tag = get_le32(pb);
126 if (tag == MKTAG('d','a','t','a')) {
127 get_be32(pb); // type
128 get_be32(pb); // unknown
129 str_size = data_size - 16;
130 atom.size -= 16;
131 } else return 0;
132 } else if (atom.size > 4 && key && !c->itunes_metadata) {
133 str_size = get_be16(pb); // string length
134 ff_mov_lang_to_iso639(get_be16(pb), language);
135 atom.size -= 4;
136 } else
137 str_size = atom.size;
138
139#ifdef MOV_EXPORT_ALL_METADATA
140 if (!key) {
141 snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
142 key = tmp_key;
143 }
144#endif
145
146 if (!key)
147 return 0;
148 if (atom.size < 0)
149 return -1;
150
151 str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
c6026e43
BC
152
153 if (parse)
154 parse(c, pb, str_size);
155 else {
f584386d
BC
156 get_buffer(pb, str, str_size);
157 str[str_size] = 0;
158 av_metadata_set(&c->fc->metadata, key, str);
159 if (*language && strcmp(language, "und")) {
160 snprintf(key2, sizeof(key2), "%s-%s", key, language);
161 av_metadata_set(&c->fc->metadata, key2, str);
162 }
c6026e43 163 }
0fb44a4e
BC
164#ifdef DEBUG_METADATA
165 av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
166 av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
167 key, str, (char*)&atom.type, str_size, atom.size);
168#endif
169
170 return 0;
171}
873358e5 172
c3e92a6c 173static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
6cea494e 174{
b6a17df4 175 int64_t total_size = 0;
c3e92a6c 176 MOVAtom a;
6cea494e
ZK
177 int i;
178 int err = 0;
5ca1d879 179
5ca1d879 180 a.offset = atom.offset;
6cea494e 181
9ed83b0a 182 if (atom.size < 0)
fa22ca22 183 atom.size = INT64_MAX;
5ca1d879 184 while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
873358e5 185 int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
bb270c08 186 a.size = atom.size;
bcfe2ba0 187 a.type=0;
5ca1d879 188 if(atom.size >= 8) {
bb270c08 189 a.size = get_be32(pb);
5ca1d879 190 a.type = get_le32(pb);
6cea494e 191 }
bb270c08 192 total_size += 8;
5ca1d879 193 a.offset += 8;
29c90869
BC
194 dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n",
195 a.type, (char*)&a.type, a.size, atom.size, total_size);
5ca1d879 196 if (a.size == 1) { /* 64 bit extended size */
bb270c08 197 a.size = get_be64(pb) - 8;
5ca1d879
ZK
198 a.offset += 8;
199 total_size += 8;
6cea494e 200 }
bb270c08
DB
201 if (a.size == 0) {
202 a.size = atom.size - total_size;
203 if (a.size <= 8)
5cd62665 204 break;
bb270c08 205 }
bb270c08 206 a.size -= 8;
8622613d 207 if(a.size < 0)
568e18b1 208 break;
3d2308b0 209 a.size = FFMIN(a.size, atom.size - total_size);
115329f1 210
873358e5
BC
211 for (i = 0; mov_default_parse_table[i].type; i++)
212 if (mov_default_parse_table[i].type == a.type) {
213 parse = mov_default_parse_table[i].parse;
214 break;
215 }
11979c46 216
873358e5
BC
217 // container is user data
218 if (!parse && (atom.type == MKTAG('u','d','t','a') ||
219 atom.type == MKTAG('i','l','s','t')))
220 parse = mov_read_udta_string;
221
222 if (!parse) { /* skip leaf atoms data */
5ca1d879 223 url_fskip(pb, a.size);
bb270c08 224 } else {
bc5c918e 225 int64_t start_pos = url_ftell(pb);
5c72cad8 226 int64_t left;
873358e5 227 err = parse(c, pb, a);
db3ee6cc 228 if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
687f35f3 229 break;
5c72cad8
BC
230 left = a.size - url_ftell(pb) + start_pos;
231 if (left > 0) /* skip garbage at atom end */
232 url_fskip(pb, left);
bb270c08 233 }
6cea494e 234
bb270c08 235 a.offset += a.size;
5ca1d879 236 total_size += a.size;
6cea494e
ZK
237 }
238
9ce84dd8 239 if (!err && total_size < atom.size && atom.size < 0x7ffff)
5ca1d879 240 url_fskip(pb, atom.size - total_size);
5cd62665 241
6cea494e
ZK
242 return err;
243}
244
c3e92a6c 245static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
221e21b7 246{
6a63ff19
BC
247 AVStream *st;
248 MOVStreamContext *sc;
221e21b7
BC
249 int entries, i, j;
250
6a63ff19
BC
251 if (c->fc->nb_streams < 1)
252 return 0;
253 st = c->fc->streams[c->fc->nb_streams-1];
254 sc = st->priv_data;
255
221e21b7
BC
256 get_be32(pb); // version + flags
257 entries = get_be32(pb);
258 if (entries >= UINT_MAX / sizeof(*sc->drefs))
259 return -1;
221e21b7 260 sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
0d8f0abf
BC
261 if (!sc->drefs)
262 return AVERROR(ENOMEM);
263 sc->drefs_count = entries;
221e21b7
BC
264
265 for (i = 0; i < sc->drefs_count; i++) {
c3e92a6c 266 MOVDref *dref = &sc->drefs[i];
221e21b7 267 uint32_t size = get_be32(pb);
bc5c918e 268 int64_t next = url_ftell(pb) + size - 4;
221e21b7
BC
269
270 dref->type = get_le32(pb);
271 get_be32(pb); // version + flags
272 dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
273
274 if (dref->type == MKTAG('a','l','i','s') && size > 150) {
275 /* macintosh alias record */
276 uint16_t volume_len, len;
277 char volume[28];
278 int16_t type;
279
280 url_fskip(pb, 10);
281
282 volume_len = get_byte(pb);
283 volume_len = FFMIN(volume_len, 27);
284 get_buffer(pb, volume, 27);
285 volume[volume_len] = 0;
286 av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
287
288 url_fskip(pb, 112);
289
290 for (type = 0; type != -1 && url_ftell(pb) < next; ) {
291 type = get_be16(pb);
292 len = get_be16(pb);
293 av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
294 if (len&1)
295 len += 1;
296 if (type == 2) { // absolute path
dbb37657 297 av_free(dref->path);
221e21b7 298 dref->path = av_mallocz(len+1);
2f4568e5
BC
299 if (!dref->path)
300 return AVERROR(ENOMEM);
221e21b7 301 get_buffer(pb, dref->path, len);
dbb7cbf2 302 if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
221e21b7
BC
303 len -= volume_len;
304 memmove(dref->path, dref->path+volume_len, len);
305 dref->path[len] = 0;
306 }
307 for (j = 0; j < len; j++)
308 if (dref->path[j] == ':')
309 dref->path[j] = '/';
310 av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
311 } else
312 url_fskip(pb, len);
313 }
314 }
315 url_fseek(pb, next, SEEK_SET);
316 }
317 return 0;
318}
319
c3e92a6c 320static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
6cea494e 321{
fefe43ff 322 AVStream *st;
0c1a9eda 323 uint32_t type;
0c1a9eda 324 uint32_t ctype;
b6a17df4 325
fefe43ff
AC
326 if (c->fc->nb_streams < 1) // meta before first trak
327 return 0;
328
329 st = c->fc->streams[c->fc->nb_streams-1];
330
6cea494e 331 get_byte(pb); /* version */
23f08617 332 get_be24(pb); /* flags */
6cea494e
ZK
333
334 /* component type */
335 ctype = get_le32(pb);
336 type = get_le32(pb); /* component subtype */
337
9bf1b268
BC
338 dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
339 dprintf(c->fc, "stype= %.4s\n", (char*)&type);
2229a5c6 340
37ffe34b 341 if (type == MKTAG('v','i','d','e'))
73920f07 342 st->codec->codec_type = CODEC_TYPE_VIDEO;
1c126b4f 343 else if(type == MKTAG('s','o','u','n'))
73920f07 344 st->codec->codec_type = CODEC_TYPE_AUDIO;
1c126b4f 345 else if(type == MKTAG('m','1','a',' '))
95a07973 346 st->codec->codec_id = CODEC_ID_MP2;
f05783c2 347 else if(type == MKTAG('s','u','b','p'))
8cb97693 348 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
f05783c2 349
6cea494e
ZK
350 get_be32(pb); /* component manufacture */
351 get_be32(pb); /* component flags */
352 get_be32(pb); /* component flags mask */
353
5ca1d879 354 if(atom.size <= 24)
6cea494e 355 return 0; /* nothing left to read */
5cd62665 356
3c13647a 357 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
6cea494e
ZK
358 return 0;
359}
360
2d423666 361int ff_mp4_read_descr_len(ByteIOContext *pb)
0e7eed09 362{
5cd62665 363 int len = 0;
5ca1d879
ZK
364 int count = 4;
365 while (count--) {
5cd62665 366 int c = get_byte(pb);
bb270c08
DB
367 len = (len << 7) | (c & 0x7f);
368 if (!(c & 0x80))
369 break;
0e7eed09
FB
370 }
371 return len;
372}
373
2d423666 374int mp4_read_descr(AVFormatContext *fc, ByteIOContext *pb, int *tag)
0e7eed09
FB
375{
376 int len;
377 *tag = get_byte(pb);
2d423666
PR
378 len = ff_mp4_read_descr_len(pb);
379 dprintf(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
0e7eed09
FB
380 return len;
381}
382
0b07ac42
BC
383#define MP4ESDescrTag 0x03
384#define MP4DecConfigDescrTag 0x04
385#define MP4DecSpecificDescrTag 0x05
386
1dec3994 387static const AVCodecTag mp4_audio_types[] = {
5c3d507f
AC
388 { CODEC_ID_MP3ON4, AOT_PS }, /* old mp3on4 draft */
389 { CODEC_ID_MP3ON4, AOT_L1 }, /* layer 1 */
390 { CODEC_ID_MP3ON4, AOT_L2 }, /* layer 2 */
391 { CODEC_ID_MP3ON4, AOT_L3 }, /* layer 3 */
b24bbbb4 392 { CODEC_ID_MP4ALS, AOT_ALS }, /* MPEG-4 ALS */
5c3d507f 393 { CODEC_ID_NONE, AOT_NULL },
1dec3994
BC
394};
395
2d423666 396int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)
5cd62665 397{
6a63ff19 398 AVStream *st;
5cd62665 399 int tag, len;
b6a17df4 400
2d423666 401 if (fc->nb_streams < 1)
6a63ff19 402 return 0;
2d423666 403 st = fc->streams[fc->nb_streams-1];
6a63ff19 404
5cd62665 405 get_be32(pb); /* version + flags */
2d423666 406 len = mp4_read_descr(fc, pb, &tag);
5cd62665 407 if (tag == MP4ESDescrTag) {
bb270c08
DB
408 get_be16(pb); /* ID */
409 get_byte(pb); /* priority */
5cd62665 410 } else
bb270c08 411 get_be16(pb); /* ID */
5cd62665 412
2d423666 413 len = mp4_read_descr(fc, pb, &tag);
5cd62665 414 if (tag == MP4DecConfigDescrTag) {
0b07ac42
BC
415 int object_type_id = get_byte(pb);
416 get_byte(pb); /* stream type */
417 get_be24(pb); /* buffer size db */
418 get_be32(pb); /* max bitrate */
419 get_be32(pb); /* avg bitrate */
420
1a40491e 421 st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
ba278391 422 dprintf(fc, "esds object type id 0x%02x\n", object_type_id);
2d423666 423 len = mp4_read_descr(fc, pb, &tag);
bb270c08 424 if (tag == MP4DecSpecificDescrTag) {
2d423666 425 dprintf(fc, "Specific MPEG4 header len=%d\n", len);
852859ff
BC
426 if((uint64_t)len > (1<<30))
427 return -1;
9a630c25 428 st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
b014dd76
BC
429 if (!st->codec->extradata)
430 return AVERROR(ENOMEM);
17871a02
BC
431 get_buffer(pb, st->codec->extradata, len);
432 st->codec->extradata_size = len;
1dec3994
BC
433 if (st->codec->codec_id == CODEC_ID_AAC) {
434 MPEG4AudioConfig cfg;
435 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
436 st->codec->extradata_size);
5aea268d 437 st->codec->channels = cfg.channels;
45a97d30
BC
438 if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
439 st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
440 else
441 st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
2d423666 442 dprintf(fc, "mp4a config channels %d obj %d ext obj %d "
45a97d30
BC
443 "sample rate %d ext sample rate %d\n", st->codec->channels,
444 cfg.object_type, cfg.ext_object_type,
445 cfg.sample_rate, cfg.ext_sample_rate);
1a40491e
DV
446 if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
447 cfg.object_type)))
1dec3994 448 st->codec->codec_id = CODEC_ID_AAC;
17871a02 449 }
bb270c08 450 }
5cd62665 451 }
5cd62665
ZK
452 return 0;
453}
454
2d423666
PR
455static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
456{
457 return ff_mov_read_esds(c->fc, pb, atom);
458}
459
6da54074
BC
460static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
461{
462 const int num = get_be32(pb);
463 const int den = get_be32(pb);
6a63ff19
BC
464 AVStream *st;
465
466 if (c->fc->nb_streams < 1)
467 return 0;
468 st = c->fc->streams[c->fc->nb_streams-1];
469
6da54074 470 if (den != 0) {
f53ee312
BC
471 if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
472 (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
6da54074 473 av_log(c->fc, AV_LOG_WARNING,
f53ee312
BC
474 "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
475 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
6da54074
BC
476 st->sample_aspect_ratio.num = num;
477 st->sample_aspect_ratio.den = den;
478 }
479 return 0;
480}
481
5ca1d879 482/* this atom contains actual media data */
c3e92a6c 483static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
6cea494e 484{
5ca1d879
ZK
485 if(atom.size == 0) /* wrong one (MP4) */
486 return 0;
487 c->found_mdat=1;
5ca1d879
ZK
488 return 0; /* now go for moov */
489}
490
7b5252ce 491/* read major brand, minor version and compatible brands and store them as metadata */
c3e92a6c 492static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
4ea28253 493{
7b5252ce 494 uint32_t minor_ver;
495 int comp_brand_size;
496 char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
497 char* comp_brands_str;
498 uint8_t type[5] = {0};
499
500 get_buffer(pb, type, 4);
a42bf191 501 if (strcmp(type, "qt "))
152e9a43 502 c->isom = 1;
a512446e 503 av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
7b5252ce 504 av_metadata_set(&c->fc->metadata, "major_brand", type);
505 minor_ver = get_be32(pb); /* minor version */
506 snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
507 av_metadata_set(&c->fc->metadata, "minor_version", minor_ver_str);
508
509 comp_brand_size = atom.size - 8;
510 if (comp_brand_size < 0)
511 return -1;
512 comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
513 if (!comp_brands_str)
514 return AVERROR(ENOMEM);
515 get_buffer(pb, comp_brands_str, comp_brand_size);
516 comp_brands_str[comp_brand_size] = 0;
517 av_metadata_set(&c->fc->metadata, "compatible_brands", comp_brands_str);
518 av_freep(&comp_brands_str);
519
4ea28253
BC
520 return 0;
521}
522
5ca1d879 523/* this atom should contain all header atoms */
c3e92a6c 524static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 525{
9cf0419b
PI
526 if (mov_read_default(c, pb, atom) < 0)
527 return -1;
5ca1d879
ZK
528 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
529 /* so we don't parse the whole file if over a network */
530 c->found_moov=1;
5ca1d879
ZK
531 return 0; /* now go for mdat */
532}
533
c3e92a6c 534static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
61aedb0f
BC
535{
536 c->fragment.moof_offset = url_ftell(pb) - 8;
537 dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
538 return mov_read_default(c, pb, atom);
539}
5ca1d879 540
c3e92a6c 541static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 542{
6a63ff19
BC
543 AVStream *st;
544 MOVStreamContext *sc;
545 int version;
49674dd0 546 char language[4] = {0};
dce25564 547 unsigned lang;
5ca1d879 548
6a63ff19
BC
549 if (c->fc->nb_streams < 1)
550 return 0;
551 st = c->fc->streams[c->fc->nb_streams-1];
552 sc = st->priv_data;
553
554 version = get_byte(pb);
b9a87c4d 555 if (version > 1)
7e627332 556 return -1; /* unsupported */
5ca1d879 557
23f08617 558 get_be24(pb); /* flags */
f444b977
BC
559 if (version == 1) {
560 get_be64(pb);
561 get_be64(pb);
562 } else {
563 get_be32(pb); /* creation time */
564 get_be32(pb); /* modification time */
565 }
5ca1d879 566
f444b977
BC
567 sc->time_scale = get_be32(pb);
568 st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
5ca1d879 569
b9a87c4d 570 lang = get_be16(pb); /* language */
49674dd0
AJ
571 if (ff_mov_lang_to_iso639(lang, language))
572 av_metadata_set(&st->metadata, "language", language);
5ca1d879
ZK
573 get_be16(pb); /* quality */
574
575 return 0;
576}
577
c3e92a6c 578static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 579{
1175561e 580 int version = get_byte(pb); /* version */
23f08617 581 get_be24(pb); /* flags */
5ca1d879 582
1175561e
BC
583 if (version == 1) {
584 get_be64(pb);
585 get_be64(pb);
586 } else {
587 get_be32(pb); /* creation time */
588 get_be32(pb); /* modification time */
589 }
5ca1d879 590 c->time_scale = get_be32(pb); /* time scale */
f8c18cd7
BC
591
592 dprintf(c->fc, "time scale = %i\n", c->time_scale);
593
1175561e 594 c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
5ca1d879
ZK
595 get_be32(pb); /* preferred scale */
596
597 get_be16(pb); /* preferred volume */
598
599 url_fskip(pb, 10); /* reserved */
600
601 url_fskip(pb, 36); /* display matrix */
602
603 get_be32(pb); /* preview time */
604 get_be32(pb); /* preview duration */
605 get_be32(pb); /* poster time */
606 get_be32(pb); /* selection time */
607 get_be32(pb); /* selection duration */
608 get_be32(pb); /* current time */
609 get_be32(pb); /* next track ID */
610
611 return 0;
612}
613
c3e92a6c 614static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
9ed83b0a 615{
6a63ff19
BC
616 AVStream *st;
617
618 if (c->fc->nb_streams < 1)
619 return 0;
620 st = c->fc->streams[c->fc->nb_streams-1];
9ed83b0a 621
568e18b1
MN
622 if((uint64_t)atom.size > (1<<30))
623 return -1;
115329f1 624
9ed83b0a
ZK
625 // currently SVQ3 decoder expect full STSD header - so let's fake it
626 // this should be fixed and just SMI header should be passed
01f4895c 627 av_free(st->codec->extradata);
b014dd76
BC
628 st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
629 if (!st->codec->extradata)
630 return AVERROR(ENOMEM);
17871a02
BC
631 st->codec->extradata_size = 0x5a + atom.size;
632 memcpy(st->codec->extradata, "SVQ3", 4); // fake
633 get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
634 dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
9ed83b0a
ZK
635 return 0;
636}
5ca1d879 637
c3e92a6c 638static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
de23f234 639{
6a63ff19
BC
640 AVStream *st;
641 int little_endian;
642
643 if (c->fc->nb_streams < 1)
644 return 0;
645 st = c->fc->streams[c->fc->nb_streams-1];
de23f234 646
6a63ff19 647 little_endian = get_be16(pb);
fa50a027
BC
648 dprintf(c->fc, "enda %d\n", little_endian);
649 if (little_endian == 1) {
de23f234
BC
650 switch (st->codec->codec_id) {
651 case CODEC_ID_PCM_S24BE:
652 st->codec->codec_id = CODEC_ID_PCM_S24LE;
653 break;
654 case CODEC_ID_PCM_S32BE:
655 st->codec->codec_id = CODEC_ID_PCM_S32LE;
656 break;
a1ef2c4b
PR
657 case CODEC_ID_PCM_F32BE:
658 st->codec->codec_id = CODEC_ID_PCM_F32LE;
659 break;
660 case CODEC_ID_PCM_F64BE:
661 st->codec->codec_id = CODEC_ID_PCM_F64LE;
662 break;
de23f234
BC
663 default:
664 break;
665 }
666 }
667 return 0;
668}
669
014a5102 670/* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
c3e92a6c 671static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
de23f234 672{
27134437
BC
673 AVStream *st;
674 uint64_t size;
68bc33fa 675 uint8_t *buf;
27134437
BC
676
677 if (c->fc->nb_streams < 1) // will happen with jp2 files
678 return 0;
679 st= c->fc->streams[c->fc->nb_streams-1];
680 size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
68bc33fa 681 if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
014a5102 682 return -1;
68bc33fa
BC
683 buf= av_realloc(st->codec->extradata, size);
684 if(!buf)
685 return -1;
686 st->codec->extradata= buf;
687 buf+= st->codec->extradata_size;
688 st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
689 AV_WB32( buf , atom.size + 8);
690 AV_WL32( buf + 4, atom.type);
691 get_buffer(pb, buf + 8, atom.size);
de23f234
BC
692 return 0;
693}
694
c3e92a6c 695static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
d9b1c197 696{
6a63ff19
BC
697 AVStream *st;
698
699 if (c->fc->nb_streams < 1)
700 return 0;
701 st = c->fc->streams[c->fc->nb_streams-1];
d9b1c197
RT
702
703 if((uint64_t)atom.size > (1<<30))
704 return -1;
115329f1 705
3840147e
MN
706 if (st->codec->codec_id == CODEC_ID_QDM2) {
707 // pass all frma atom to codec, needed at least for QDM2
708 av_free(st->codec->extradata);
b014dd76
BC
709 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
710 if (!st->codec->extradata)
711 return AVERROR(ENOMEM);
3840147e 712 st->codec->extradata_size = atom.size;
b014dd76 713 get_buffer(pb, st->codec->extradata, atom.size);
3840147e 714 } else if (atom.size > 8) { /* to read frma, esds atoms */
9cf0419b
PI
715 if (mov_read_default(c, pb, atom) < 0)
716 return -1;
5c72cad8 717 } else
bb270c08 718 url_fskip(pb, atom.size);
d9b1c197
RT
719 return 0;
720}
721
bde24601
BC
722/**
723 * This function reads atom content and puts data in extradata without tag
724 * nor size unlike mov_read_extradata.
725 */
c3e92a6c 726static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
169eb021 727{
6a63ff19
BC
728 AVStream *st;
729
730 if (c->fc->nb_streams < 1)
731 return 0;
732 st = c->fc->streams[c->fc->nb_streams-1];
169eb021 733
568e18b1
MN
734 if((uint64_t)atom.size > (1<<30))
735 return -1;
736
01f4895c 737 av_free(st->codec->extradata);
b014dd76
BC
738 st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
739 if (!st->codec->extradata)
740 return AVERROR(ENOMEM);
01f4895c 741 st->codec->extradata_size = atom.size;
b014dd76 742 get_buffer(pb, st->codec->extradata, atom.size);
169eb021
MM
743 return 0;
744}
745
c3e92a6c 746static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 747{
6a63ff19
BC
748 AVStream *st;
749 MOVStreamContext *sc;
568e18b1 750 unsigned int i, entries;
5ca1d879 751
6a63ff19
BC
752 if (c->fc->nb_streams < 1)
753 return 0;
754 st = c->fc->streams[c->fc->nb_streams-1];
755 sc = st->priv_data;
756
5ca1d879 757 get_byte(pb); /* version */
23f08617 758 get_be24(pb); /* flags */
5ca1d879
ZK
759
760 entries = get_be32(pb);
115329f1 761
568e18b1
MN
762 if(entries >= UINT_MAX/sizeof(int64_t))
763 return -1;
115329f1 764
9a630c25 765 sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
5ca1d879 766 if (!sc->chunk_offsets)
0d8f0abf
BC
767 return AVERROR(ENOMEM);
768 sc->chunk_count = entries;
769
37ffe34b
BC
770 if (atom.type == MKTAG('s','t','c','o'))
771 for(i=0; i<entries; i++)
5ca1d879 772 sc->chunk_offsets[i] = get_be32(pb);
37ffe34b
BC
773 else if (atom.type == MKTAG('c','o','6','4'))
774 for(i=0; i<entries; i++)
5ca1d879 775 sc->chunk_offsets[i] = get_be64(pb);
37ffe34b 776 else
5ca1d879 777 return -1;
115329f1 778
5ca1d879
ZK
779 return 0;
780}
781
2288834f
BC
782/**
783 * Compute codec id for 'lpcm' tag.
784 * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
785 */
2d423666 786enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
2288834f
BC
787{
788 if (flags & 1) { // floating point
789 if (flags & 2) { // big endian
790 if (bps == 32) return CODEC_ID_PCM_F32BE;
7e4b3fb8 791 else if (bps == 64) return CODEC_ID_PCM_F64BE;
2288834f 792 } else {
7e4b3fb8
BC
793 if (bps == 32) return CODEC_ID_PCM_F32LE;
794 else if (bps == 64) return CODEC_ID_PCM_F64LE;
2288834f
BC
795 }
796 } else {
797 if (flags & 2) {
798 if (bps == 8)
799 // signed integer
800 if (flags & 4) return CODEC_ID_PCM_S8;
801 else return CODEC_ID_PCM_U8;
802 else if (bps == 16) return CODEC_ID_PCM_S16BE;
803 else if (bps == 24) return CODEC_ID_PCM_S24BE;
804 else if (bps == 32) return CODEC_ID_PCM_S32BE;
805 } else {
806 if (bps == 8)
807 if (flags & 4) return CODEC_ID_PCM_S8;
808 else return CODEC_ID_PCM_U8;
021b8ae3 809 else if (bps == 16) return CODEC_ID_PCM_S16LE;
2288834f
BC
810 else if (bps == 24) return CODEC_ID_PCM_S24LE;
811 else if (bps == 32) return CODEC_ID_PCM_S32LE;
812 }
813 }
fb65d2ca 814 return CODEC_ID_NONE;
2288834f
BC
815}
816
c3e92a6c 817static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 818{
6a63ff19
BC
819 AVStream *st;
820 MOVStreamContext *sc;
baf9fb32 821 int j, entries, pseudo_stream_id;
b595afaa 822
6a63ff19
BC
823 if (c->fc->nb_streams < 1)
824 return 0;
825 st = c->fc->streams[c->fc->nb_streams-1];
826 sc = st->priv_data;
827
6cea494e 828 get_byte(pb); /* version */
23f08617 829 get_be24(pb); /* flags */
6cea494e 830
6cea494e
ZK
831 entries = get_be32(pb);
832
117a9190
BC
833 for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
834 //Parsing Sample description table
b6a17df4 835 enum CodecID id;
28155113 836 int dref_id = 1;
c3e92a6c 837 MOVAtom a = { 0, 0, 0 };
bc5c918e 838 int64_t start_pos = url_ftell(pb);
bb270c08 839 int size = get_be32(pb); /* size */
baf9fb32 840 uint32_t format = get_le32(pb); /* data format */
5cd62665 841
28155113
BC
842 if (size >= 16) {
843 get_be32(pb); /* reserved */
844 get_be16(pb); /* reserved */
845 dref_id = get_be16(pb);
846 }
0e7eed09 847
744a9c75 848 if (st->codec->codec_tag &&
978677a7 849 st->codec->codec_tag != format &&
1a40491e 850 (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
1c126b4f 851 : st->codec->codec_tag != MKTAG('j','p','e','g'))
744a9c75 852 ){
7ce68923
DB
853 /* Multiple fourcc, we skip JPEG. This is not correct, we should
854 * export it as a separate AVStream but this needs a few changes
855 * in the MOV demuxer, patch welcome. */
285a3da9 856 av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
e7cc4b52
BC
857 url_fskip(pb, size - (url_ftell(pb) - start_pos));
858 continue;
859 }
978677a7 860 sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
221e21b7 861 sc->dref_id= dref_id;
e7cc4b52 862
bb270c08 863 st->codec->codec_tag = format;
1a40491e 864 id = ff_codec_get_id(codec_movaudio_tags, format);
86b61d42 865 if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
1a40491e 866 id = ff_codec_get_id(ff_codec_wav_tags, bswap_32(format)&0xFFFF);
bca7db35 867
48855b26 868 if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
99487f42 869 st->codec->codec_type = CODEC_TYPE_AUDIO;
48855b26 870 } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
1c126b4f 871 format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
1a40491e 872 id = ff_codec_get_id(codec_movvideo_tags, format);
99487f42 873 if (id <= 0)
1a40491e 874 id = ff_codec_get_id(ff_codec_bmp_tags, format);
99487f42
BC
875 if (id > 0)
876 st->codec->codec_type = CODEC_TYPE_VIDEO;
1e3c9307 877 else if(st->codec->codec_type == CODEC_TYPE_DATA){
1a40491e 878 id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
1e3c9307
MN
879 if(id > 0)
880 st->codec->codec_type = CODEC_TYPE_SUBTITLE;
881 }
99487f42
BC
882 }
883
29c90869
BC
884 dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
885 (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
886 (format >> 24) & 0xff, st->codec->codec_type);
a20da52c 887
99487f42 888 if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
baf9fb32
BC
889 uint8_t codec_name[32];
890 unsigned int color_depth;
891 int color_greyscale;
baf9fb32 892
01f4895c 893 st->codec->codec_id = id;
6cea494e
ZK
894 get_be16(pb); /* version */
895 get_be16(pb); /* revision level */
896 get_be32(pb); /* vendor */
897 get_be32(pb); /* temporal quality */
94472c1d 898 get_be32(pb); /* spatial quality */
3cb4ee51
BC
899
900 st->codec->width = get_be16(pb); /* width */
901 st->codec->height = get_be16(pb); /* height */
902
6cea494e
ZK
903 get_be32(pb); /* horiz resolution */
904 get_be32(pb); /* vert resolution */
905 get_be32(pb); /* data size, always 0 */
43612ffe 906 get_be16(pb); /* frames per samples */
f8c18cd7 907
eb034aca 908 get_buffer(pb, codec_name, 32); /* codec name, pascal string */
576f1445 909 if (codec_name[0] <= 31) {
19635234
RD
910 int i;
911 int pos = 0;
912 for (i = 0; i < codec_name[0] && pos < sizeof(st->codec->codec_name) - 3; i++) {
913 uint8_t tmp;
f2ad9070 914 PUT_UTF8(codec_name[i+1], tmp, st->codec->codec_name[pos++] = tmp;)
19635234
RD
915 }
916 st->codec->codec_name[pos] = 0;
576f1445 917 }
5cd62665 918
dd1c8f3e 919 st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
01f4895c 920 st->codec->color_table_id = get_be16(pb); /* colortable id */
0de2157f 921 dprintf(c->fc, "depth %d, ctab id %d\n",
dd1c8f3e 922 st->codec->bits_per_coded_sample, st->codec->color_table_id);
b595afaa 923 /* figure out the palette situation */
dd1c8f3e
LA
924 color_depth = st->codec->bits_per_coded_sample & 0x1F;
925 color_greyscale = st->codec->bits_per_coded_sample & 0x20;
b595afaa
MM
926
927 /* if the depth is 2, 4, or 8 bpp, file is palettized */
115329f1 928 if ((color_depth == 2) || (color_depth == 4) ||
b595afaa 929 (color_depth == 8)) {
47e1d7ef
BC
930 /* for palette traversal */
931 unsigned int color_start, color_count, color_end;
932 unsigned char r, g, b;
933
e49da827 934 st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
b595afaa 935 if (color_greyscale) {
47e1d7ef 936 int color_index, color_dec;
b595afaa 937 /* compute the greyscale palette */
dd1c8f3e 938 st->codec->bits_per_coded_sample = color_depth;
b595afaa
MM
939 color_count = 1 << color_depth;
940 color_index = 255;
941 color_dec = 256 / (color_count - 1);
942 for (j = 0; j < color_count; j++) {
943 r = g = b = color_index;
e49da827 944 st->codec->palctrl->palette[j] =
b595afaa
MM
945 (r << 16) | (g << 8) | (b);
946 color_index -= color_dec;
947 if (color_index < 0)
948 color_index = 0;
949 }
71f36235 950 } else if (st->codec->color_table_id) {
47e1d7ef 951 const uint8_t *color_table;
b595afaa
MM
952 /* if flag bit 3 is set, use the default palette */
953 color_count = 1 << color_depth;
954 if (color_depth == 2)
a90466f7 955 color_table = ff_qt_default_palette_4;
b595afaa 956 else if (color_depth == 4)
a90466f7 957 color_table = ff_qt_default_palette_16;
b595afaa 958 else
a90466f7 959 color_table = ff_qt_default_palette_256;
b595afaa
MM
960
961 for (j = 0; j < color_count; j++) {
2121b160
RB
962 r = color_table[j * 3 + 0];
963 g = color_table[j * 3 + 1];
964 b = color_table[j * 3 + 2];
e49da827 965 st->codec->palctrl->palette[j] =
b595afaa
MM
966 (r << 16) | (g << 8) | (b);
967 }
b595afaa 968 } else {
b595afaa
MM
969 /* load the palette from the file */
970 color_start = get_be32(pb);
971 color_count = get_be16(pb);
972 color_end = get_be16(pb);
8b35bd80
MM
973 if ((color_start <= 255) &&
974 (color_end <= 255)) {
9de2919c
MM
975 for (j = color_start; j <= color_end; j++) {
976 /* each R, G, or B component is 16 bits;
977 * only use the top 8 bits; skip alpha bytes
978 * up front */
979 get_byte(pb);
980 get_byte(pb);
981 r = get_byte(pb);
982 get_byte(pb);
983 g = get_byte(pb);
984 get_byte(pb);
985 b = get_byte(pb);
986 get_byte(pb);
e49da827 987 st->codec->palctrl->palette[j] =
9de2919c 988 (r << 16) | (g << 8) | (b);
8b35bd80 989 }
b595afaa
MM
990 }
991 }
01f4895c 992 st->codec->palctrl->palette_changed = 1;
e49da827 993 }
de23f234 994 } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
aaef2bb3 995 int bits_per_sample, flags;
de23f234 996 uint16_t version = get_be16(pb);
b595afaa 997
99487f42 998 st->codec->codec_id = id;
de23f234
BC
999 get_be16(pb); /* revision level */
1000 get_be32(pb); /* vendor */
6d6d7970 1001
de23f234 1002 st->codec->channels = get_be16(pb); /* channel count */
318c5e05 1003 dprintf(c->fc, "audio channels %d\n", st->codec->channels);
dd1c8f3e 1004 st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
de23f234 1005
77c75437 1006 sc->audio_cid = get_be16(pb);
de23f234
BC
1007 get_be16(pb); /* packet size = 0 */
1008
1009 st->codec->sample_rate = ((get_be32(pb) >> 16));
1010
5ef3ad59
BC
1011 //Read QT version 1 fields. In version 0 these do not exist.
1012 dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
1013 if(!c->isom) {
1014 if(version==1) {
1015 sc->samples_per_frame = get_be32(pb);
1016 get_be32(pb); /* bytes per packet */
1017 sc->bytes_per_frame = get_be32(pb);
1018 get_be32(pb); /* bytes per sample */
1019 } else if(version==2) {
1020 get_be32(pb); /* sizeof struct only */
1021 st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
1022 st->codec->channels = get_be32(pb);
1023 get_be32(pb); /* always 0x7F000000 */
dd1c8f3e 1024 st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
aaef2bb3 1025 flags = get_be32(pb); /* lcpm format specific flag */
9184d53a
BC
1026 sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
1027 sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
2288834f 1028 if (format == MKTAG('l','p','c','m'))
2d423666 1029 st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
5ef3ad59
BC
1030 }
1031 }
1032
de23f234 1033 switch (st->codec->codec_id) {
b72708f8
BC
1034 case CODEC_ID_PCM_S8:
1035 case CODEC_ID_PCM_U8:
dd1c8f3e 1036 if (st->codec->bits_per_coded_sample == 16)
b72708f8
BC
1037 st->codec->codec_id = CODEC_ID_PCM_S16BE;
1038 break;
0dd39bfe 1039 case CODEC_ID_PCM_S16LE:
de23f234 1040 case CODEC_ID_PCM_S16BE:
dd1c8f3e 1041 if (st->codec->bits_per_coded_sample == 8)
de23f234 1042 st->codec->codec_id = CODEC_ID_PCM_S8;
dd1c8f3e 1043 else if (st->codec->bits_per_coded_sample == 24)
6b477e1b
BC
1044 st->codec->codec_id =
1045 st->codec->codec_id == CODEC_ID_PCM_S16BE ?
1046 CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
de23f234 1047 break;
53152765
BC
1048 /* set values for old format before stsd version 1 appeared */
1049 case CODEC_ID_MACE3:
1050 sc->samples_per_frame = 6;
1051 sc->bytes_per_frame = 2*st->codec->channels;
1052 break;
1053 case CODEC_ID_MACE6:
1054 sc->samples_per_frame = 6;
1055 sc->bytes_per_frame = 1*st->codec->channels;
1056 break;
1057 case CODEC_ID_ADPCM_IMA_QT:
1058 sc->samples_per_frame = 64;
1059 sc->bytes_per_frame = 34*st->codec->channels;
1060 break;
cc326d2b
BC
1061 case CODEC_ID_GSM:
1062 sc->samples_per_frame = 160;
1063 sc->bytes_per_frame = 33;
1064 break;
de23f234
BC
1065 default:
1066 break;
6d6d7970 1067 }
14342fd5 1068
9770089d
BC
1069 bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
1070 if (bits_per_sample) {
dd1c8f3e 1071 st->codec->bits_per_coded_sample = bits_per_sample;
9770089d
BC
1072 sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
1073 }
cc8d87b7 1074 } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
58e9f2ed
DC
1075 // ttxt stsd contains display flags, justification, background
1076 // color, fonts, and default styles, so fake an atom to read it
1077 MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
fb9ac654 1078 if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
3dd36041 1079 mov_read_glbl(c, pb, fake_atom);
cc8d87b7 1080 st->codec->codec_id= id;
6cdbff63
DC
1081 st->codec->width = sc->width;
1082 st->codec->height = sc->height;
de23f234
BC
1083 } else {
1084 /* other codec type, just skip (rtp, mp4s, tmcd ...) */
1085 url_fskip(pb, size - (url_ftell(pb) - start_pos));
6cea494e 1086 }
de23f234
BC
1087 /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
1088 a.size = size - (url_ftell(pb) - start_pos);
9cf0419b
PI
1089 if (a.size > 8) {
1090 if (mov_read_default(c, pb, a) < 0)
1091 return -1;
1092 } else if (a.size > 0)
de23f234 1093 url_fskip(pb, a.size);
6cea494e 1094 }
115329f1 1095
60f5c96e 1096 if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
302c389e 1097 st->codec->sample_rate= sc->time_scale;
e31bd3e3 1098
d00f8e17 1099 /* special codec parameters handling */
e31bd3e3 1100 switch (st->codec->codec_id) {
b250f9c6 1101#if CONFIG_DV_DEMUXER
b60c0454 1102 case CODEC_ID_DVAUDIO:
8e2fd8e1 1103 c->dv_fctx = avformat_alloc_context();
b60c0454
BC
1104 c->dv_demux = dv_init_demux(c->dv_fctx);
1105 if (!c->dv_demux) {
1106 av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
1107 return -1;
1108 }
1109 sc->dv_audio_container = 1;
1110 st->codec->codec_id = CODEC_ID_PCM_S16LE;
1111 break;
989ac5a6 1112#endif
b95319a2 1113 /* no ifdef since parameters are always those */
3f78a3a9 1114 case CODEC_ID_QCELP:
17ad7b24
BC
1115 // force sample rate for qcelp when not stored in mov
1116 if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
1117 st->codec->sample_rate = 8000;
73b458e3 1118 st->codec->frame_size= 160;
061f407e 1119 st->codec->channels= 1; /* really needed */
73b458e3 1120 break;
b95319a2 1121 case CODEC_ID_AMR_NB:
aeb62788 1122 case CODEC_ID_AMR_WB:
cfb5a2ab 1123 st->codec->frame_size= sc->samples_per_frame;
b95319a2 1124 st->codec->channels= 1; /* really needed */
f06188d5 1125 /* force sample rate for amr, stsd in 3gp does not store sample rate */
5b9ce252 1126 if (st->codec->codec_id == CODEC_ID_AMR_NB)
f06188d5 1127 st->codec->sample_rate = 8000;
5b9ce252
BC
1128 else if (st->codec->codec_id == CODEC_ID_AMR_WB)
1129 st->codec->sample_rate = 16000;
b95319a2 1130 break;
a41104f8 1131 case CODEC_ID_MP2:
c59f24e6 1132 case CODEC_ID_MP3:
95a07973 1133 st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
57004ff1 1134 st->need_parsing = AVSTREAM_PARSE_FULL;
a41104f8 1135 break;
5610f20e 1136 case CODEC_ID_GSM:
74e9b9ae
BC
1137 case CODEC_ID_ADPCM_MS:
1138 case CODEC_ID_ADPCM_IMA_WAV:
1139 st->codec->block_align = sc->bytes_per_frame;
1140 break;
be511925 1141 case CODEC_ID_ALAC:
a1532824 1142 if (st->codec->extradata_size == 36) {
364df7b7
BC
1143 st->codec->frame_size = AV_RB32(st->codec->extradata+12);
1144 st->codec->channels = AV_RB8 (st->codec->extradata+21);
a1532824 1145 }
be511925 1146 break;
e31bd3e3
BC
1147 default:
1148 break;
1149 }
5cd62665 1150
6cea494e
ZK
1151 return 0;
1152}
1153
c3e92a6c 1154static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
6cea494e 1155{
6a63ff19
BC
1156 AVStream *st;
1157 MOVStreamContext *sc;
568e18b1 1158 unsigned int i, entries;
b6a17df4 1159
6a63ff19
BC
1160 if (c->fc->nb_streams < 1)
1161 return 0;
1162 st = c->fc->streams[c->fc->nb_streams-1];
1163 sc = st->priv_data;
1164
6cea494e 1165 get_byte(pb); /* version */
23f08617 1166 get_be24(pb); /* flags */
6cea494e
ZK
1167
1168 entries = get_be32(pb);
115329f1 1169
f8c18cd7
BC
1170 dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1171
0d8f0abf
BC
1172 if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
1173 return -1;
04e06cfa
BC
1174 sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
1175 if (!sc->stsc_data)
0d8f0abf
BC
1176 return AVERROR(ENOMEM);
1177 sc->stsc_count = entries;
1178
6cea494e 1179 for(i=0; i<entries; i++) {
04e06cfa
BC
1180 sc->stsc_data[i].first = get_be32(pb);
1181 sc->stsc_data[i].count = get_be32(pb);
1182 sc->stsc_data[i].id = get_be32(pb);
6cea494e
ZK
1183 }
1184 return 0;
1185}
1186
171a3531
BC
1187static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
1188{
1189 AVStream *st;
1190 MOVStreamContext *sc;
1191 unsigned i, entries;
1192
1193 if (c->fc->nb_streams < 1)
1194 return 0;
1195 st = c->fc->streams[c->fc->nb_streams-1];
1196 sc = st->priv_data;
1197
1198 get_be32(pb); // version + flags
1199
1200 entries = get_be32(pb);
1201 if (entries >= UINT_MAX / sizeof(*sc->stps_data))
1202 return -1;
1203 sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
1204 if (!sc->stps_data)
1205 return AVERROR(ENOMEM);
1206 sc->stps_count = entries;
1207
1208 for (i = 0; i < entries; i++) {
1209 sc->stps_data[i] = get_be32(pb);
1210 //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
1211 }
1212
1213 return 0;
1214}
1215
c3e92a6c 1216static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
247d56f5 1217{
6a63ff19
BC
1218 AVStream *st;
1219 MOVStreamContext *sc;
568e18b1 1220 unsigned int i, entries;
247d56f5 1221
6a63ff19
BC
1222 if (c->fc->nb_streams < 1)
1223 return 0;
1224 st = c->fc->streams[c->fc->nb_streams-1];
1225 sc = st->priv_data;
1226
247d56f5 1227 get_byte(pb); /* version */
23f08617 1228 get_be24(pb); /* flags */
247d56f5
BB
1229
1230 entries = get_be32(pb);
115329f1 1231
0d8f0abf
BC
1232 dprintf(c->fc, "keyframe_count = %d\n", entries);
1233
1c02d96f 1234 if(entries >= UINT_MAX / sizeof(int))
568e18b1 1235 return -1;
1c02d96f 1236 sc->keyframes = av_malloc(entries * sizeof(int));
247d56f5 1237 if (!sc->keyframes)
0d8f0abf
BC
1238 return AVERROR(ENOMEM);
1239 sc->keyframe_count = entries;
1240
247d56f5
BB
1241 for(i=0; i<entries; i++) {
1242 sc->keyframes[i] = get_be32(pb);
f8c18cd7 1243 //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
247d56f5
BB
1244 }
1245 return 0;
1246}
1247
c3e92a6c 1248static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
6cea494e 1249{
6a63ff19
BC
1250 AVStream *st;
1251 MOVStreamContext *sc;
bd27eed6
AC
1252 unsigned int i, entries, sample_size, field_size, num_bytes;
1253 GetBitContext gb;
1254 unsigned char* buf;
b6a17df4 1255
6a63ff19
BC
1256 if (c->fc->nb_streams < 1)
1257 return 0;
1258 st = c->fc->streams[c->fc->nb_streams-1];
1259 sc = st->priv_data;
1260
6cea494e 1261 get_byte(pb); /* version */
23f08617 1262 get_be24(pb); /* flags */
5cd62665 1263
bd27eed6 1264 if (atom.type == MKTAG('s','t','s','z')) {
d0dab0ec
AC
1265 sample_size = get_be32(pb);
1266 if (!sc->sample_size) /* do not overwrite value computed in stsd */
1267 sc->sample_size = sample_size;
1268 field_size = 32;
bd27eed6
AC
1269 } else {
1270 sample_size = 0;
1271 get_be24(pb); /* reserved */
1272 field_size = get_byte(pb);
1273 }
6cea494e 1274 entries = get_be32(pb);
0d8f0abf
BC
1275
1276 dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
568e18b1 1277
6cea494e 1278 sc->sample_count = entries;
b72708f8
BC
1279 if (sample_size)
1280 return 0;
1281
bd27eed6
AC
1282 if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
1283 av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
1284 return -1;
1285 }
1286
e4bc8af1 1287 if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
0d8f0abf 1288 return -1;
1c02d96f 1289 sc->sample_sizes = av_malloc(entries * sizeof(int));
b6a17df4 1290 if (!sc->sample_sizes)
0d8f0abf
BC
1291 return AVERROR(ENOMEM);
1292
bd27eed6
AC
1293 num_bytes = (entries*field_size+4)>>3;
1294
08a5b4e9 1295 buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
bd27eed6
AC
1296 if (!buf) {
1297 av_freep(&sc->sample_sizes);
1298 return AVERROR(ENOMEM);
1299 }
1300
1301 if (get_buffer(pb, buf, num_bytes) < num_bytes) {
1302 av_freep(&sc->sample_sizes);
1303 av_free(buf);
1304 return -1;
1305 }
1306
1307 init_get_bits(&gb, buf, 8*num_bytes);
1308
eb61405a 1309 for(i=0; i<entries; i++)
bd27eed6
AC
1310 sc->sample_sizes[i] = get_bits_long(&gb, field_size);
1311
1312 av_free(buf);
6cea494e
ZK
1313 return 0;
1314}
1315
c3e92a6c 1316static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
0147f198 1317{
6a63ff19
BC
1318 AVStream *st;
1319 MOVStreamContext *sc;
568e18b1 1320 unsigned int i, entries;
d957696f
MN
1321 int64_t duration=0;
1322 int64_t total_sample_count=0;
b6a17df4 1323
6a63ff19
BC
1324 if (c->fc->nb_streams < 1)
1325 return 0;
1326 st = c->fc->streams[c->fc->nb_streams-1];
1327 sc = st->priv_data;
1328
0147f198 1329 get_byte(pb); /* version */
23f08617 1330 get_be24(pb); /* flags */
0147f198 1331 entries = get_be32(pb);
0d8f0abf
BC
1332
1333 dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1334
c3e92a6c 1335 if(entries >= UINT_MAX / sizeof(*sc->stts_data))
568e18b1 1336 return -1;
c3e92a6c 1337 sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
c1da59fa 1338 if (!sc->stts_data)
0d8f0abf
BC
1339 return AVERROR(ENOMEM);
1340 sc->stts_count = entries;
cd7352d5 1341
0147f198 1342 for(i=0; i<entries; i++) {
cd461d48
MN
1343 int sample_duration;
1344 int sample_count;
0147f198 1345
891f64b3 1346 sample_count=get_be32(pb);
0147f198 1347 sample_duration = get_be32(pb);
cd7352d5
MN
1348 sc->stts_data[i].count= sample_count;
1349 sc->stts_data[i].duration= sample_duration;
1350
318c5e05 1351 dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
4e5ef14f 1352
7e815047 1353 duration+=(int64_t)sample_duration*sample_count;
891f64b3 1354 total_sample_count+=sample_count;
891f64b3 1355 }
1356
961e0ccd
MN
1357 st->nb_frames= total_sample_count;
1358 if(duration)
1359 st->duration= duration;
0147f198
FR
1360 return 0;
1361}
1362
c3e92a6c 1363static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
c4ac052b 1364{
6a63ff19
BC
1365 AVStream *st;
1366 MOVStreamContext *sc;
c4ac052b
MN
1367 unsigned int i, entries;
1368
6a63ff19
BC
1369 if (c->fc->nb_streams < 1)
1370 return 0;
1371 st = c->fc->streams[c->fc->nb_streams-1];
1372 sc = st->priv_data;
1373
c4ac052b 1374 get_byte(pb); /* version */
23f08617 1375 get_be24(pb); /* flags */
c4ac052b 1376 entries = get_be32(pb);
0d8f0abf
BC
1377
1378 dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
1379
c3e92a6c 1380 if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
c4ac052b 1381 return -1;
c3e92a6c 1382 sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
c1da59fa 1383 if (!sc->ctts_data)
0d8f0abf
BC
1384 return AVERROR(ENOMEM);
1385 sc->ctts_count = entries;
4e5ef14f 1386
c4ac052b 1387 for(i=0; i<entries; i++) {
70a61ed4
MN
1388 int count =get_be32(pb);
1389 int duration =get_be32(pb);
1390
1391 sc->ctts_data[i].count = count;
1392 sc->ctts_data[i].duration= duration;
e7452721
BC
1393 if (duration < 0)
1394 sc->dts_shift = FFMAX(sc->dts_shift, -duration);
c4ac052b 1395 }
e7452721 1396
bddc2df5 1397 dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
e7452721 1398
c4ac052b
MN
1399 return 0;
1400}
1401
1e77810d
BC
1402static void mov_build_index(MOVContext *mov, AVStream *st)
1403{
1404 MOVStreamContext *sc = st->priv_data;
bc5c918e 1405 int64_t current_offset;
1e77810d
BC
1406 int64_t current_dts = 0;
1407 unsigned int stts_index = 0;
1408 unsigned int stsc_index = 0;
1409 unsigned int stss_index = 0;
171a3531 1410 unsigned int stps_index = 0;
1e77810d 1411 unsigned int i, j;
c5898e86 1412 uint64_t stream_size = 0;
1e77810d 1413
baf2ffd3
BC
1414 /* adjust first dts according to edit list */
1415 if (sc->time_offset) {
2ac736a6 1416 int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
bbe46bc4 1417 current_dts = -rescaled;
f03a081d
BC
1418 if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
1419 /* more than 16 frames delay, dts are likely wrong
1420 this happens with files created by iMovie */
1421 sc->wrong_dts = 1;
1422 st->codec->has_b_frames = 1;
1423 }
baf2ffd3
BC
1424 }
1425
d3bc61ac
BC
1426 /* only use old uncompressed audio chunk demuxing when stts specifies it */
1427 if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
1428 sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
1e77810d
BC
1429 unsigned int current_sample = 0;
1430 unsigned int stts_sample = 0;
171a3531 1431 unsigned int sample_size;
1e77810d
BC
1432 unsigned int distance = 0;
1433 int key_off = sc->keyframes && sc->keyframes[0] == 1;
1434
4b29ed39
BC
1435 current_dts -= sc->dts_shift;
1436
1e77810d
BC
1437 for (i = 0; i < sc->chunk_count; i++) {
1438 current_offset = sc->chunk_offsets[i];
04e06cfa
BC
1439 if (stsc_index + 1 < sc->stsc_count &&
1440 i + 1 == sc->stsc_data[stsc_index + 1].first)
1e77810d 1441 stsc_index++;
04e06cfa 1442 for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
171a3531 1443 int keyframe = 0;
1e77810d
BC
1444 if (current_sample >= sc->sample_count) {
1445 av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
f0f2218d 1446 return;
1e77810d 1447 }
171a3531
BC
1448
1449 if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
1450 keyframe = 1;
1e77810d
BC
1451 if (stss_index + 1 < sc->keyframe_count)
1452 stss_index++;
171a3531
BC
1453 } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
1454 keyframe = 1;
1455 if (stps_index + 1 < sc->stps_count)
1456 stps_index++;
1e77810d 1457 }
171a3531
BC
1458 if (keyframe)
1459 distance = 0;
1e77810d 1460 sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
978677a7 1461 if(sc->pseudo_stream_id == -1 ||
04e06cfa 1462 sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
1e77810d
BC
1463 av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
1464 keyframe ? AVINDEX_KEYFRAME : 0);
585dac65
BC
1465 dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1466 "size %d, distance %d, keyframe %d\n", st->index, current_sample,
1467 current_offset, current_dts, sample_size, distance, keyframe);
1468 }
6c00a9de 1469
1e77810d 1470 current_offset += sample_size;
c5898e86 1471 stream_size += sample_size;
bbe46bc4 1472 current_dts += sc->stts_data[stts_index].duration;
1e77810d
BC
1473 distance++;
1474 stts_sample++;
1475 current_sample++;
1476 if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
1477 stts_sample = 0;
1478 stts_index++;
1479 }
1480 }
1481 }
fedb1eca
BC
1482 if (st->duration > 0)
1483 st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
7e69621f 1484 } else {
1e77810d 1485 for (i = 0; i < sc->chunk_count; i++) {
7e69621f
BC
1486 unsigned chunk_samples;
1487
1e77810d 1488 current_offset = sc->chunk_offsets[i];
04e06cfa
BC
1489 if (stsc_index + 1 < sc->stsc_count &&
1490 i + 1 == sc->stsc_data[stsc_index + 1].first)
1e77810d 1491 stsc_index++;
04e06cfa 1492 chunk_samples = sc->stsc_data[stsc_index].count;
7e69621f
BC
1493
1494 if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
1495 av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
1496 return;
1497 }
1498
1499 while (chunk_samples > 0) {
1500 unsigned size, samples;
1501
1502 if (sc->samples_per_frame >= 160) { // gsm
1503 samples = sc->samples_per_frame;
1504 size = sc->bytes_per_frame;
1505 } else {
1506 if (sc->samples_per_frame > 1) {
1507 samples = FFMIN((1024 / sc->samples_per_frame)*
1508 sc->samples_per_frame, chunk_samples);
1509 size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
1e77810d 1510 } else {
7e69621f
BC
1511 samples = FFMIN(1024, chunk_samples);
1512 size = samples * sc->sample_size;
1e77810d
BC
1513 }
1514 }
7e69621f
BC
1515
1516 av_add_index_entry(st, current_offset, current_dts, size, 0, AVINDEX_KEYFRAME);
117a9190
BC
1517 dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
1518 "size %d, duration %d\n", st->index, i, current_offset, current_dts,
7e69621f
BC
1519 size, samples);
1520
1521 current_offset += size;
bbe46bc4 1522 current_dts += samples;
7e69621f 1523 chunk_samples -= samples;
1e77810d
BC
1524 }
1525 }
1526 }
1e77810d 1527}
bd991df2 1528
c3e92a6c 1529static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879
ZK
1530{
1531 AVStream *st;
1532 MOVStreamContext *sc;
bd991df2 1533 int ret;
5ca1d879 1534
5ca1d879 1535 st = av_new_stream(c->fc, c->fc->nb_streams);
3efe8848 1536 if (!st) return AVERROR(ENOMEM);
9a630c25 1537 sc = av_mallocz(sizeof(MOVStreamContext));
2922cbdb 1538 if (!sc) return AVERROR(ENOMEM);
5ca1d879 1539
5ca1d879 1540 st->priv_data = sc;
05edc1a7 1541 st->codec->codec_type = CODEC_TYPE_DATA;
64d50fa5 1542 sc->ffindex = st->index;
5ca1d879 1543
bd991df2
BC
1544 if ((ret = mov_read_default(c, pb, atom)) < 0)
1545 return ret;
1546
1547 /* sanity checks */
6c00a9de
BC
1548 if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
1549 (!sc->sample_size && !sc->sample_count))) {
6282c5f4
BC
1550 av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
1551 st->index);
bd991df2
BC
1552 return 0;
1553 }
6c00a9de 1554
507330b9
BC
1555 if (!sc->time_scale) {
1556 av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
6c00a9de 1557 sc->time_scale = c->time_scale;
507330b9
BC
1558 if (!sc->time_scale)
1559 sc->time_scale = 1;
1560 }
6c00a9de 1561
bbe46bc4 1562 av_set_pts_info(st, 64, 1, sc->time_scale);
bd991df2 1563
3f78a3a9 1564 if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
5b4f5e5d
BC
1565 !st->codec->frame_size && sc->stts_count == 1) {
1566 st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
1567 st->codec->sample_rate, sc->time_scale);
1568 dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
1569 }
bd991df2 1570
bd991df2
BC
1571 mov_build_index(c, st);
1572
1573 if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
1574 if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
9e81a0ce
BC
1575 av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
1576 st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
bd991df2
BC
1577 } else
1578 sc->pb = c->fc->pb;
1579
1580 switch (st->codec->codec_id) {
b250f9c6 1581#if CONFIG_H261_DECODER
bd991df2
BC
1582 case CODEC_ID_H261:
1583#endif
b250f9c6 1584#if CONFIG_H263_DECODER
bd991df2
BC
1585 case CODEC_ID_H263:
1586#endif
a0dd3c00
BC
1587#if CONFIG_H264_DECODER
1588 case CODEC_ID_H264:
1589#endif
b250f9c6 1590#if CONFIG_MPEG4_DECODER
bd991df2
BC
1591 case CODEC_ID_MPEG4:
1592#endif
6c00a9de 1593 st->codec->width = 0; /* let decoder init width/height */
bd991df2
BC
1594 st->codec->height= 0;
1595 break;
bd991df2 1596 }
f9900374
BC
1597
1598 /* Do not need those anymore. */
1599 av_freep(&sc->chunk_offsets);
04e06cfa 1600 av_freep(&sc->stsc_data);
f9900374
BC
1601 av_freep(&sc->sample_sizes);
1602 av_freep(&sc->keyframes);
1603 av_freep(&sc->stts_data);
171a3531 1604 av_freep(&sc->stps_data);
f9900374 1605
bd991df2 1606 return 0;
5ca1d879
ZK
1607}
1608
c3e92a6c 1609static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
51c15201
BC
1610{
1611 int ret;
1612 c->itunes_metadata = 1;
1613 ret = mov_read_default(c, pb, atom);
1614 c->itunes_metadata = 0;
1615 return ret;
1616}
1617
c3e92a6c 1618static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
51c15201 1619{
df8843c6
BC
1620 while (atom.size > 8) {
1621 uint32_t tag = get_le32(pb);
1622 atom.size -= 4;
1623 if (tag == MKTAG('h','d','l','r')) {
1624 url_fseek(pb, -8, SEEK_CUR);
1625 atom.size += 8;
1626 return mov_read_default(c, pb, atom);
1627 }
1628 }
1629 return 0;
51c15201
BC
1630}
1631
c3e92a6c 1632static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879 1633{
ec072669
JS
1634 int i;
1635 int width;
1636 int height;
1637 int64_t disp_transform[2];
1638 int display_matrix[3][2];
6a63ff19
BC
1639 AVStream *st;
1640 MOVStreamContext *sc;
1641 int version;
1642
1643 if (c->fc->nb_streams < 1)
1644 return 0;
1645 st = c->fc->streams[c->fc->nb_streams-1];
1646 sc = st->priv_data;
5ca1d879 1647
6a63ff19 1648 version = get_byte(pb);
23f08617 1649 get_be24(pb); /* flags */
5ca1d879
ZK
1650 /*
1651 MOV_TRACK_ENABLED 0x0001
1652 MOV_TRACK_IN_MOVIE 0x0002
1653 MOV_TRACK_IN_PREVIEW 0x0004
1654 MOV_TRACK_IN_POSTER 0x0008
1655 */
1656
1175561e
BC
1657 if (version == 1) {
1658 get_be64(pb);
1659 get_be64(pb);
1660 } else {
1661 get_be32(pb); /* creation time */
1662 get_be32(pb); /* modification time */
1663 }
5ca1d879
ZK
1664 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1665 get_be32(pb); /* reserved */
fcdd622c 1666
117a9190
BC
1667 /* highlevel (considering edits) duration in movie timebase */
1668 (version == 1) ? get_be64(pb) : get_be32(pb);
5ca1d879
ZK
1669 get_be32(pb); /* reserved */
1670 get_be32(pb); /* reserved */
1671
1672 get_be16(pb); /* layer */
1673 get_be16(pb); /* alternate group */
1674 get_be16(pb); /* volume */
1675 get_be16(pb); /* reserved */
1676
ec072669
JS
1677 //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
1678 // they're kept in fixed point format through all calculations
1679 // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
1680 for (i = 0; i < 3; i++) {
1681 display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
1682 display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
1683 get_be32(pb); // 2.30 fixed point (not used)
1684 }
5ca1d879 1685
ec072669
JS
1686 width = get_be32(pb); // 16.16 fixed point track width
1687 height = get_be32(pb); // 16.16 fixed point track height
6cdbff63
DC
1688 sc->width = width >> 16;
1689 sc->height = height >> 16;
ec072669 1690
d862fce7 1691 // transform the display width/height according to the matrix
ec072669 1692 // skip this if the display matrix is the default identity matrix
d862fce7 1693 // or if it is rotating the picture, ex iPhone 3GS
ec072669
JS
1694 // to keep the same scale, use [width height 1<<16]
1695 if (width && height &&
d862fce7
BC
1696 ((display_matrix[0][0] != 65536 ||
1697 display_matrix[1][1] != 65536) &&
1698 !display_matrix[0][1] &&
1699 !display_matrix[1][0] &&
1700 !display_matrix[2][0] && !display_matrix[2][1])) {
ec072669
JS
1701 for (i = 0; i < 2; i++)
1702 disp_transform[i] =
1703 (int64_t) width * display_matrix[0][i] +
1704 (int64_t) height * display_matrix[1][i] +
1705 ((int64_t) display_matrix[2][i] << 16);
1706
1707 //sample aspect ratio is new width/height divided by old width/height
59729451 1708 st->sample_aspect_ratio = av_d2q(
ec072669
JS
1709 ((double) disp_transform[0] * height) /
1710 ((double) disp_transform[1] * width), INT_MAX);
1711 }
5ca1d879
ZK
1712 return 0;
1713}
1714
c3e92a6c 1715static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
61aedb0f
BC
1716{
1717 MOVFragment *frag = &c->fragment;
1718 MOVTrackExt *trex = NULL;
1719 int flags, track_id, i;
1720
1721 get_byte(pb); /* version */
1722 flags = get_be24(pb);
1723
1724 track_id = get_be32(pb);
63581eb1 1725 if (!track_id)
61aedb0f
BC
1726 return -1;
1727 frag->track_id = track_id;
1728 for (i = 0; i < c->trex_count; i++)
1729 if (c->trex_data[i].track_id == frag->track_id) {
1730 trex = &c->trex_data[i];
1731 break;
1732 }
1733 if (!trex) {
1734 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
1735 return -1;
1736 }
1737
1738 if (flags & 0x01) frag->base_data_offset = get_be64(pb);
1739 else frag->base_data_offset = frag->moof_offset;
1740 if (flags & 0x02) frag->stsd_id = get_be32(pb);
1741 else frag->stsd_id = trex->stsd_id;
1742
1743 frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
1744 frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
1745 frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
1746 dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
1747 return 0;
1748}
1749
c3e92a6c 1750static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
61aedb0f
BC
1751{
1752 MOVTrackExt *trex;
1753
1754 if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
1755 return -1;
0d8f0abf
BC
1756 trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
1757 if (!trex)
61aedb0f 1758 return AVERROR(ENOMEM);
0d8f0abf 1759 c->trex_data = trex;
61aedb0f
BC
1760 trex = &c->trex_data[c->trex_count++];
1761 get_byte(pb); /* version */
1762 get_be24(pb); /* flags */
1763 trex->track_id = get_be32(pb);
1764 trex->stsd_id = get_be32(pb);
1765 trex->duration = get_be32(pb);
1766 trex->size = get_be32(pb);
1767 trex->flags = get_be32(pb);
1768 return 0;
1769}
1770
c3e92a6c 1771static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
61aedb0f
BC
1772{
1773 MOVFragment *frag = &c->fragment;
63581eb1 1774 AVStream *st = NULL;
44e43aab 1775 MOVStreamContext *sc;
61aedb0f
BC
1776 uint64_t offset;
1777 int64_t dts;
1778 int data_offset = 0;
1779 unsigned entries, first_sample_flags = frag->flags;
1780 int flags, distance, i;
1781
63581eb1
AC
1782 for (i = 0; i < c->fc->nb_streams; i++) {
1783 if (c->fc->streams[i]->id == frag->track_id) {
1784 st = c->fc->streams[i];
1785 break;
1786 }
1787 }
1788 if (!st) {
1789 av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
44e43aab 1790 return -1;
63581eb1 1791 }
44e43aab 1792 sc = st->priv_data;
61aedb0f
BC
1793 if (sc->pseudo_stream_id+1 != frag->stsd_id)
1794 return 0;
61aedb0f
BC
1795 get_byte(pb); /* version */
1796 flags = get_be24(pb);
1797 entries = get_be32(pb);
1798 dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
1799 if (flags & 0x001) data_offset = get_be32(pb);
1800 if (flags & 0x004) first_sample_flags = get_be32(pb);
1801 if (flags & 0x800) {
0d8f0abf 1802 MOVStts *ctts_data;
61aedb0f
BC
1803 if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
1804 return -1;
0d8f0abf
BC
1805 ctts_data = av_realloc(sc->ctts_data,
1806 (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
1807 if (!ctts_data)
61aedb0f 1808 return AVERROR(ENOMEM);
0d8f0abf 1809 sc->ctts_data = ctts_data;
61aedb0f
BC
1810 }
1811 dts = st->duration;
1812 offset = frag->base_data_offset + data_offset;
1813 distance = 0;
1814 dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
1815 for (i = 0; i < entries; i++) {
1816 unsigned sample_size = frag->size;
1817 int sample_flags = i ? frag->flags : first_sample_flags;
1818 unsigned sample_duration = frag->duration;
1819 int keyframe;
1820
1821 if (flags & 0x100) sample_duration = get_be32(pb);
1822 if (flags & 0x200) sample_size = get_be32(pb);
1823 if (flags & 0x400) sample_flags = get_be32(pb);
1824 if (flags & 0x800) {
1825 sc->ctts_data[sc->ctts_count].count = 1;
1826 sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
1827 sc->ctts_count++;
1828 }
1829 if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
1830 (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
1831 distance = 0;
1832 av_add_index_entry(st, offset, dts, sample_size, distance,
1833 keyframe ? AVINDEX_KEYFRAME : 0);
1834 dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
1835 "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
1836 offset, dts, sample_size, distance, keyframe);
1837 distance++;
bbe46bc4 1838 dts += sample_duration;
61aedb0f
BC
1839 offset += sample_size;
1840 }
1841 frag->moof_offset = offset;
61aedb0f
BC
1842 st->duration = dts;
1843 return 0;
1844}
1845
5ca1d879
ZK
1846/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1847/* like the files created with Adobe Premiere 5.0, for samples see */
1848/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
c3e92a6c 1849static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
5ca1d879
ZK
1850{
1851 int err;
5ca1d879 1852
5ca1d879
ZK
1853 if (atom.size < 8)
1854 return 0; /* continue */
1855 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1856 url_fskip(pb, atom.size - 4);
1857 return 0;
1858 }
1859 atom.type = get_le32(pb);
1860 atom.offset += 8;
1861 atom.size -= 8;
1c126b4f 1862 if (atom.type != MKTAG('m','d','a','t')) {
5ca1d879
ZK
1863 url_fskip(pb, atom.size);
1864 return 0;
1865 }
1866 err = mov_read_mdat(c, pb, atom);
5ca1d879
ZK
1867 return err;
1868}
1869
c3e92a6c 1870static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
0147f198 1871{
b250f9c6 1872#if CONFIG_ZLIB
0147f198 1873 ByteIOContext ctx;
b6a17df4
ZK
1874 uint8_t *cmov_data;
1875 uint8_t *moov_data; /* uncompressed data */
0147f198 1876 long cmov_len, moov_len;
6f04eb1e 1877 int ret = -1;
b6a17df4 1878
0147f198 1879 get_be32(pb); /* dcom atom */
1c126b4f 1880 if (get_le32(pb) != MKTAG('d','c','o','m'))
0147f198 1881 return -1;
1c126b4f 1882 if (get_le32(pb) != MKTAG('z','l','i','b')) {
f3592353 1883 av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
0147f198
FR
1884 return -1;
1885 }
1886 get_be32(pb); /* cmvd atom */
1c126b4f 1887 if (get_le32(pb) != MKTAG('c','m','v','d'))
0147f198
FR
1888 return -1;
1889 moov_len = get_be32(pb); /* uncompressed size */
5ca1d879 1890 cmov_len = atom.size - 6 * 4;
5cd62665 1891
9a630c25 1892 cmov_data = av_malloc(cmov_len);
0147f198 1893 if (!cmov_data)
0d8f0abf 1894 return AVERROR(ENOMEM);
9a630c25 1895 moov_data = av_malloc(moov_len);
0147f198
FR
1896 if (!moov_data) {
1897 av_free(cmov_data);
0d8f0abf 1898 return AVERROR(ENOMEM);
0147f198
FR
1899 }
1900 get_buffer(pb, cmov_data, cmov_len);
b6a17df4 1901 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
6f04eb1e 1902 goto free_and_return;
942f3bb5 1903 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
6f04eb1e 1904 goto free_and_return;
1c126b4f 1905 atom.type = MKTAG('m','o','o','v');
5ca1d879
ZK
1906 atom.offset = 0;
1907 atom.size = moov_len;
9ed83b0a 1908#ifdef DEBUG
dbb4f00a 1909// { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
9ed83b0a 1910#endif
5ca1d879 1911 ret = mov_read_default(c, &ctx, atom);
6f04eb1e 1912free_and_return:
0147f198
FR
1913 av_free(moov_data);
1914 av_free(cmov_data);
1915 return ret;
d966b2f0
BC
1916#else
1917 av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
1918 return -1;
0147f198 1919#endif
d966b2f0 1920}
0147f198 1921
baf25c9d 1922/* edit list atom */
c3e92a6c 1923static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
baf25c9d 1924{
1c4bf2ec 1925 MOVStreamContext *sc;
e0977c80
BC
1926 int i, edit_count;
1927
1c4bf2ec
BC
1928 if (c->fc->nb_streams < 1)
1929 return 0;
1930 sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
1931
e0977c80 1932 get_byte(pb); /* version */
23f08617 1933 get_be24(pb); /* flags */
1975c52c 1934 edit_count = get_be32(pb); /* entries */
e0977c80 1935
53e099de
BC
1936 if((uint64_t)edit_count*12+8 > atom.size)
1937 return -1;
1938
e0977c80 1939 for(i=0; i<edit_count; i++){
d435e520 1940 int time;
2ac736a6 1941 int duration = get_be32(pb); /* Track duration */
d435e520 1942 time = get_be32(pb); /* Media time */
e0977c80 1943 get_be32(pb); /* Media rate */
2ac736a6
RD
1944 if (i == 0 && time >= -1) {
1945 sc->time_offset = time != -1 ? time : -duration;
a5929abe 1946 }
e0977c80 1947 }
baf2ffd3
BC
1948
1949 if(edit_count > 1)
1950 av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
1951 "a/v desync might occur, patch welcome\n");
1952
4c125b8f 1953 dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
e0977c80 1954 return 0;
baf25c9d
GC
1955}
1956
6cea494e 1957static const MOVParseTableEntry mov_default_parse_table[] = {
d4fdba0d 1958{ MKTAG('a','v','s','s'), mov_read_extradata },
1c126b4f
BC
1959{ MKTAG('c','o','6','4'), mov_read_stco },
1960{ MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
1961{ MKTAG('d','i','n','f'), mov_read_default },
1962{ MKTAG('d','r','e','f'), mov_read_dref },
1963{ MKTAG('e','d','t','s'), mov_read_default },
1964{ MKTAG('e','l','s','t'), mov_read_elst },
1965{ MKTAG('e','n','d','a'), mov_read_enda },
1966{ MKTAG('f','i','e','l'), mov_read_extradata },
1967{ MKTAG('f','t','y','p'), mov_read_ftyp },
1968{ MKTAG('g','l','b','l'), mov_read_glbl },
1969{ MKTAG('h','d','l','r'), mov_read_hdlr },
51c15201 1970{ MKTAG('i','l','s','t'), mov_read_ilst },
1c126b4f
BC
1971{ MKTAG('j','p','2','h'), mov_read_extradata },
1972{ MKTAG('m','d','a','t'), mov_read_mdat },
1973{ MKTAG('m','d','h','d'), mov_read_mdhd },
1974{ MKTAG('m','d','i','a'), mov_read_default },
51c15201 1975{ MKTAG('m','e','t','a'), mov_read_meta },
1c126b4f
BC
1976{ MKTAG('m','i','n','f'), mov_read_default },
1977{ MKTAG('m','o','o','f'), mov_read_moof },
1978{ MKTAG('m','o','o','v'), mov_read_moov },
1979{ MKTAG('m','v','e','x'), mov_read_default },
1980{ MKTAG('m','v','h','d'), mov_read_mvhd },
1981{ MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
1982{ MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
1983{ MKTAG('a','v','c','C'), mov_read_glbl },
6da54074 1984{ MKTAG('p','a','s','p'), mov_read_pasp },
1c126b4f
BC
1985{ MKTAG('s','t','b','l'), mov_read_default },
1986{ MKTAG('s','t','c','o'), mov_read_stco },
171a3531 1987{ MKTAG('s','t','p','s'), mov_read_stps },
1c126b4f
BC
1988{ MKTAG('s','t','s','c'), mov_read_stsc },
1989{ MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
1990{ MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
1991{ MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
1992{ MKTAG('s','t','t','s'), mov_read_stts },
bd27eed6 1993{ MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
1c126b4f
BC
1994{ MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
1995{ MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
1996{ MKTAG('t','r','a','k'), mov_read_trak },
1997{ MKTAG('t','r','a','f'), mov_read_default },
1998{ MKTAG('t','r','e','x'), mov_read_trex },
1999{ MKTAG('t','r','u','n'), mov_read_trun },
86b0affd 2000{ MKTAG('u','d','t','a'), mov_read_default },
1c126b4f
BC
2001{ MKTAG('w','a','v','e'), mov_read_wave },
2002{ MKTAG('e','s','d','s'), mov_read_esds },
2003{ MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
2004{ MKTAG('c','m','o','v'), mov_read_cmov },
bcfe2ba0 2005{ 0, NULL }
6cea494e
ZK
2006};
2007
c9a65ca8
FB
2008static int mov_probe(AVProbeData *p)
2009{
0e7eed09
FB
2010 unsigned int offset;
2011 uint32_t tag;
2497479f 2012 int score = 0;
3ffe3793 2013
c9a65ca8 2014 /* check file header */
0e7eed09
FB
2015 offset = 0;
2016 for(;;) {
2017 /* ignore invalid offset */
2018 if ((offset + 8) > (unsigned int)p->buf_size)
2497479f 2019 return score;
fead30d4 2020 tag = AV_RL32(p->buf + offset + 4);
0e7eed09 2021 switch(tag) {
2497479f 2022 /* check for obvious tags */
1c126b4f
BC
2023 case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
2024 case MKTAG('m','o','o','v'):
2025 case MKTAG('m','d','a','t'):
2026 case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
2027 case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
40e7aaa3 2028 case MKTAG('f','t','y','p'):
3ffe3793 2029 return AVPROBE_SCORE_MAX;
2497479f 2030 /* those are more common words, so rate then a bit less */
1c126b4f
BC
2031 case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
2032 case MKTAG('w','i','d','e'):
2033 case MKTAG('f','r','e','e'):
2034 case MKTAG('j','u','n','k'):
2035 case MKTAG('p','i','c','t'):
2497479f 2036 return AVPROBE_SCORE_MAX - 5;
5469b788 2037 case MKTAG(0x82,0x82,0x7f,0x7d):
1c126b4f
BC
2038 case MKTAG('s','k','i','p'):
2039 case MKTAG('u','u','i','d'):
2040 case MKTAG('p','r','f','l'):
fead30d4 2041 offset = AV_RB32(p->buf+offset) + offset;
2497479f
FR
2042 /* if we only find those cause probedata is too small at least rate them */
2043 score = AVPROBE_SCORE_MAX - 50;
0e7eed09
FB
2044 break;
2045 default:
2046 /* unrecognized tag */
2497479f 2047 return score;
0e7eed09 2048 }
3ffe3793 2049 }
2497479f 2050 return score;
c9a65ca8
FB
2051}
2052
a266644f 2053static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
6cea494e 2054{
e4141433 2055 MOVContext *mov = s->priv_data;
899681cd 2056 ByteIOContext *pb = s->pb;
f9900374 2057 int err;
c3e92a6c 2058 MOVAtom atom = { 0, 0, 0 };
6cea494e 2059
6cea494e 2060 mov->fc = s;
117a9190
BC
2061 /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
2062 if(!url_is_streamed(pb))
bb270c08 2063 atom.size = url_fsize(pb);
6cea494e 2064 else
fa22ca22 2065 atom.size = INT64_MAX;
6cea494e 2066
6cea494e 2067 /* check MOV header */
612b5cbb
BC
2068 if ((err = mov_read_default(mov, pb, atom)) < 0) {
2069 av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
2070 return err;
2071 }
2072 if (!mov->found_moov) {
2073 av_log(s, AV_LOG_ERROR, "moov atom not found\n");
bb270c08 2074 return -1;
6cea494e 2075 }
0265fe81 2076 dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
4e5ef14f 2077
6cea494e
ZK
2078 return 0;
2079}
2080
5dc5c43b 2081static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
6cea494e 2082{
5dc5c43b 2083 AVIndexEntry *sample = NULL;
86d8602f 2084 int64_t best_dts = INT64_MAX;
5dc5c43b 2085 int i;
11f16b66 2086 for (i = 0; i < s->nb_streams; i++) {
69fc436c
RD
2087 AVStream *avst = s->streams[i];
2088 MOVStreamContext *msc = avst->priv_data;
3fe4d5d4 2089 if (msc->pb && msc->current_sample < avst->nb_index_entries) {
69fc436c 2090 AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
bbe46bc4 2091 int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
1c02d96f 2092 dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
687f35f3
BC
2093 if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
2094 (!url_is_streamed(s->pb) &&
221e21b7 2095 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
687f35f3 2096 ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
221e21b7 2097 (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
b72708f8
BC
2098 sample = current_sample;
2099 best_dts = dts;
5dc5c43b 2100 *st = avst;
86d8602f 2101 }
6cea494e 2102 }
6cea494e 2103 }
5dc5c43b
RD
2104 return sample;
2105}
2106
2107static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
2108{
2109 MOVContext *mov = s->priv_data;
2110 MOVStreamContext *sc;
2111 AVIndexEntry *sample;
2112 AVStream *st = NULL;
2113 int ret;
2114 retry:
2115 sample = mov_find_next_sample(s, &st);
433aeb62
BC
2116 if (!sample) {
2117 mov->found_mdat = 0;
2118 if (!url_is_streamed(s->pb) ||
c3e92a6c 2119 mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
433aeb62 2120 url_feof(s->pb))
350f2c2c 2121 return AVERROR_EOF;
433aeb62
BC
2122 dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
2123 goto retry;
2124 }
69fc436c 2125 sc = st->priv_data;
b72708f8
BC
2126 /* must be done just before reading, to avoid infinite loop on sample */
2127 sc->current_sample++;
3fe4d5d4
RD
2128
2129 if (st->discard != AVDISCARD_ALL) {
e1c1b0ff
RD
2130 if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
2131 av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
2132 sc->ffindex, sample->pos);
2133 return -1;
2134 }
2135 ret = av_get_packet(sc->pb, pkt, sample->size);
a2f38511
RD
2136 if (ret < 0)
2137 return ret;
e1c1b0ff
RD
2138#if CONFIG_DV_DEMUXER
2139 if (mov->dv_demux && sc->dv_audio_container) {
2140 dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
2141 av_free(pkt->data);
2142 pkt->size = 0;
2143 ret = dv_get_packet(mov->dv_demux, pkt);
2144 if (ret < 0)
2145 return ret;
2146 }
312954f0 2147#endif
3fe4d5d4
RD
2148 }
2149
b72708f8
BC
2150 pkt->stream_index = sc->ffindex;
2151 pkt->dts = sample->timestamp;
2152 if (sc->ctts_data) {
bbe46bc4 2153 pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
b72708f8 2154 /* update ctts context */
a234e38d
BC
2155 sc->ctts_sample++;
2156 if (sc->ctts_index < sc->ctts_count &&
2157 sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
2158 sc->ctts_index++;
2159 sc->ctts_sample = 0;
b565ea09 2160 }
0c5f76f7
BC
2161 if (sc->wrong_dts)
2162 pkt->dts = AV_NOPTS_VALUE;
b72708f8 2163 } else {
f0f2218d 2164 int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
e8430214
HG
2165 st->index_entries[sc->current_sample].timestamp : st->duration;
2166 pkt->duration = next_dts - pkt->dts;
b72708f8 2167 pkt->pts = pkt->dts;
b565ea09 2168 }
3fe4d5d4
RD
2169 if (st->discard == AVDISCARD_ALL)
2170 goto retry;
b72708f8
BC
2171 pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
2172 pkt->pos = sample->pos;
29c90869
BC
2173 dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
2174 pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
b72708f8
BC
2175 return 0;
2176}
3ffe3793 2177
b72708f8
BC
2178static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
2179{
2180 MOVStreamContext *sc = st->priv_data;
2181 int sample, time_sample;
2182 int i;
115329f1 2183
b72708f8 2184 sample = av_index_search_timestamp(st, timestamp, flags);
318c5e05 2185 dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
b72708f8
BC
2186 if (sample < 0) /* not sure what to do */
2187 return -1;
2188 sc->current_sample = sample;
1c02d96f 2189 dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
b72708f8
BC
2190 /* adjust ctts index */
2191 if (sc->ctts_data) {
2192 time_sample = 0;
2193 for (i = 0; i < sc->ctts_count; i++) {
54a5c719
BC
2194 int next = time_sample + sc->ctts_data[i].count;
2195 if (next > sc->current_sample) {
a234e38d
BC
2196 sc->ctts_index = i;
2197 sc->ctts_sample = sc->current_sample - time_sample;
b72708f8 2198 break;
115329f1 2199 }
54a5c719 2200 time_sample = next;
247d56f5 2201 }
247d56f5 2202 }
b72708f8 2203 return sample;
6cea494e
ZK
2204}
2205
961e0ccd 2206static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
baf25c9d 2207{
b72708f8
BC
2208 AVStream *st;
2209 int64_t seek_timestamp, timestamp;
2210 int sample;
2211 int i;
baf25c9d 2212
b72708f8 2213 if (stream_index >= s->nb_streams)
baf25c9d 2214 return -1;
8dc81a45
BC
2215 if (sample_time < 0)
2216 sample_time = 0;
baf25c9d 2217
b72708f8
BC
2218 st = s->streams[stream_index];
2219 sample = mov_seek_stream(st, sample_time, flags);
2220 if (sample < 0)
baf25c9d 2221 return -1;
baf25c9d 2222
b72708f8
BC
2223 /* adjust seek timestamp to found sample timestamp */
2224 seek_timestamp = st->index_entries[sample].timestamp;
baf25c9d 2225
b72708f8
BC
2226 for (i = 0; i < s->nb_streams; i++) {
2227 st = s->streams[i];
3fe4d5d4 2228 if (stream_index == i)
b72708f8 2229 continue;
baf25c9d 2230
b72708f8
BC
2231 timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
2232 mov_seek_stream(st, timestamp, flags);
115329f1 2233 }
baf25c9d
GC
2234 return 0;
2235}
baf25c9d 2236
a266644f 2237static int mov_read_close(AVFormatContext *s)
6cea494e 2238{
e4141433 2239 MOVContext *mov = s->priv_data;
6c00a9de
BC
2240 int i, j;
2241
2242 for (i = 0; i < s->nb_streams; i++) {
e49da827
BC
2243 AVStream *st = s->streams[i];
2244 MOVStreamContext *sc = st->priv_data;
6c00a9de 2245
7c622eed 2246 av_freep(&sc->ctts_data);
6c00a9de 2247 for (j = 0; j < sc->drefs_count; j++)
221e21b7
BC
2248 av_freep(&sc->drefs[j].path);
2249 av_freep(&sc->drefs);
2250 if (sc->pb && sc->pb != s->pb)
2251 url_fclose(sc->pb);
e49da827
BC
2252
2253 av_freep(&st->codec->palctrl);
4440b118 2254 }
6c00a9de
BC
2255
2256 if (mov->dv_demux) {
2257 for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
b60c0454
BC
2258 av_freep(&mov->dv_fctx->streams[i]->codec);
2259 av_freep(&mov->dv_fctx->streams[i]);
2260 }
2261 av_freep(&mov->dv_fctx);
2262 av_freep(&mov->dv_demux);
2263 }
6c00a9de 2264
61aedb0f 2265 av_freep(&mov->trex_data);
6c00a9de 2266
6cea494e
ZK
2267 return 0;
2268}
2269
ff70e601 2270AVInputFormat mov_demuxer = {
fc5188f3 2271 "mov,mp4,m4a,3gp,3g2,mj2",
bde15e74 2272 NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
c9a65ca8
FB
2273 sizeof(MOVContext),
2274 mov_probe,
6cea494e
ZK
2275 mov_read_header,
2276 mov_read_packet,
2277 mov_read_close,
baf25c9d 2278 mov_read_seek,
6cea494e 2279};