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