cleanup
[libav.git] / libavformat / mov.c
CommitLineData
6cea494e
ZK
1/*
2 * MOV decoder.
19720f15 3 * Copyright (c) 2001 Fabrice Bellard.
6cea494e 4 *
19720f15
FB
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
6cea494e 9 *
19720f15 10 * This library is distributed in the hope that it will be useful,
6cea494e 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19720f15
FB
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
6cea494e 14 *
19720f15
FB
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
6cea494e 18 */
d957696f
MN
19
20#include <limits.h>
21
6cea494e
ZK
22#include "avformat.h"
23#include "avi.h"
24
0147f198
FR
25#ifdef CONFIG_ZLIB
26#include <zlib.h>
27#endif
28
6cea494e
ZK
29/*
30 * First version by Francois Revol revol@free.fr
baf25c9d 31 * Seek function by Gael Chardon gael.dev@4now.net
5ca1d879 32 *
6cea494e 33 * Features and limitations:
5ca1d879 34 * - reads most of the QT files I have (at least the structure),
6cea494e 35 * the exceptions are .mov with zlib compressed headers ('cmov' section). It shouldn't be hard to implement.
0147f198 36 * FIXED, Francois Revol, 07/17/2002
6cea494e
ZK
37 * - ffmpeg has nearly none of the usual QuickTime codecs,
38 * although I succesfully dumped raw and mp3 audio tracks off .mov files.
39 * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
40 * - .mp4 parsing is still hazardous, although the format really is QuickTime with some minor changes
41 * (to make .mov parser crash maybe ?), despite what they say in the MPEG FAQ at
42 * http://mpeg.telecomitalialab.com/faq.htm
43 * - the code is quite ugly... maybe I won't do it recursive next time :-)
baf25c9d 44 * - seek is not supported with files that contain edit list
5ca1d879 45 *
6cea494e
ZK
46 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
47 * when coding this :) (it's a writer anyway)
5ca1d879 48 *
6cea494e
ZK
49 * Reference documents:
50 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
51 * Apple:
baf25c9d 52 * http://developer.apple.com/documentation/QuickTime/QTFF/
15c8dbe7 53 * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
6cea494e
ZK
54 * QuickTime is a trademark of Apple (AFAIK :))
55 */
56
c9a65ca8 57//#define DEBUG
9ed83b0a
ZK
58#ifdef DEBUG
59#include <stdio.h>
60#include <fcntl.h>
61#endif
6cea494e 62
b595afaa
MM
63#include "qtpalette.h"
64
baf25c9d
GC
65
66/* Allows seeking (MOV_SPLIT_CHUNKS should also be defined) */
67#define MOV_SEEK
68
3ffe3793
FR
69/* allows chunk splitting - should work now... */
70/* in case you can't read a file, try commenting */
71#define MOV_SPLIT_CHUNKS
72
14342fd5
JC
73/* Special handling for movies created with Minolta Dimaxe Xi*/
74/* this fix should not interfere with other .mov files, but just in case*/
75#define MOV_MINOLTA_FIX
76
6cea494e
ZK
77/* some streams in QT (and in MP4 mostly) aren't either video nor audio */
78/* so we first list them as this, then clean up the list of streams we give back, */
79/* getting rid of these */
b6a17df4 80#define CODEC_TYPE_MOV_OTHER (enum CodecType) 2
6cea494e 81
a266644f 82static const CodecTag mov_video_tags[] = {
6cea494e 83/* { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
0147f198
FR
84/* { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
85/* { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
53e27dd5 86/* { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
6cea494e
ZK
87/* Graphics */
88/* Animation */
89/* Apple video */
90/* Kodak Photo CD */
3ffe3793 91 { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
6cea494e 92 { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
3ffe3793 93 { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
6cea494e 94 { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
53e27dd5
SB
95 { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
96/* { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
6cea494e
ZK
97/* { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
98/* Sorenson video */
0147f198
FR
99 { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
100 { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
3ffe3793 101 { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
8b82a956 102 { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
0e7eed09 103 { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
6cea494e 104 { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
8dafdb88 105 { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
6cea494e 106/* { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
0147f198 107 { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
25fa62e1 108 { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
e1687cc0
FB
109 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
110 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
53e27dd5 111/* { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, *//* AVID dv */
d86053a4 112 { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
2fdf638b
MM
113 { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
114 { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
1dc1ed99 115 { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
b595afaa 116 { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
070ed1bc 117 { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
d08d7142 118 { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
169eb021 119 { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
5ca1d879 120 { CODEC_ID_NONE, 0 },
6cea494e
ZK
121};
122
a266644f 123static const CodecTag mov_audio_tags[] = {
6cea494e
ZK
124/* { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, *//* uncompressed */
125 { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
5ca1d879 126 /* { CODEC_ID_PCM_S8, MKTAG('t', 'w', 'o', 's') },*/ /* 8 bits */
5cd62665 127 { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
6cea494e
ZK
128 { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /* */
129 { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /* */
130 { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /* */
0147f198 131 { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
3f95e843
FR
132 { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
133 { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
6cea494e
ZK
134
135 { CODEC_ID_MP2, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
136 { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
137 { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
138/* { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
139/* MP4 tags */
f2196640 140 { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
5ca1d879 141 /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
891f64b3 142 { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
d663a1fd 143 { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
8dafdb88 144 { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
5ca1d879 145 { CODEC_ID_NONE, 0 },
6cea494e
ZK
146};
147
148/* the QuickTime file format is quite convoluted...
149 * it has lots of index tables, each indexing something in another one...
150 * Here we just use what is needed to read the chunks
151 */
152
153typedef struct MOV_sample_to_chunk_tbl {
154 long first;
155 long count;
156 long id;
157} MOV_sample_to_chunk_tbl;
158
5cd62665 159typedef struct {
5ca1d879
ZK
160 uint32_t type;
161 int64_t offset;
162 int64_t size; /* total size (excluding the size and type fields) */
163} MOV_atom_t;
164
165typedef struct {
166 int seed;
167 int flags;
168 int size;
169 void* clrs;
170} MOV_ctab_t;
171
172typedef struct {
5cd62665
ZK
173 uint8_t version;
174 uint32_t flags; // 24bit
175
176 /* 0x03 ESDescrTag */
177 uint16_t es_id;
178#define MP4ODescrTag 0x01
179#define MP4IODescrTag 0x02
180#define MP4ESDescrTag 0x03
181#define MP4DecConfigDescrTag 0x04
182#define MP4DecSpecificDescrTag 0x05
183#define MP4SLConfigDescrTag 0x06
184#define MP4ContentIdDescrTag 0x07
185#define MP4SupplContentIdDescrTag 0x08
186#define MP4IPIPtrDescrTag 0x09
187#define MP4IPMPPtrDescrTag 0x0A
188#define MP4IPMPDescrTag 0x0B
189#define MP4RegistrationDescrTag 0x0D
190#define MP4ESIDIncDescrTag 0x0E
191#define MP4ESIDRefDescrTag 0x0F
192#define MP4FileIODescrTag 0x10
193#define MP4FileODescrTag 0x11
194#define MP4ExtProfileLevelDescrTag 0x13
195#define MP4ExtDescrTagsStart 0x80
196#define MP4ExtDescrTagsEnd 0xFE
197 uint8_t stream_priority;
198
199 /* 0x04 DecConfigDescrTag */
200 uint8_t object_type_id;
201 uint8_t stream_type;
202 /* XXX: really streamType is
203 * only 6bit, followed by:
204 * 1bit upStream
205 * 1bit reserved
206 */
207 uint32_t buffer_size_db; // 24
208 uint32_t max_bitrate;
209 uint32_t avg_bitrate;
210
211 /* 0x05 DecSpecificDescrTag */
212 uint8_t decoder_cfg_len;
213 uint8_t *decoder_cfg;
214
215 /* 0x06 SLConfigDescrTag */
216 uint8_t sl_config_len;
217 uint8_t *sl_config;
218} MOV_esds_t;
219
b6a17df4
ZK
220struct MOVParseTableEntry;
221
cd461d48
MN
222typedef struct Time2Sample{
223 int count;
224 int duration;
225}Time2Sample;
226
6cea494e
ZK
227typedef struct MOVStreamContext {
228 int ffindex; /* the ffmpeg stream id */
229 int is_ff_stream; /* Is this stream presented to ffmpeg ? i.e. is this an audio or video stream ? */
230 long next_chunk;
231 long chunk_count;
0c1a9eda 232 int64_t *chunk_offsets;
cd461d48
MN
233 int stts_count;
234 Time2Sample *stts_data;
235 int edit_count; /* number of 'edit' (elst atom) */
6cea494e
ZK
236 long sample_to_chunk_sz;
237 MOV_sample_to_chunk_tbl *sample_to_chunk;
3ffe3793 238 long sample_to_chunk_index;
7fe5a3c0
GC
239 int sample_to_time_index;
240 long sample_to_time_sample;
241 uint64_t sample_to_time_time;
6cea494e
ZK
242 long sample_size;
243 long sample_count;
244 long *sample_sizes;
247d56f5
BB
245 long keyframe_count;
246 long *keyframes;
5cd62665 247 int time_scale;
3ffe3793
FR
248 long current_sample;
249 long left_in_chunk; /* how many samples before next chunk */
0e7eed09 250 /* specific MPEG4 header which is added at the beginning of the stream */
7fea94ce 251 unsigned int header_len;
0e7eed09 252 uint8_t *header_data;
5ca1d879 253 MOV_esds_t esds;
6cea494e
ZK
254} MOVStreamContext;
255
256typedef struct MOVContext {
257 int mp4; /* set to 1 as soon as we are sure that the file is an .mp4 file (even some header parsing depends on this) */
258 AVFormatContext *fc;
5cd62665
ZK
259 int time_scale;
260 int duration; /* duration of the longest track */
6cea494e
ZK
261 int found_moov; /* when both 'moov' and 'mdat' sections has been found */
262 int found_mdat; /* we suppose we have enough data to read the file */
0c1a9eda
ZK
263 int64_t mdat_size;
264 int64_t mdat_offset;
6cea494e
ZK
265 int total_streams;
266 /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
267 * but we need the info to be able to skip data from those streams in the 'mdat' section
268 */
269 MOVStreamContext *streams[MAX_STREAMS];
5cd62665 270
0c1a9eda 271 int64_t next_chunk_offset;
5cd62665 272 MOVStreamContext *partial; /* != 0 : there is still to read in the current chunk */
5ca1d879
ZK
273 int ctab_size;
274 MOV_ctab_t **ctab; /* color tables */
b6a17df4
ZK
275 const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
276 /* NOTE: for recursion save to/ restore from local variable! */
b595afaa
MM
277
278 AVPaletteControl palette_control;
6cea494e
ZK
279} MOVContext;
280
281
6cea494e
ZK
282/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
283
284/* those functions parse an atom */
285/* return code:
286 1: found what I wanted, exit
287 0: continue to parse next atom
288 -1: error occured, exit
289 */
5ca1d879 290typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
6cea494e
ZK
291
292/* links atom IDs to parse functions */
293typedef struct MOVParseTableEntry {
0c1a9eda 294 uint32_t type;
6cea494e
ZK
295 mov_parse_function func;
296} MOVParseTableEntry;
297
5ca1d879
ZK
298#ifdef DEBUG
299/*
300 * XXX: static sux, even more in a multithreaded environment...
301 * Avoid them. This is here just to help debugging.
302 */
303static int debug_indent = 0;
304void print_atom(const char *str, MOV_atom_t atom)
305{
306 unsigned int tag, i;
307 tag = (unsigned int) atom.type;
308 i=debug_indent;
309 if(tag == 0) tag = MKTAG('N', 'U', 'L', 'L');
310 while(i--)
baf25c9d
GC
311 av_log(NULL, AV_LOG_DEBUG, "|");
312 av_log(NULL, AV_LOG_DEBUG, "parse:");
313 av_log(NULL, AV_LOG_DEBUG, " %s: tag=%c%c%c%c offset=0x%x size=0x%x\n",
5ca1d879
ZK
314 str, tag & 0xff,
315 (tag >> 8) & 0xff,
316 (tag >> 16) & 0xff,
317 (tag >> 24) & 0xff,
318 (unsigned int)atom.offset,
319 (unsigned int)atom.size);
320 assert((unsigned int)atom.size < 0x7fffffff);// catching errors
321}
322#else
323#define print_atom(a,b)
324#endif
325
326
327static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 328{
5ca1d879 329 print_atom("leaf", atom);
b6a17df4 330
5ca1d879
ZK
331 if (atom.size>1)
332 url_fskip(pb, atom.size);
333/* url_seek(pb, atom_offset+atom.size, SEEK_SET); */
6cea494e
ZK
334 return 0;
335}
336
5ca1d879 337static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 338{
b6a17df4 339 int64_t total_size = 0;
5ca1d879 340 MOV_atom_t a;
6cea494e
ZK
341 int i;
342 int err = 0;
5ca1d879 343
6cea494e 344#ifdef DEBUG
5ca1d879 345 print_atom("default", atom);
6cea494e
ZK
346 debug_indent++;
347#endif
5cd62665 348
5ca1d879 349 a.offset = atom.offset;
6cea494e 350
9ed83b0a
ZK
351 if (atom.size < 0)
352 atom.size = 0x7fffffffffffffffLL;
5ca1d879
ZK
353 while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
354 a.size = atom.size;
355 a.type=0L;
356 if(atom.size >= 8) {
357 a.size = get_be32(pb);
358 a.type = get_le32(pb);
6cea494e 359 }
5cd62665 360 total_size += 8;
5ca1d879 361 a.offset += 8;
baf25c9d 362 //av_log(NULL, AV_LOG_DEBUG, "type: %08x %.4s sz: %Lx %Lx %Lx\n", type, (char*)&type, size, atom.size, total_size);
5ca1d879
ZK
363 if (a.size == 1) { /* 64 bit extended size */
364 a.size = get_be64(pb) - 8;
365 a.offset += 8;
366 total_size += 8;
6cea494e 367 }
5ca1d879
ZK
368 if (a.size == 0) {
369 a.size = atom.size - total_size;
370 if (a.size <= 8)
5cd62665
ZK
371 break;
372 }
5ca1d879
ZK
373 for (i = 0; c->parse_table[i].type != 0L
374 && c->parse_table[i].type != a.type; i++)
5cd62665
ZK
375 /* empty */;
376
5ca1d879 377 a.size -= 8;
568e18b1
MN
378
379 if(a.size < 0)
380 break;
381
baf25c9d 382// av_log(NULL, AV_LOG_DEBUG, " i=%ld\n", i);
b6a17df4 383 if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
5ca1d879 384// url_seek(pb, atom.offset+atom.size, SEEK_SET);
6cea494e 385#ifdef DEBUG
5ca1d879 386 print_atom("unknown", a);
6cea494e 387#endif
5ca1d879 388 url_fskip(pb, a.size);
b6a17df4
ZK
389 } else {
390#ifdef DEBUG
391 //char b[5] = { type & 0xff, (type >> 8) & 0xff, (type >> 16) & 0xff, (type >> 24) & 0xff, 0 };
392 //print_atom(b, type, offset, size);
393#endif
5ca1d879 394 err = (c->parse_table[i].func)(c, pb, a);
b6a17df4 395 }
6cea494e 396
5ca1d879
ZK
397 a.offset += a.size;
398 total_size += a.size;
6cea494e
ZK
399 }
400
5ca1d879 401 if (!err && total_size < atom.size && atom.size < 0x7ffff) {
baf25c9d 402 //av_log(NULL, AV_LOG_DEBUG, "RESET %Ld %Ld err:%d\n", atom.size, total_size, err);
5ca1d879 403 url_fskip(pb, atom.size - total_size);
5cd62665
ZK
404 }
405
6cea494e
ZK
406#ifdef DEBUG
407 debug_indent--;
408#endif
409 return err;
410}
411
5ca1d879 412static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 413{
5ca1d879
ZK
414 unsigned int len;
415 MOV_ctab_t *t;
568e18b1
MN
416#if 1
417 url_fskip(pb, atom.size); // for now
418#else
419 VERY VERY BROKEN, NEVER execute this, needs rewrite
5ca1d879
ZK
420 c->ctab = av_realloc(c->ctab, ++c->ctab_size);
421 t = c->ctab[c->ctab_size];
422 t->seed = get_be32(pb);
423 t->flags = get_be16(pb);
424 t->size = get_be16(pb) + 1;
425 len = 2 * t->size * 4;
426 if (len > 0) {
427 t->clrs = av_malloc(len); // 16bit A R G B
428 if (t->clrs)
429 get_buffer(pb, t->clrs, len);
3ffe3793 430 }
568e18b1 431#endif
5cd62665 432
0147f198
FR
433 return 0;
434}
435
5ca1d879 436static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 437{
5ca1d879 438 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
3ffe3793 439 int len = 0;
0c1a9eda 440 uint32_t type;
0c1a9eda 441 uint32_t ctype;
b6a17df4 442
5ca1d879 443 print_atom("hdlr", atom);
6cea494e
ZK
444
445 get_byte(pb); /* version */
446 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
447
448 /* component type */
449 ctype = get_le32(pb);
450 type = get_le32(pb); /* component subtype */
451
452#ifdef DEBUG
baf25c9d
GC
453 av_log(NULL, AV_LOG_DEBUG, "ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
454 av_log(NULL, AV_LOG_DEBUG, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
6cea494e
ZK
455#endif
456#ifdef DEBUG
457/* XXX: yeah this is ugly... */
458 if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
459 if(type == MKTAG('v', 'i', 'd', 'e'))
460 puts("hdlr: vide");
461 else if(type == MKTAG('s', 'o', 'u', 'n'))
462 puts("hdlr: soun");
463 } else if(ctype == 0) { /* MP4 */
464 if(type == MKTAG('v', 'i', 'd', 'e'))
465 puts("hdlr: vide");
466 else if(type == MKTAG('s', 'o', 'u', 'n'))
467 puts("hdlr: soun");
468 else if(type == MKTAG('o', 'd', 's', 'm'))
469 puts("hdlr: odsm");
470 else if(type == MKTAG('s', 'd', 's', 'm'))
471 puts("hdlr: sdsm");
472 } else puts("hdlr: meta");
473#endif
474
475 if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
0147f198
FR
476 /* helps parsing the string hereafter... */
477 c->mp4 = 0;
6cea494e
ZK
478 if(type == MKTAG('v', 'i', 'd', 'e'))
479 st->codec.codec_type = CODEC_TYPE_VIDEO;
480 else if(type == MKTAG('s', 'o', 'u', 'n'))
481 st->codec.codec_type = CODEC_TYPE_AUDIO;
482 } else if(ctype == 0) { /* MP4 */
0147f198
FR
483 /* helps parsing the string hereafter... */
484 c->mp4 = 1;
6cea494e
ZK
485 if(type == MKTAG('v', 'i', 'd', 'e'))
486 st->codec.codec_type = CODEC_TYPE_VIDEO;
487 else if(type == MKTAG('s', 'o', 'u', 'n'))
488 st->codec.codec_type = CODEC_TYPE_AUDIO;
489 }
490 get_be32(pb); /* component manufacture */
491 get_be32(pb); /* component flags */
492 get_be32(pb); /* component flags mask */
493
5ca1d879 494 if(atom.size <= 24)
6cea494e
ZK
495 return 0; /* nothing left to read */
496 /* XXX: MP4 uses a C string, not a pascal one */
497 /* component name */
0147f198
FR
498
499 if(c->mp4) {
500 /* .mp4: C string */
5ca1d879 501 while(get_byte(pb) && (++len < (atom.size - 24)));
0147f198
FR
502 } else {
503 /* .mov: PASCAL string */
9ed83b0a
ZK
504#ifdef DEBUG
505 char* buf;
506#endif
0147f198 507 len = get_byte(pb);
5ca1d879 508#ifdef DEBUG
b6a17df4
ZK
509 buf = (uint8_t*) av_malloc(len+1);
510 if (buf) {
511 get_buffer(pb, buf, len);
b6a17df4 512 buf[len] = '\0';
baf25c9d 513 av_log(NULL, AV_LOG_DEBUG, "**buf='%s'\n", buf);
b6a17df4
ZK
514 av_free(buf);
515 } else
6cea494e 516#endif
5ca1d879 517 url_fskip(pb, len);
6cea494e 518 }
5cd62665 519
3c13647a 520 url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
6cea494e
ZK
521 return 0;
522}
523
5ca1d879 524static int mov_mp4_read_descr_len(ByteIOContext *pb)
0e7eed09 525{
5cd62665 526 int len = 0;
5ca1d879
ZK
527 int count = 4;
528 while (count--) {
5cd62665
ZK
529 int c = get_byte(pb);
530 len = (len << 7) | (c & 0x7f);
5ca1d879
ZK
531 if (!(c & 0x80))
532 break;
0e7eed09
FB
533 }
534 return len;
535}
536
5ca1d879 537static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
0e7eed09
FB
538{
539 int len;
540 *tag = get_byte(pb);
5ca1d879 541 len = mov_mp4_read_descr_len(pb);
0e7eed09 542#ifdef DEBUG
baf25c9d 543 av_log(NULL, AV_LOG_DEBUG, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
0e7eed09
FB
544#endif
545 return len;
546}
547
5cd62665
ZK
548static inline unsigned int get_be24(ByteIOContext *s)
549{
550 unsigned int val;
551 val = get_byte(s) << 16;
552 val |= get_byte(s) << 8;
553 val |= get_byte(s);
554 return val;
555}
556
5ca1d879 557static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
5cd62665 558{
5cd62665
ZK
559 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
560 MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
5ca1d879 561 int64_t start_pos = url_ftell(pb);
5cd62665 562 int tag, len;
b6a17df4 563
5ca1d879 564 print_atom("esds", atom);
5cd62665
ZK
565
566 /* Well, broken but suffisant for some MP4 streams */
567 get_be32(pb); /* version + flags */
5ca1d879 568 len = mov_mp4_read_descr(pb, &tag);
5cd62665
ZK
569 if (tag == MP4ESDescrTag) {
570 get_be16(pb); /* ID */
571 get_byte(pb); /* priority */
572 } else
573 get_be16(pb); /* ID */
574
5ca1d879 575 len = mov_mp4_read_descr(pb, &tag);
5cd62665
ZK
576 if (tag == MP4DecConfigDescrTag) {
577 sc->esds.object_type_id = get_byte(pb);
5ca1d879
ZK
578 sc->esds.stream_type = get_byte(pb);
579 sc->esds.buffer_size_db = get_be24(pb);
5cd62665
ZK
580 sc->esds.max_bitrate = get_be32(pb);
581 sc->esds.avg_bitrate = get_be32(pb);
582
5ca1d879 583 len = mov_mp4_read_descr(pb, &tag);
baf25c9d 584 //av_log(NULL, AV_LOG_DEBUG, "LEN %d TAG %d m:%d a:%d\n", len, tag, sc->esds.max_bitrate, sc->esds.avg_bitrate);
5cd62665
ZK
585 if (tag == MP4DecSpecificDescrTag) {
586#ifdef DEBUG
baf25c9d 587 av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
5cd62665 588#endif
3129cd01 589 st->codec.extradata = (uint8_t*) av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
5ca1d879
ZK
590 if (st->codec.extradata) {
591 get_buffer(pb, st->codec.extradata, len);
592 st->codec.extradata_size = len;
5cd62665
ZK
593 }
594 }
595 }
596 /* in any case, skip garbage */
5ca1d879 597 url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
5cd62665
ZK
598 return 0;
599}
600
5ca1d879
ZK
601/* this atom contains actual media data */
602static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 603{
5ca1d879
ZK
604 print_atom("mdat", atom);
605
606 if(atom.size == 0) /* wrong one (MP4) */
607 return 0;
608 c->found_mdat=1;
609 c->mdat_offset = atom.offset;
610 c->mdat_size = atom.size;
611 if(c->found_moov)
612 return 1; /* found both, just go */
613 url_fskip(pb, atom.size);
614 return 0; /* now go for moov */
615}
616
617/* this atom should contain all header atoms */
618static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
619{
620 int err;
b6a17df4 621
5ca1d879 622 print_atom("moov", atom);
b6a17df4 623
5ca1d879
ZK
624 err = mov_read_default(c, pb, atom);
625 /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
626 /* so we don't parse the whole file if over a network */
627 c->found_moov=1;
628 if(c->found_mdat)
629 return 1; /* found both, just go */
630 return 0; /* now go for mdat */
631}
632
633
634static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
635{
5ca1d879
ZK
636 print_atom("mdhd", atom);
637
638 get_byte(pb); /* version */
639
640 get_byte(pb); get_byte(pb);
641 get_byte(pb); /* flags */
642
643 get_be32(pb); /* creation time */
644 get_be32(pb); /* modification time */
645
baf25c9d 646 c->streams[c->fc->nb_streams-1]->time_scale = get_be32(pb);
5ca1d879
ZK
647
648#ifdef DEBUG
baf25c9d 649 av_log(NULL, AV_LOG_DEBUG, "track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->time_scale); /* time scale */
5ca1d879
ZK
650#endif
651 get_be32(pb); /* duration */
652
653 get_be16(pb); /* language */
654 get_be16(pb); /* quality */
655
656 return 0;
657}
658
659static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
660{
661 print_atom("mvhd", atom);
662
663 get_byte(pb); /* version */
664 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
665
666 get_be32(pb); /* creation time */
667 get_be32(pb); /* modification time */
668 c->time_scale = get_be32(pb); /* time scale */
669#ifdef DEBUG
baf25c9d 670 av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
5ca1d879
ZK
671#endif
672 c->duration = get_be32(pb); /* duration */
673 get_be32(pb); /* preferred scale */
674
675 get_be16(pb); /* preferred volume */
676
677 url_fskip(pb, 10); /* reserved */
678
679 url_fskip(pb, 36); /* display matrix */
680
681 get_be32(pb); /* preview time */
682 get_be32(pb); /* preview duration */
683 get_be32(pb); /* poster time */
684 get_be32(pb); /* selection time */
685 get_be32(pb); /* selection duration */
686 get_be32(pb); /* current time */
687 get_be32(pb); /* next track ID */
688
689 return 0;
690}
691
9ed83b0a
ZK
692static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
693{
694 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
695
568e18b1
MN
696 if((uint64_t)atom.size > (1<<30))
697 return -1;
698
9ed83b0a
ZK
699 // currently SVQ3 decoder expect full STSD header - so let's fake it
700 // this should be fixed and just SMI header should be passed
701 av_free(st->codec.extradata);
702 st->codec.extradata_size = 0x5a + atom.size;
3129cd01 703 st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
9ed83b0a
ZK
704
705 if (st->codec.extradata) {
9ed83b0a
ZK
706 strcpy(st->codec.extradata, "SVQ3"); // fake
707 get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
baf25c9d 708 //av_log(NULL, AV_LOG_DEBUG, "Reading SMI %Ld %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
9ed83b0a
ZK
709 } else
710 url_fskip(pb, atom.size);
711
712 return 0;
713}
5ca1d879 714
169eb021
MM
715static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
716{
717 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
718
568e18b1
MN
719 if((uint64_t)atom.size > (1<<30))
720 return -1;
721
169eb021
MM
722 av_free(st->codec.extradata);
723
724 st->codec.extradata_size = atom.size;
725 st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
726
727 if (st->codec.extradata) {
728 get_buffer(pb, st->codec.extradata, atom.size);
729 } else
730 url_fskip(pb, atom.size);
731
732 return 0;
733}
734
5ca1d879
ZK
735static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
736{
737 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
738 MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
568e18b1 739 unsigned int i, entries;
5ca1d879
ZK
740
741 print_atom("stco", atom);
742
743 get_byte(pb); /* version */
744 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
745
746 entries = get_be32(pb);
568e18b1
MN
747
748 if(entries >= UINT_MAX/sizeof(int64_t))
749 return -1;
750
5ca1d879
ZK
751 sc->chunk_count = entries;
752 sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
753 if (!sc->chunk_offsets)
754 return -1;
755 if (atom.type == MKTAG('s', 't', 'c', 'o')) {
756 for(i=0; i<entries; i++) {
757 sc->chunk_offsets[i] = get_be32(pb);
758 }
759 } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
760 for(i=0; i<entries; i++) {
761 sc->chunk_offsets[i] = get_be64(pb);
762 }
763 } else
764 return -1;
765#ifdef DEBUG
766/*
767 for(i=0; i<entries; i++) {
baf25c9d 768 av_log(NULL, AV_LOG_DEBUG, "chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
5ca1d879
ZK
769 }
770*/
771#endif
772 return 0;
773}
774
775static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
776{
777 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
fd6e513e 778 //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
5ca1d879
ZK
779 int entries, frames_per_sample;
780 uint32_t format;
53ffdd14 781 uint8_t codec_name[32];
5ca1d879 782
b595afaa
MM
783 /* for palette traversal */
784 int color_depth;
785 int color_start;
786 int color_count;
787 int color_end;
788 int color_index;
789 int color_dec;
790 int color_greyscale;
791 unsigned char *color_table;
792 int j;
793 unsigned char r, g, b;
794
5ca1d879 795 print_atom("stsd", atom);
6cea494e
ZK
796
797 get_byte(pb); /* version */
798 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
799
6cea494e
ZK
800 entries = get_be32(pb);
801
891f64b3 802 while(entries--) { //Parsing Sample description table
b6a17df4 803 enum CodecID id;
5ca1d879 804 int size = get_be32(pb); /* size */
6cea494e 805 format = get_le32(pb); /* data format */
5cd62665 806
6cea494e
ZK
807 get_be32(pb); /* reserved */
808 get_be16(pb); /* reserved */
809 get_be16(pb); /* index */
0e7eed09
FB
810
811 /* for MPEG4: set codec type by looking for it */
812 id = codec_get_id(mov_video_tags, format);
813 if (id >= 0) {
814 AVCodec *codec;
b6a17df4 815 codec = avcodec_find_decoder(id);
0e7eed09 816 if (codec)
b6a17df4 817 st->codec.codec_type = codec->type;
0e7eed09
FB
818 }
819#ifdef DEBUG
baf25c9d 820 av_log(NULL, AV_LOG_DEBUG, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
5cd62665 821 size,
0e7eed09
FB
822 (format >> 0) & 0xff,
823 (format >> 8) & 0xff,
824 (format >> 16) & 0xff,
825 (format >> 24) & 0xff,
826 st->codec.codec_type);
827#endif
5cd62665 828 st->codec.codec_tag = format;
5ca1d879
ZK
829 if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
830 MOV_atom_t a = { 0, 0, 0 };
831 st->codec.codec_id = id;
6cea494e
ZK
832 get_be16(pb); /* version */
833 get_be16(pb); /* revision level */
834 get_be32(pb); /* vendor */
835 get_be32(pb); /* temporal quality */
836 get_be32(pb); /* spacial quality */
837 st->codec.width = get_be16(pb); /* width */
838 st->codec.height = get_be16(pb); /* height */
0e7eed09
FB
839#if 1
840 if (st->codec.codec_id == CODEC_ID_MPEG4) {
841 /* in some MPEG4 the width/height are not correct, so
842 we ignore this info */
843 st->codec.width = 0;
844 st->codec.height = 0;
845 }
846#endif
6cea494e
ZK
847 get_be32(pb); /* horiz resolution */
848 get_be32(pb); /* vert resolution */
849 get_be32(pb); /* data size, always 0 */
5cd62665 850 frames_per_sample = get_be16(pb); /* frames per samples */
6cea494e 851#ifdef DEBUG
baf25c9d 852 av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
6cea494e 853#endif
53ffdd14
RG
854 get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
855 if (codec_name[0] <= 31) {
856 memcpy(st->codec.codec_name, &codec_name[1],codec_name[0]);
857 st->codec.codec_name[codec_name[0]] = 0;
858 }
5cd62665
ZK
859
860 st->codec.bits_per_sample = get_be16(pb); /* depth */
861 st->codec.color_table_id = get_be16(pb); /* colortable id */
6cea494e 862
14342fd5 863/* These are set in mov_read_stts and might already be set!
14bea432
MN
864 st->codec.frame_rate = 25;
865 st->codec.frame_rate_base = 1;
14342fd5 866*/
5ca1d879 867 size -= (16+8*4+2+32+2*2);
5cd62665
ZK
868#if 0
869 while (size >= 8) {
5ca1d879 870 MOV_atom_t a;
0c1a9eda 871 int64_t start_pos;
5cd62665 872
5ca1d879
ZK
873 a.size = get_be32(pb);
874 a.type = get_le32(pb);
5cd62665 875 size -= 8;
0e7eed09 876#ifdef DEBUG
baf25c9d 877 av_log(NULL, AV_LOG_DEBUG, "VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
5ca1d879
ZK
878 (a.type >> 0) & 0xff,
879 (a.type >> 8) & 0xff,
880 (a.type >> 16) & 0xff,
881 (a.type >> 24) & 0xff,
882 a.size, size);
0e7eed09
FB
883#endif
884 start_pos = url_ftell(pb);
885
5ca1d879 886 switch(a.type) {
0e7eed09
FB
887 case MKTAG('e', 's', 'd', 's'):
888 {
889 int tag, len;
890 /* Well, broken but suffisant for some MP4 streams */
891 get_be32(pb); /* version + flags */
5ca1d879 892 len = mov_mp4_read_descr(pb, &tag);
0e7eed09
FB
893 if (tag == 0x03) {
894 /* MP4ESDescrTag */
895 get_be16(pb); /* ID */
896 get_byte(pb); /* priority */
5ca1d879 897 len = mov_mp4_read_descr(pb, &tag);
0e7eed09
FB
898 if (tag != 0x04)
899 goto fail;
900 /* MP4DecConfigDescrTag */
901 get_byte(pb); /* objectTypeId */
902 get_be32(pb); /* streamType + buffer size */
5cd62665 903 get_be32(pb); /* max bit rate */
0e7eed09 904 get_be32(pb); /* avg bit rate */
891f64b3 905 len = mov_mp4_read_descr(pb, &tag);
0e7eed09
FB
906 if (tag != 0x05)
907 goto fail;
908 /* MP4DecSpecificDescrTag */
909#ifdef DEBUG
baf25c9d 910 av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
0e7eed09
FB
911#endif
912 sc->header_data = av_mallocz(len);
913 if (sc->header_data) {
914 get_buffer(pb, sc->header_data, len);
5cd62665 915 sc->header_len = len;
0e7eed09
FB
916 }
917 }
918 /* in any case, skip garbage */
919 }
920 break;
921 default:
922 break;
923 }
5cd62665 924 fail:
baf25c9d 925 av_log(NULL, AV_LOG_DEBUG, "ATOMENEWSIZE %Ld %d\n", atom.size, url_ftell(pb) - start_pos);
5ca1d879
ZK
926 if (atom.size > 8) {
927 url_fskip(pb, (atom.size - 8) -
5cd62665 928 ((url_ftell(pb) - start_pos)));
5ca1d879 929 size -= atom.size - 8;
5cd62665
ZK
930 }
931 }
0e7eed09
FB
932 if (size > 0) {
933 /* unknown extension */
934 url_fskip(pb, size);
935 }
5cd62665 936#else
b595afaa
MM
937
938 /* figure out the palette situation */
939 color_depth = st->codec.bits_per_sample & 0x1F;
940 color_greyscale = st->codec.bits_per_sample & 0x20;
941
942 /* if the depth is 2, 4, or 8 bpp, file is palettized */
943 if ((color_depth == 2) || (color_depth == 4) ||
944 (color_depth == 8)) {
945
946 if (color_greyscale) {
947
948 /* compute the greyscale palette */
949 color_count = 1 << color_depth;
950 color_index = 255;
951 color_dec = 256 / (color_count - 1);
952 for (j = 0; j < color_count; j++) {
953 r = g = b = color_index;
954 c->palette_control.palette[j] =
955 (r << 16) | (g << 8) | (b);
956 color_index -= color_dec;
957 if (color_index < 0)
958 color_index = 0;
959 }
960
961 } else if (st->codec.color_table_id & 0x08) {
962
963 /* if flag bit 3 is set, use the default palette */
964 color_count = 1 << color_depth;
965 if (color_depth == 2)
a90466f7 966 color_table = ff_qt_default_palette_4;
b595afaa 967 else if (color_depth == 4)
a90466f7 968 color_table = ff_qt_default_palette_16;
b595afaa 969 else
a90466f7 970 color_table = ff_qt_default_palette_256;
b595afaa
MM
971
972 for (j = 0; j < color_count; j++) {
973 r = color_table[j * 4 + 0];
974 g = color_table[j * 4 + 1];
975 b = color_table[j * 4 + 2];
976 c->palette_control.palette[j] =
977 (r << 16) | (g << 8) | (b);
978 }
979
980 } else {
981
982 /* load the palette from the file */
983 color_start = get_be32(pb);
984 color_count = get_be16(pb);
985 color_end = get_be16(pb);
986 for (j = color_start; j <= color_end; j++) {
987 /* each R, G, or B component is 16 bits;
988 * only use the top 8 bits; skip alpha bytes
989 * up front */
990 get_byte(pb);
991 get_byte(pb);
992 r = get_byte(pb);
993 get_byte(pb);
994 g = get_byte(pb);
995 get_byte(pb);
996 b = get_byte(pb);
997 get_byte(pb);
998 c->palette_control.palette[j] =
999 (r << 16) | (g << 8) | (b);
1000 }
1001 }
1002
1003 st->codec.palctrl = &c->palette_control;
1004 st->codec.palctrl->palette_changed = 1;
1005 } else
1006 st->codec.palctrl = NULL;
1007
5ca1d879
ZK
1008 a.size = size;
1009 mov_read_default(c, pb, a);
5cd62665
ZK
1010#endif
1011 } else {
891f64b3 1012 st->codec.codec_id = codec_get_id(mov_audio_tags, format);
d663a1fd 1013 if(st->codec.codec_id==CODEC_ID_AMR_NB || st->codec.codec_id==CODEC_ID_AMR_WB) //from TS26.244
891f64b3 1014 {
1015#ifdef DEBUG
baf25c9d 1016 av_log(NULL, AV_LOG_DEBUG, "AMR-NB or AMR-WB audio identified!!\n");
891f64b3 1017#endif
1018 get_be32(pb);get_be32(pb); //Reserved_8
1019 get_be16(pb);//Reserved_2
1020 get_be16(pb);//Reserved_2
1021 get_be32(pb);//Reserved_4
1022 get_be16(pb);//TimeScale
1023 get_be16(pb);//Reserved_2
1024
1025 //AMRSpecificBox.(10 bytes)
d663a1fd 1026
891f64b3 1027 get_be32(pb); //size
891f64b3 1028 get_be32(pb); //type=='damr'
891f64b3 1029 get_be32(pb); //vendor
1030 get_byte(pb); //decoder version
1031 get_be16(pb); //mode_set
1032 get_byte(pb); //mode_change_period
1033 get_byte(pb); //frames_per_sample
6cea494e 1034
25c4950e 1035 st->duration = AV_NOPTS_VALUE;//Not possible to get from this info, must count number of AMR frames
d663a1fd
MN
1036 if(st->codec.codec_id==CODEC_ID_AMR_NB)
1037 {
1038 st->codec.sample_rate=8000;
1039 st->codec.channels=1;
1040 }
1041 else //AMR-WB
1042 {
1043 st->codec.sample_rate=16000;
1044 st->codec.channels=1;
1045 }
891f64b3 1046 st->codec.bits_per_sample=16;
1047 st->codec.bit_rate=0; /*It is not possible to tell this before we have
1048 an audio frame and even then every frame can be different*/
5cd62665 1049 }
14342fd5
JC
1050 else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 's' ))
1051 {
1052 //This is some stuff for the hint track, lets ignore it!
1053 //Do some mp4 auto detect.
1054 c->mp4=1;
1055 size-=(16);
1056 url_fskip(pb, size); /* The mp4s atom also contians a esds atom that we can skip*/
1057 }
2768b0d9
TR
1058 else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 'a' ))
1059 {
1060 /* Handle mp4 audio tag */
1061 get_be32(pb); /* version */
1062 get_be32(pb);
1063 st->codec.channels = get_be16(pb); /* channels */
1064 st->codec.bits_per_sample = get_be16(pb); /* bits per sample */
1065 get_be32(pb);
1066 st->codec.sample_rate = get_be16(pb); /* sample rate, not always correct */
1067 get_be16(pb);
1068 c->mp4=1;
3ec34bfd 1069 {
2768b0d9
TR
1070 MOV_atom_t a = { format, url_ftell(pb), size - (20 + 20 + 8) };
1071 mov_read_default(c, pb, a);
3ec34bfd 1072 }
2768b0d9
TR
1073 /* Get correct sample rate from extradata */
1074 if(st->codec.extradata_size) {
1075 const int samplerate_table[] = {
1076 96000, 88200, 64000, 48000, 44100, 32000,
1077 24000, 22050, 16000, 12000, 11025, 8000,
1078 7350, 0, 0, 0
1079 };
1080 unsigned char *px = st->codec.extradata;
1081 // 5 bits objectTypeIndex, 4 bits sampleRateIndex, 4 bits channels
1082 int samplerate_index = ((px[0] & 7) << 1) + ((px[1] >> 7) & 1);
1083 st->codec.sample_rate = samplerate_table[samplerate_index];
f2196640 1084 st->codec.channels = (px[1] >> 3) & 15;
2768b0d9
TR
1085 }
1086 }
14342fd5
JC
1087 else if(size>=(16+20))
1088 {//16 bytes read, reading atleast 20 more
c3ea71a0 1089 uint16_t version;
14342fd5 1090#ifdef DEBUG
baf25c9d 1091 av_log(NULL, AV_LOG_DEBUG, "audio size=0x%X\n",size);
14342fd5 1092#endif
c3ea71a0 1093 version = get_be16(pb); /* version */
891f64b3 1094 get_be16(pb); /* revision level */
1095 get_be32(pb); /* vendor */
1096
1097 st->codec.channels = get_be16(pb); /* channel count */
1098 st->codec.bits_per_sample = get_be16(pb); /* sample size */
1099
1100 /* handle specific s8 codec */
1101 get_be16(pb); /* compression id = 0*/
1102 get_be16(pb); /* packet size = 0 */
1103
1104 st->codec.sample_rate = ((get_be32(pb) >> 16));
baf25c9d 1105 //av_log(NULL, AV_LOG_DEBUG, "CODECID %d %d %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);
891f64b3 1106
1107 switch (st->codec.codec_id) {
1108 case CODEC_ID_PCM_S16BE:
1109 if (st->codec.bits_per_sample == 8)
1110 st->codec.codec_id = CODEC_ID_PCM_S8;
1111 /* fall */
1112 case CODEC_ID_PCM_U8:
1113 st->codec.bit_rate = st->codec.sample_rate * 8;
1114 break;
1115 default:
1116 ;
1117 }
14342fd5
JC
1118
1119 //Read QT version 1 fields. In version 0 theese dont exist
1120#ifdef DEBUG
baf25c9d
GC
1121 av_log(NULL, AV_LOG_DEBUG, "version =%d mp4=%d\n",version,c->mp4);
1122 av_log(NULL, AV_LOG_DEBUG, "size-(16+20+16)=%d\n",size-(16+20+16));
14342fd5
JC
1123#endif
1124 if((version==1) && size>=(16+20+16))
1125 {
1126 get_be32(pb); /* samples per packet */
1127 get_be32(pb); /* bytes per packet */
1128 get_be32(pb); /* bytes per frame */
1129 get_be32(pb); /* bytes per sample */
1130 if(size>(16+20+16))
1131 {
1132 //Optional, additional atom-based fields
c3ea71a0 1133 MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
14342fd5 1134#ifdef DEBUG
baf25c9d 1135 av_log(NULL, AV_LOG_DEBUG, "offest=0x%X, sizeleft=%d=0x%x,format=%c%c%c%c\n",(int)url_ftell(pb),size - (16 + 20 + 16 ),size - (16 + 20 + 16 ),
14342fd5
JC
1136 (format >> 0) & 0xff,
1137 (format >> 8) & 0xff,
1138 (format >> 16) & 0xff,
1139 (format >> 24) & 0xff);
1140#endif
14342fd5
JC
1141 mov_read_default(c, pb, a);
1142 }
1143 }
1144 else
1145 {
1146 //We should be down to 0 bytes here, but lets make sure.
1147 size-=(16+20);
1148#ifdef DEBUG
1149 if(size>0)
baf25c9d 1150 av_log(NULL, AV_LOG_DEBUG, "skipping 0x%X bytes\n",size-(16+20));
14342fd5
JC
1151#endif
1152 url_fskip(pb, size);
1153 }
1154 }
1155 else
1156 {
1157 size-=16;
1158 //Unknown size, but lets do our best and skip the rest.
1159#ifdef DEBUG
baf25c9d 1160 av_log(NULL, AV_LOG_DEBUG, "Strange size, skipping 0x%X bytes\n",size);
14342fd5
JC
1161#endif
1162 url_fskip(pb, size);
891f64b3 1163 }
6cea494e 1164 }
6cea494e 1165 }
5cd62665 1166
6cea494e
ZK
1167 return 0;
1168}
1169
5ca1d879 1170static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 1171{
5ca1d879
ZK
1172 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1173 MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
568e18b1 1174 unsigned int i, entries;
b6a17df4 1175
5ca1d879 1176 print_atom("stsc", atom);
5cd62665 1177
6cea494e
ZK
1178 get_byte(pb); /* version */
1179 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1180
1181 entries = get_be32(pb);
568e18b1
MN
1182
1183 if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
1184 return -1;
1185
3ffe3793 1186#ifdef DEBUG
baf25c9d 1187av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
3ffe3793 1188#endif
6cea494e 1189 sc->sample_to_chunk_sz = entries;
b6a17df4
ZK
1190 sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1191 if (!sc->sample_to_chunk)
1192 return -1;
6cea494e
ZK
1193 for(i=0; i<entries; i++) {
1194 sc->sample_to_chunk[i].first = get_be32(pb);
1195 sc->sample_to_chunk[i].count = get_be32(pb);
1196 sc->sample_to_chunk[i].id = get_be32(pb);
1197#ifdef DEBUG
baf25c9d 1198/* av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id); */
6cea494e
ZK
1199#endif
1200 }
1201 return 0;
1202}
1203
247d56f5
BB
1204static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1205{
1206 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1207 MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
568e18b1 1208 unsigned int i, entries;
247d56f5
BB
1209
1210 print_atom("stss", atom);
1211
1212 get_byte(pb); /* version */
1213 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1214
1215 entries = get_be32(pb);
568e18b1
MN
1216
1217 if(entries >= UINT_MAX / sizeof(long))
1218 return -1;
1219
247d56f5
BB
1220 sc->keyframe_count = entries;
1221#ifdef DEBUG
1222 av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1223#endif
1224 sc->keyframes = (long*) av_malloc(entries * sizeof(long));
1225 if (!sc->keyframes)
1226 return -1;
1227 for(i=0; i<entries; i++) {
1228 sc->keyframes[i] = get_be32(pb);
1229#ifdef DEBUG
1230/* av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1231#endif
1232 }
1233 return 0;
1234}
1235
5ca1d879 1236static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
6cea494e 1237{
5ca1d879
ZK
1238 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1239 MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
568e18b1 1240 unsigned int i, entries;
b6a17df4 1241
5ca1d879 1242 print_atom("stsz", atom);
5cd62665 1243
6cea494e
ZK
1244 get_byte(pb); /* version */
1245 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
5cd62665 1246
6cea494e
ZK
1247 sc->sample_size = get_be32(pb);
1248 entries = get_be32(pb);
568e18b1
MN
1249 if(entries >= UINT_MAX / sizeof(long))
1250 return -1;
1251
6cea494e 1252 sc->sample_count = entries;
0147f198 1253#ifdef DEBUG
baf25c9d 1254 av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
0147f198 1255#endif
6cea494e
ZK
1256 if(sc->sample_size)
1257 return 0; /* there isn't any table following */
b6a17df4
ZK
1258 sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
1259 if (!sc->sample_sizes)
1260 return -1;
6cea494e
ZK
1261 for(i=0; i<entries; i++) {
1262 sc->sample_sizes[i] = get_be32(pb);
1263#ifdef DEBUG
7dbab4a9 1264 av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]);
6cea494e
ZK
1265#endif
1266 }
1267 return 0;
1268}
1269
5ca1d879 1270static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
0147f198 1271{
5ca1d879 1272 AVStream *st = c->fc->streams[c->fc->nb_streams-1];
fd6e513e 1273 //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
568e18b1 1274 unsigned int i, entries;
d957696f
MN
1275 int64_t duration=0;
1276 int64_t total_sample_count=0;
b6a17df4 1277
5ca1d879 1278 print_atom("stts", atom);
0147f198
FR
1279
1280 get_byte(pb); /* version */
1281 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1282 entries = get_be32(pb);
cd461d48 1283 if(entries >= UINT_MAX / sizeof(Time2Sample))
568e18b1 1284 return -1;
891f64b3 1285
baf25c9d 1286 c->streams[c->fc->nb_streams-1]->stts_count = entries;
cd461d48 1287 c->streams[c->fc->nb_streams-1]->stts_data = av_malloc(entries * sizeof(Time2Sample));
891f64b3 1288
3ffe3793 1289#ifdef DEBUG
baf25c9d 1290av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
3ffe3793 1291#endif
0147f198 1292 for(i=0; i<entries; i++) {
cd461d48
MN
1293 int sample_duration;
1294 int sample_count;
0147f198 1295
891f64b3 1296 sample_count=get_be32(pb);
0147f198 1297 sample_duration = get_be32(pb);
cd461d48
MN
1298 c->streams[c->fc->nb_streams - 1]->stts_data[i].count= sample_count;
1299 c->streams[c->fc->nb_streams - 1]->stts_data[i].duration= sample_duration;
891f64b3 1300#ifdef DEBUG
baf25c9d 1301 av_log(NULL, AV_LOG_DEBUG, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
891f64b3 1302#endif
1303 duration+=sample_duration*sample_count;
1304 total_sample_count+=sample_count;
1305
1306#if 0 //We calculate an average instead, needed by .mp4-files created with nec e606 3g phone
0147f198
FR
1307
1308 if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
14bea432 1309 st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
baf25c9d 1310 st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
0147f198 1311#ifdef DEBUG
baf25c9d 1312 av_log(NULL, AV_LOG_DEBUG, "VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
0147f198
FR
1313#endif
1314 }
891f64b3 1315#endif
1316 }
1317
14342fd5
JC
1318 /*The stsd atom which contain codec type sometimes comes after the stts so we cannot check for codec_type*/
1319 if(duration>0)
891f64b3 1320 {
d957696f
MN
1321 av_reduce(
1322 &st->codec.frame_rate,
1323 &st->codec.frame_rate_base,
baf25c9d 1324 c->streams[c->fc->nb_streams-1]->time_scale * total_sample_count,
d957696f
MN
1325 duration,
1326 INT_MAX
1327 );
14342fd5 1328
891f64b3 1329#ifdef DEBUG
baf25c9d 1330 av_log(NULL, AV_LOG_DEBUG, "FRAME RATE average (video or audio)= %f (tot sample count= %i ,tot dur= %i timescale=%d)\n", (float)st->codec.frame_rate/st->codec.frame_rate_base,total_sample_count,duration,c->streams[c->fc->nb_streams-1]->time_scale);
891f64b3 1331#endif
0147f198 1332 }
14342fd5
JC
1333 else
1334 {
1335 st->codec.frame_rate_base = 1;
baf25c9d 1336 st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
14342fd5 1337 }
0147f198
FR
1338 return 0;
1339}
1340
5ca1d879
ZK
1341static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1342{
1343 AVStream *st;
1344 MOVStreamContext *sc;
1345
1346 print_atom("trak", atom);
1347
1348 st = av_new_stream(c->fc, c->fc->nb_streams);
1349 if (!st) return -2;
1350 sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
1351 if (!sc) {
1352 av_free(st);
1353 return -1;
1354 }
1355
1356 sc->sample_to_chunk_index = -1;
1357 st->priv_data = sc;
1358 st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
25c4950e
FB
1359 st->start_time = 0; /* XXX: check */
1360 st->duration = (c->duration * (int64_t)AV_TIME_BASE) / c->time_scale;
5ca1d879
ZK
1361 c->streams[c->fc->nb_streams-1] = sc;
1362
1363 return mov_read_default(c, pb, atom);
1364}
1365
1366static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1367{
1368 AVStream *st;
1369
1370 print_atom("tkhd", atom);
1371
1372 st = c->fc->streams[c->fc->nb_streams-1];
1373
1374 get_byte(pb); /* version */
1375
1376 get_byte(pb); get_byte(pb);
1377 get_byte(pb); /* flags */
1378 /*
1379 MOV_TRACK_ENABLED 0x0001
1380 MOV_TRACK_IN_MOVIE 0x0002
1381 MOV_TRACK_IN_PREVIEW 0x0004
1382 MOV_TRACK_IN_POSTER 0x0008
1383 */
1384
1385 get_be32(pb); /* creation time */
1386 get_be32(pb); /* modification time */
1387 st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1388 get_be32(pb); /* reserved */
25c4950e
FB
1389 st->start_time = 0; /* check */
1390 st->duration = (get_be32(pb) * (int64_t)AV_TIME_BASE) / c->time_scale; /* duration */
5ca1d879
ZK
1391 get_be32(pb); /* reserved */
1392 get_be32(pb); /* reserved */
1393
1394 get_be16(pb); /* layer */
1395 get_be16(pb); /* alternate group */
1396 get_be16(pb); /* volume */
1397 get_be16(pb); /* reserved */
1398
1399 url_fskip(pb, 36); /* display matrix */
1400
1401 /* those are fixed-point */
1402 st->codec.width = get_be32(pb) >> 16; /* track width */
1403 st->codec.height = get_be32(pb) >> 16; /* track height */
1404
1405 return 0;
1406}
1407
1408/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1409/* like the files created with Adobe Premiere 5.0, for samples see */
1410/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1411static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1412{
1413 int err;
5ca1d879
ZK
1414
1415#ifdef DEBUG
1416 print_atom("wide", atom);
1417 debug_indent++;
1418#endif
1419 if (atom.size < 8)
1420 return 0; /* continue */
1421 if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1422 url_fskip(pb, atom.size - 4);
1423 return 0;
1424 }
1425 atom.type = get_le32(pb);
1426 atom.offset += 8;
1427 atom.size -= 8;
fd6e513e 1428 if (atom.type != MKTAG('m', 'd', 'a', 't')) {
5ca1d879
ZK
1429 url_fskip(pb, atom.size);
1430 return 0;
1431 }
1432 err = mov_read_mdat(c, pb, atom);
1433#ifdef DEBUG
1434 debug_indent--;
1435#endif
1436 return err;
1437}
1438
1439
0147f198 1440#ifdef CONFIG_ZLIB
0c1a9eda 1441static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
0147f198
FR
1442{
1443 return -1;
1444}
1445
5ca1d879 1446static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
0147f198 1447{
0147f198 1448 ByteIOContext ctx;
b6a17df4
ZK
1449 uint8_t *cmov_data;
1450 uint8_t *moov_data; /* uncompressed data */
0147f198
FR
1451 long cmov_len, moov_len;
1452 int ret;
b6a17df4 1453
5ca1d879 1454 print_atom("cmov", atom);
0147f198
FR
1455
1456 get_be32(pb); /* dcom atom */
1457 if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1458 return -1;
1459 if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
baf25c9d 1460 av_log(NULL, AV_LOG_DEBUG, "unknown compression for cmov atom !");
0147f198
FR
1461 return -1;
1462 }
1463 get_be32(pb); /* cmvd atom */
1464 if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1465 return -1;
1466 moov_len = get_be32(pb); /* uncompressed size */
5ca1d879 1467 cmov_len = atom.size - 6 * 4;
5cd62665 1468
b6a17df4 1469 cmov_data = (uint8_t *) av_malloc(cmov_len);
0147f198
FR
1470 if (!cmov_data)
1471 return -1;
b6a17df4 1472 moov_data = (uint8_t *) av_malloc(moov_len);
0147f198
FR
1473 if (!moov_data) {
1474 av_free(cmov_data);
1475 return -1;
1476 }
1477 get_buffer(pb, cmov_data, cmov_len);
b6a17df4 1478 if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
0147f198
FR
1479 return -1;
1480 if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1481 return -1;
1482 ctx.buf_end = ctx.buffer + moov_len;
5ca1d879
ZK
1483 atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1484 atom.offset = 0;
1485 atom.size = moov_len;
9ed83b0a
ZK
1486#ifdef DEBUG
1487 { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1488#endif
5ca1d879 1489 ret = mov_read_default(c, &ctx, atom);
0147f198
FR
1490 av_free(moov_data);
1491 av_free(cmov_data);
9ed83b0a 1492
0147f198
FR
1493 return ret;
1494}
1495#endif
1496
baf25c9d
GC
1497/* edit list atom */
1498static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1499{
58e555d4 1500 int i, edit_count;
baf25c9d
GC
1501 print_atom("elst", atom);
1502
1503 get_byte(pb); /* version */
1504 get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
58e555d4
MN
1505 edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb); /* entries */
1506
1507 for(i=0; i<edit_count; i++){
1508 get_be32(pb); /* Track duration */
1509 get_be32(pb); /* Media time */
1510 get_be32(pb); /* Media rate */
1511 }
baf25c9d
GC
1512#ifdef DEBUG
1513 av_log(NULL, AV_LOG_DEBUG, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1514#endif
1515 return 0;
1516}
1517
6cea494e
ZK
1518static const MOVParseTableEntry mov_default_parse_table[] = {
1519/* mp4 atoms */
5ca1d879
ZK
1520{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1521{ MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1522{ MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1523{ MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
1524{ MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1525{ MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1526{ MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1527{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
58e555d4 1528{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
5ca1d879
ZK
1529{ MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1530{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1531{ MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1532{ MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1533{ MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1534{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1535{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1536{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1537{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1538{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1539{ MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1540{ MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1541{ MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1542{ MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1543{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1544{ MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1545{ MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1546{ MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
3c13647a 1547{ MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
5ca1d879 1548{ MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
169eb021
MM
1549{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1550{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC },
5ca1d879
ZK
1551{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1552{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1553{ MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1554{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1555{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1556{ MKTAG( 's', 't', 's', 'h' ), mov_read_default },
247d56f5 1557{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
5ca1d879
ZK
1558{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1559{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1560{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1561{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1562{ MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1563{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1564{ MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1565{ MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1566{ MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
1567{ MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1568{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
6cea494e 1569/* extra mp4 */
5ca1d879 1570{ MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
6cea494e 1571/* QT atoms */
5ca1d879
ZK
1572{ MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1573{ MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1574{ MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1575{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1576{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1577{ MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1578{ MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1579{ MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1580{ MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1581{ MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1582{ MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1583{ MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1584{ MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1585{ MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1586{ MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1587{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1588//{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
0147f198 1589#ifdef CONFIG_ZLIB
5ca1d879 1590{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
0147f198 1591#else
5ca1d879 1592{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
0147f198 1593#endif
5ca1d879 1594{ 0L, mov_read_leaf }
6cea494e
ZK
1595};
1596
1597static void mov_free_stream_context(MOVStreamContext *sc)
1598{
1599 if(sc) {
1ea4f593
FB
1600 av_free(sc->chunk_offsets);
1601 av_free(sc->sample_to_chunk);
5cd62665 1602 av_free(sc->sample_sizes);
247d56f5 1603 av_free(sc->keyframes);
0e7eed09 1604 av_free(sc->header_data);
baf25c9d 1605 av_free(sc->stts_data);
1ea4f593 1606 av_free(sc);
6cea494e
ZK
1607 }
1608}
1609
5ca1d879 1610static inline uint32_t mov_to_tag(uint8_t *buf)
0e7eed09 1611{
5ca1d879 1612 return MKTAG(buf[0], buf[1], buf[2], buf[3]);
0e7eed09
FB
1613}
1614
5cd62665 1615static inline uint32_t to_be32(uint8_t *buf)
0e7eed09
FB
1616{
1617 return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1618}
1619
b6a17df4 1620/* XXX: is it sufficient ? */
c9a65ca8
FB
1621static int mov_probe(AVProbeData *p)
1622{
0e7eed09
FB
1623 unsigned int offset;
1624 uint32_t tag;
2497479f 1625 int score = 0;
3ffe3793 1626
c9a65ca8
FB
1627 /* check file header */
1628 if (p->buf_size <= 12)
1629 return 0;
0e7eed09
FB
1630 offset = 0;
1631 for(;;) {
1632 /* ignore invalid offset */
1633 if ((offset + 8) > (unsigned int)p->buf_size)
2497479f 1634 return score;
5ca1d879 1635 tag = mov_to_tag(p->buf + offset + 4);
0e7eed09 1636 switch(tag) {
2497479f 1637 /* check for obvious tags */
0e7eed09 1638 case MKTAG( 'm', 'o', 'o', 'v' ):
8b879f18
FR
1639 case MKTAG( 'm', 'd', 'a', 't' ):
1640 case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
bc634f6f 1641 case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
3ffe3793 1642 return AVPROBE_SCORE_MAX;
2497479f
FR
1643 /* those are more common words, so rate then a bit less */
1644 case MKTAG( 'w', 'i', 'd', 'e' ):
1645 case MKTAG( 'f', 'r', 'e', 'e' ):
1646 case MKTAG( 'j', 'u', 'n', 'k' ):
1647 case MKTAG( 'p', 'i', 'c', 't' ):
1648 return AVPROBE_SCORE_MAX - 5;
0e7eed09 1649 case MKTAG( 'f', 't', 'y', 'p' ):
5ca1d879 1650 case MKTAG( 's', 'k', 'i', 'p' ):
14342fd5 1651 offset = to_be32(p->buf+offset) + offset;
2497479f
FR
1652 /* if we only find those cause probedata is too small at least rate them */
1653 score = AVPROBE_SCORE_MAX - 50;
0e7eed09
FB
1654 break;
1655 default:
1656 /* unrecognized tag */
2497479f 1657 return score;
0e7eed09 1658 }
3ffe3793 1659 }
2497479f 1660 return score;
c9a65ca8
FB
1661}
1662
a266644f 1663static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
6cea494e 1664{
b6a17df4 1665 MOVContext *mov = (MOVContext *) s->priv_data;
6cea494e 1666 ByteIOContext *pb = &s->pb;
684f44d9 1667 int i, j, nb, err;
5ca1d879 1668 MOV_atom_t atom = { 0, 0, 0 };
6cea494e 1669
6cea494e 1670 mov->fc = s;
b6a17df4 1671 mov->parse_table = mov_default_parse_table;
c9a65ca8
FB
1672#if 0
1673 /* XXX: I think we should auto detect */
1674 if(s->iformat->name[1] == 'p')
6cea494e 1675 mov->mp4 = 1;
c9a65ca8 1676#endif
6cea494e 1677 if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
5ca1d879 1678 atom.size = url_filesize(url_fileno(pb));
6cea494e 1679 else
9ed83b0a 1680 atom.size = 0x7FFFFFFFFFFFFFFFLL;
6cea494e
ZK
1681
1682#ifdef DEBUG
baf25c9d 1683 av_log(NULL, AV_LOG_DEBUG, "filesz=%Ld\n", atom.size);
6cea494e
ZK
1684#endif
1685
1686 /* check MOV header */
5ca1d879 1687 err = mov_read_default(mov, pb, atom);
25fa62e1 1688 if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
bc874dae 1689 av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%lld\n",
25fa62e1
ZK
1690 err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1691 return -1;
6cea494e
ZK
1692 }
1693#ifdef DEBUG
baf25c9d 1694 av_log(NULL, AV_LOG_DEBUG, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
6cea494e
ZK
1695#endif
1696 /* some cleanup : make sure we are on the mdat atom */
1697 if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1698 url_fseek(pb, mov->mdat_offset, SEEK_SET);
1699
1700 mov->next_chunk_offset = mov->mdat_offset; /* initialise reading */
1701
1702#ifdef DEBUG
baf25c9d 1703 av_log(NULL, AV_LOG_DEBUG, "mdat_reset_offset=%d\n", (int) url_ftell(pb));
6cea494e
ZK
1704#endif
1705
1706#ifdef DEBUG
baf25c9d 1707 av_log(NULL, AV_LOG_DEBUG, "streams= %d\n", s->nb_streams);
6cea494e
ZK
1708#endif
1709 mov->total_streams = nb = s->nb_streams;
5ca1d879 1710
6cea494e
ZK
1711#if 1
1712 for(i=0; i<s->nb_streams;) {
1713 if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
1ea4f593 1714 av_free(s->streams[i]);
6cea494e
ZK
1715 for(j=i+1; j<s->nb_streams; j++)
1716 s->streams[j-1] = s->streams[j];
1717 s->nb_streams--;
1718 } else
1719 i++;
1720 }
1721 for(i=0; i<s->nb_streams;i++) {
1722 MOVStreamContext *sc;
1723 sc = (MOVStreamContext *)s->streams[i]->priv_data;
1724 sc->ffindex = i;
1725 sc->is_ff_stream = 1;
1726 }
1727#endif
1728#ifdef DEBUG
baf25c9d 1729 av_log(NULL, AV_LOG_DEBUG, "real streams= %d\n", s->nb_streams);
6cea494e
ZK
1730#endif
1731 return 0;
1732}
1733
1734/* Yes, this is ugly... I didn't write the specs of QT :p */
1735/* XXX:remove useless commented code sometime */
a266644f 1736static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
6cea494e 1737{
b6a17df4 1738 MOVContext *mov = (MOVContext *) s->priv_data;
0e7eed09 1739 MOVStreamContext *sc;
9ed83b0a 1740 int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
247d56f5 1741 int i, a, b, m;
5cd62665 1742 int size;
7619ed2b 1743 int idx;
6cea494e 1744 size = 0x0FFFFFFF;
5cd62665 1745
3ffe3793
FR
1746#ifdef MOV_SPLIT_CHUNKS
1747 if (mov->partial) {
5cd62665
ZK
1748 sc = mov->partial;
1749 idx = sc->sample_to_chunk_index;
1750
3ffe3793 1751 if (idx < 0) return 0;
7dbab4a9
FR
1752#ifdef DEBUG
1753 fprintf(stderr, "sc[ffid %d]->sample_size = %d\n", sc->ffindex, sc->sample_size);
1754#endif
92e51b66
RG
1755 // sample_size is not always correct for audio. Quicktime ignores this value and
1756 // computes it differently.
1757 if(s->streams[sc->ffindex]->codec.codec_type == CODEC_TYPE_VIDEO)
1758 size = sc->sample_size?sc->sample_size:sc->sample_sizes[sc->current_sample];
5cd62665
ZK
1759 sc->current_sample++;
1760 sc->left_in_chunk--;
3ffe3793 1761
5cd62665 1762 if (sc->left_in_chunk <= 0)
3ffe3793
FR
1763 mov->partial = 0;
1764 offset = mov->next_chunk_offset;
1765 /* extract the sample */
1766
1767 goto readchunk;
1768 }
1769#endif
1770
6cea494e 1771again:
5cd62665 1772 sc = 0;
6cea494e 1773 for(i=0; i<mov->total_streams; i++) {
5cd62665 1774 MOVStreamContext *msc = mov->streams[i];
baf25c9d 1775 //av_log(NULL, AV_LOG_DEBUG, "MOCHUNK %ld %d %p pos:%Ld\n", mov->streams[i]->next_chunk, mov->total_streams, mov->streams[i], url_ftell(&s->pb));
5cd62665
ZK
1776 if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
1777 && (msc->chunk_offsets[msc->next_chunk] < offset)) {
1778 sc = msc;
1779 offset = msc->chunk_offsets[msc->next_chunk];
baf25c9d 1780 //av_log(NULL, AV_LOG_DEBUG, "SELETED %Ld i:%d\n", offset, i);
6cea494e 1781 }
6cea494e 1782 }
9ed83b0a 1783 if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
5cd62665
ZK
1784 return -1;
1785
1786 sc->next_chunk++;
1787
3ffe3793 1788 if(mov->next_chunk_offset < offset) { /* some meta data */
6cea494e 1789 url_fskip(&s->pb, (offset - mov->next_chunk_offset));
3ffe3793
FR
1790 mov->next_chunk_offset = offset;
1791 }
1792
baf25c9d 1793//av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
b9866ebc 1794 if(!sc->is_ff_stream || s->streams[sc->ffindex]->discard) {
6cea494e 1795 url_fskip(&s->pb, (offset - mov->next_chunk_offset));
3ffe3793 1796 mov->next_chunk_offset = offset;
9ed83b0a 1797 offset = 0x0FFFFFFFFFFFFFFFLL;
6cea494e
ZK
1798 goto again;
1799 }
6cea494e
ZK
1800
1801 /* now get the chunk size... */
1802
1803 for(i=0; i<mov->total_streams; i++) {
5cd62665
ZK
1804 MOVStreamContext *msc = mov->streams[i];
1805 if ((msc->next_chunk < msc->chunk_count)
1806 && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
1807 size = msc->chunk_offsets[msc->next_chunk] - offset;
6cea494e 1808 }
bc634f6f
ZK
1809
1810#ifdef MOV_MINOLTA_FIX
1811 //Make sure that size is according to sample_size (Needed by .mov files
1812 //created on a Minolta Dimage Xi where audio chunks contains waste data in the end)
1813 //Maybe we should really not only check sc->sample_size, but also sc->sample_sizes
1814 //but I have no such movies
1815 if (sc->sample_size > 0) {
1816 int foundsize=0;
1817 for(i=0; i<(sc->sample_to_chunk_sz); i++) {
92e51b66 1818 if( (sc->sample_to_chunk[i].first)<=(sc->next_chunk) )
bc634f6f 1819 {
cac0a56c
RS
1820 // I can't figure out why for PCM audio sample_size is always 1
1821 // (it should actually be channels*bits_per_second/8) but it is.
1822 AVCodecContext* cod = &s->streams[sc->ffindex]->codec;
1823 if (sc->sample_size == 1 && (cod->codec_id == CODEC_ID_PCM_S16BE || cod->codec_id == CODEC_ID_PCM_S16LE))
1824 foundsize=(sc->sample_to_chunk[i].count*cod->channels*cod->bits_per_sample)/8;
1825 else
1826 foundsize=sc->sample_to_chunk[i].count*sc->sample_size;
bc634f6f
ZK
1827 }
1828#ifdef DEBUG
c3ea71a0 1829 av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id);
bc634f6f
ZK
1830#endif
1831 }
1832 if( (foundsize>0) && (foundsize<size) )
1833 {
1834#ifdef DEBUG
baf25c9d 1835 /*av_log(NULL, AV_LOG_DEBUG, "this size should actually be %d\n",foundsize);*/
bc634f6f
ZK
1836#endif
1837 size=foundsize;
1838 }
1839 }
1840#endif //MOV_MINOLTA_FIX
1841
3ffe3793
FR
1842#ifdef MOV_SPLIT_CHUNKS
1843 /* split chunks into samples */
92e51b66
RG
1844 if (s->streams[sc->ffindex]->codec.codec_type == CODEC_TYPE_VIDEO) {
1845 // This does not support split audio, as the sample_size is often not correct
7dbab4a9
FR
1846 idx = sc->sample_to_chunk_index;
1847 if ((idx + 1 < sc->sample_to_chunk_sz)
1848 && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
1849 idx++;
1850 sc->sample_to_chunk_index = idx;
1851 if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
1852 mov->partial = sc;
1853 /* we'll have to get those samples before next chunk */
1854 sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
92e51b66 1855 size = sc->sample_size?sc->sample_size:sc->sample_sizes[sc->current_sample];
7dbab4a9 1856 }
7619ed2b 1857
7dbab4a9
FR
1858 sc->current_sample++;
1859 }
3ffe3793
FR
1860#endif
1861
1862readchunk:
c3ea71a0
FR
1863#ifdef DEBUG
1864 av_log(NULL, AV_LOG_DEBUG, "chunk: %lli -> %lli (%i)\n", offset, offset + size, size);
1865#endif
6cea494e
ZK
1866 if(size == 0x0FFFFFFF)
1867 size = mov->mdat_size + mov->mdat_offset - offset;
1868 if(size < 0)
1869 return -1;
1870 if(size == 0)
1871 return -1;
0e7eed09 1872 url_fseek(&s->pb, offset, SEEK_SET);
5cd62665 1873
baf25c9d 1874 //av_log(NULL, AV_LOG_DEBUG, "READCHUNK hlen: %d %d off: %Ld pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
0e7eed09
FB
1875 if (sc->header_len > 0) {
1876 av_new_packet(pkt, size + sc->header_len);
1877 memcpy(pkt->data, sc->header_data, sc->header_len);
1878 get_buffer(&s->pb, pkt->data + sc->header_len, size);
1879 /* free header */
1880 av_freep(&sc->header_data);
1881 sc->header_len = 0;
1882 } else {
1883 av_new_packet(pkt, size);
1884 get_buffer(&s->pb, pkt->data, pkt->size);
1885 }
1886 pkt->stream_index = sc->ffindex;
247d56f5
BB
1887
1888 // If the keyframes table exists, mark any samples that are in the table as key frames.
1889 // If no table exists, treat very sample as a key frame.
1890 if (sc->keyframes) {
1891 a = 0;
1892 b = sc->keyframe_count - 1;
1893
1894 while (a < b) {
1895 m = (a + b + 1) >> 1;
1896 if (sc->keyframes[m] > sc->current_sample) {
1897 b = m - 1;
1898 } else {
1899 a = m;
1900 }
1901 }
1902
1903 if (sc->keyframes[a] == sc->current_sample)
1904 pkt->flags |= PKT_FLAG_KEY;
1905 }
1906 else
1907 pkt->flags |= PKT_FLAG_KEY;
6cea494e
ZK
1908
1909#ifdef DEBUG
7dbab4a9 1910/*
c3ea71a0 1911 av_log(NULL, AV_LOG_DEBUG, "Packet (%d, %ld) ", pkt->stream_index, pkt->size);
6cea494e 1912 for(i=0; i<8; i++)
baf25c9d 1913 av_log(NULL, AV_LOG_DEBUG, "%02x ", pkt->data[i]);
6cea494e 1914 for(i=0; i<8; i++)
baf25c9d 1915 av_log(NULL, AV_LOG_DEBUG, "%c ", (pkt->data[i]) & 0x7F);
c3ea71a0 1916 av_log(NULL, AV_LOG_DEBUG, "\n");
7dbab4a9 1917*/
6cea494e
ZK
1918#endif
1919
1920 mov->next_chunk_offset = offset + size;
7fe5a3c0
GC
1921
1922 /* find the corresponding dts */
1923 if (sc && sc->sample_to_time_index < sc->stts_count && pkt) {
cd461d48
MN
1924 unsigned int count;
1925 uint64_t dts;
1926 unsigned int duration = sc->stts_data[sc->sample_to_time_index].duration;
1927 count = sc->stts_data[sc->sample_to_time_index].count;
7fe5a3c0
GC
1928 if ((sc->sample_to_time_sample + count) < sc->current_sample) {
1929 sc->sample_to_time_sample += count;
1930 sc->sample_to_time_time += count*duration;
1931 sc->sample_to_time_index ++;
cd461d48 1932 duration = sc->stts_data[sc->sample_to_time_index].duration;
7fe5a3c0 1933 }
cd461d48 1934 dts = sc->sample_to_time_time + (sc->current_sample-1 - sc->sample_to_time_sample) * (int64_t)duration;
7fe5a3c0
GC
1935 dts = av_rescale( dts,
1936 (int64_t)s->streams[sc->ffindex]->time_base.den,
1937 (int64_t)sc->time_scale * (int64_t)s->streams[sc->ffindex]->time_base.num );
cd461d48
MN
1938 pkt->dts = dts;
1939 //do not set pts=dts because u think it might be equal!!!!!!!!
7fe5a3c0
GC
1940#ifdef DEBUG
1941/* av_log(NULL, AV_LOG_DEBUG, "stream #%d smp #%ld dts = %ld (smp:%ld time:%ld idx:%ld ent:%d count:%ld dur:%ld)\n"
1942 , pkt->stream_index, sc->current_sample-1, (long)pkt->dts
1943 , (long)sc->sample_to_time_sample
1944 , (long)sc->sample_to_time_time
1945 , (long)sc->sample_to_time_index
1946 , (long)sc->stts_count
1947 , count
1948 , duration);*/
1949#endif
1950 }
6cea494e
ZK
1951
1952 return 0;
1953}
1954
baf25c9d
GC
1955#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
1956/**
1957 * Seek method based on the one described in the Appendix C of QTFileFormat.pdf
1958 */
7b3c1382 1959static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
baf25c9d
GC
1960{
1961 MOVContext* mov = (MOVContext *) s->priv_data;
1962 MOVStreamContext* sc;
1963 int32_t i, a, b, m;
1964 int64_t sample_time;
1965 int64_t start_time;
1966 int32_t seek_sample, sample;
1967 int32_t duration;
1968 int32_t count;
1969 int32_t chunk;
1970 int32_t left_in_chunk;
1971 int64_t chunk_file_offset;
1972 int64_t sample_file_offset;
1973 int32_t first_chunk_sample;
1974 int32_t sample_to_chunk_idx;
7fe5a3c0
GC
1975 int sample_to_time_index;
1976 long sample_to_time_sample = 0;
1977 uint64_t sample_to_time_time = 0;
baf25c9d
GC
1978 int mov_idx;
1979
1980 // Find the corresponding mov stream
1981 for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++)
1982 if (mov->streams[mov_idx]->ffindex == stream_index)
1983 break;
1984 if (mov_idx == mov->total_streams) {
1985 av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index);
1986 return -1;
1987 }
1988 sc = mov->streams[mov_idx];
1989
1990 // Step 1. Find the edit that contains the requested time (elst)
1991 if (sc->edit_count) {
1992 // FIXME should handle edit list
1993 av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count);
1994 return -1;
1995 }
1996
1997 // Step 2. Find the corresponding sample using the Time-to-sample atom (stts) */
1998#ifdef DEBUG
1999 av_log(s, AV_LOG_DEBUG, "Searching for time %li in stream #%i (time_scale=%i)\n", (long)timestamp, mov_idx, sc->time_scale);
2000#endif
2001 // convert timestamp from time_base unit to timescale unit
2002 sample_time = av_rescale( timestamp,
2003 (int64_t)sc->time_scale * s->streams[stream_index]->time_base.num,
2004 (int64_t)s->streams[stream_index]->time_base.den);
2005 start_time = 0; // FIXME use elst atom
2006 sample = 1; // sample are 0 based in table
2007#ifdef DEBUG
2008 av_log(s, AV_LOG_DEBUG, "Searching for sample_time %li \n", (long)sample_time);
2009#endif
2010 for (i = 0; i < sc->stts_count; i++) {
cd461d48
MN
2011 count = sc->stts_data[i].count;
2012 duration = sc->stts_data[i].duration;
baf25c9d
GC
2013//av_log(s, AV_LOG_DEBUG, "> sample_time %lli \n", (long)sample_time);
2014//av_log(s, AV_LOG_DEBUG, "> count=%i duration=%i\n", count, duration);
2015 if ((start_time + count*duration) > sample_time) {
7fe5a3c0
GC
2016 sample_to_time_time = start_time;
2017 sample_to_time_index = i;
2018 sample_to_time_sample = sample;
baf25c9d
GC
2019 sample += (sample_time - start_time) / duration;
2020 break;
2021 }
2022 sample += count;
2023 start_time += count * duration;
2024 }
7fe5a3c0
GC
2025 sample_to_time_time = start_time;
2026 sample_to_time_index = i;
baf25c9d
GC
2027 /* NOTE: despite what qt doc say, the dt value (Display Time in qt vocabulary) computed with the stts atom
2028 is a decoding time stamp (dts) not a presentation time stamp. And as usual dts != pts for stream with b frames */
2029
2030#ifdef DEBUG
2031 av_log(s, AV_LOG_DEBUG, "Found time %li at sample #%u\n", (long)sample_time, sample);
2032#endif
2033 if (sample > sc->sample_count) {
2034 av_log(s, AV_LOG_ERROR, "mov: sample pos is too high, unable to seek (req. sample=%i, sample count=%ld)\n", sample, sc->sample_count);
2035 return -1;
2036 }
2037
2038 // Step 3. Find the prior sync. sample using the Sync sample atom (stss)
2039 if (sc->keyframes) {
2040 a = 0;
2041 b = sc->keyframe_count - 1;
2042 while (a < b) {
2043 m = (a + b + 1) >> 1;
2044 if (sc->keyframes[m] > sample) {
2045 b = m - 1;
2046 } else {
2047 a = m;
2048 }
2049#ifdef DEBUG
2050 // av_log(s, AV_LOG_DEBUG, "a=%i (%i) b=%i (%i) m=%i (%i) stream #%i\n", a, sc->keyframes[a], b, sc->keyframes[b], m, sc->keyframes[m], mov_idx);
2051#endif
2052 }
7fe5a3c0
GC
2053 // for low latency prob: always use the previous keyframe, just uncomment the next line
2054 // if (a) a--;
baf25c9d
GC
2055 seek_sample = sc->keyframes[a];
2056 }
2057 else
2058 seek_sample = sample; // else all samples are key frames
2059#ifdef DEBUG
2060 av_log(s, AV_LOG_DEBUG, "Found nearest keyframe at sample #%i \n", seek_sample);
2061#endif
2062
2063 // Step 4. Find the chunk of the sample using the Sample-to-chunk-atom (stsc)
2064 for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) {
2065 b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count;
2066 if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b))
2067 break;
2068 first_chunk_sample += b;
2069 }
2070 chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count;
2071 left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count;
2072 first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count;
2073 sample_to_chunk_idx = i;
2074#ifdef DEBUG
2075 av_log(s, AV_LOG_DEBUG, "Sample was found in chunk #%i at sample offset %i (idx %i)\n", chunk, seek_sample - first_chunk_sample, sample_to_chunk_idx);
2076#endif
2077
2078 // Step 5. Find the offset of the chunk using the chunk offset atom
2079 if (!sc->chunk_offsets) {
2080 av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n");
2081 return -1;
2082 }
2083 if (chunk > sc->chunk_count) {
2084 av_log(s, AV_LOG_ERROR, "mov: chunk offset atom too short, unable to seek (req. chunk=%i, chunk count=%li)\n", chunk, sc->chunk_count);
2085 return -1;
2086 }
2087 chunk_file_offset = sc->chunk_offsets[chunk - 1];
2088#ifdef DEBUG
2089 av_log(s, AV_LOG_DEBUG, "Chunk file offset is #%llu \n", chunk_file_offset);
2090#endif
2091
2092 // Step 6. Find the byte offset within the chunk using the sample size atom
2093 sample_file_offset = chunk_file_offset;
2094 if (sc->sample_size)
2095 sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size;
2096 else {
2097 for (i = 0; i < (seek_sample - first_chunk_sample); i++) {
2098 sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1];
2099 }
2100 }
2101#ifdef DEBUG
2102 av_log(s, AV_LOG_DEBUG, "Sample file offset is #%llu \n", sample_file_offset);
2103#endif
2104
2105 // Step 6. Update the parser
2106 mov->partial = sc;
2107 mov->next_chunk_offset = sample_file_offset;
2108 // Update current stream state
2109 sc->current_sample = seek_sample - 1; // zero based
2110 sc->left_in_chunk = left_in_chunk;
2111 sc->next_chunk = chunk; // +1 -1 (zero based)
2112 sc->sample_to_chunk_index = sample_to_chunk_idx;
2113
2114 // Update other streams
2115 for (i = 0; i<mov->total_streams; i++) {
5c030d3e 2116 MOVStreamContext *msc;
baf25c9d
GC
2117 if (i == mov_idx) continue;
2118 // Find the nearest 'next' chunk
5c030d3e 2119 msc = mov->streams[i];
baf25c9d
GC
2120 a = 0;
2121 b = msc->chunk_count - 1;
2122 while (a < b) {
2123 m = (a + b + 1) >> 1;
2124 if (msc->chunk_offsets[m] > chunk_file_offset) {
2125 b = m - 1;
2126 } else {
2127 a = m;
2128 }
2129#ifdef DEBUG
2130/* av_log(s, AV_LOG_DEBUG, "a=%i (%li) b=%i (%li) m=%i (%li) stream #%i\n"
2131 , a, (long)msc->chunk_offsets[a], b, (long)msc->chunk_offsets[b], m, (long)msc->chunk_offsets[m], i); */
2132#endif
2133 }
2134 msc->next_chunk = a;
2135 if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1))
2136 msc->next_chunk ++;
2137#ifdef DEBUG
2138 av_log(s, AV_LOG_DEBUG, "Nearest next chunk for stream #%i is #%i @%lli\n", i, msc->next_chunk+1, msc->chunk_offsets[msc->next_chunk]);
2139#endif
2140 // Compute sample count and index in the sample_to_chunk table (what a pity)
2141 msc->sample_to_chunk_index = 0;
2142 msc->current_sample = 0;
2143 for(; msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1)
2144 && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) {
2145 msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \
2146 * msc->sample_to_chunk[msc->sample_to_chunk_index].count;
2147 }
2148 msc->current_sample += (msc->next_chunk - (msc->sample_to_chunk[msc->sample_to_chunk_index].first - 1)) * sc->sample_to_chunk[msc->sample_to_chunk_index].count;
2149 msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1;
7fe5a3c0
GC
2150 // Find corresponding position in stts (used later to compute dts)
2151 sample = 0;
2152 start_time = 0;
2153 for (msc->sample_to_time_index = 0; msc->sample_to_time_index < msc->stts_count; msc->sample_to_time_index++) {
cd461d48
MN
2154 count = msc->stts_data[msc->sample_to_time_index].count;
2155 duration = msc->stts_data[msc->sample_to_time_index].duration;
7fe5a3c0
GC
2156 if ((sample + count - 1) > msc->current_sample) {
2157 msc->sample_to_time_time = start_time;
2158 msc->sample_to_time_sample = sample;
2159 break;
2160 }
2161 sample += count;
2162 start_time += count * duration;
2163 }
baf25c9d
GC
2164#ifdef DEBUG
2165 av_log(s, AV_LOG_DEBUG, "Next Sample for stream #%i is #%i @%i\n", i, msc->current_sample + 1, msc->sample_to_chunk_index + 1);
2166#endif
2167 }
2168 return 0;
2169}
2170#endif
2171
a266644f 2172static int mov_read_close(AVFormatContext *s)
6cea494e
ZK
2173{
2174 int i;
b6a17df4 2175 MOVContext *mov = (MOVContext *) s->priv_data;
6cea494e
ZK
2176 for(i=0; i<mov->total_streams; i++)
2177 mov_free_stream_context(mov->streams[i]);
5ca1d879
ZK
2178 /* free color tabs */
2179 for(i=0; i<mov->ctab_size; i++)
2180 av_freep(&mov->ctab[i]);
2181 av_freep(&mov->ctab);
6cea494e
ZK
2182 return 0;
2183}
2184
c9a65ca8 2185static AVInputFormat mov_iformat = {
4cb3f3b6 2186 "mov,mp4,m4a,3gp",
c9a65ca8
FB
2187 "QuickTime/MPEG4 format",
2188 sizeof(MOVContext),
2189 mov_probe,
6cea494e
ZK
2190 mov_read_header,
2191 mov_read_packet,
2192 mov_read_close,
baf25c9d
GC
2193#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
2194 mov_read_seek,
2195#endif
6cea494e
ZK
2196};
2197
c9a65ca8
FB
2198int mov_init(void)
2199{
2200 av_register_input_format(&mov_iformat);
2201 return 0;
2202}