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