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