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