Statistics
| Branch: | Revision:

ffmpeg / libavformat / mov.c @ 53ffdd14

History | View | Annotate | Download (75.3 KB)

1
/*
2
 * MOV decoder.
3
 * Copyright (c) 2001 Fabrice Bellard.
4
 *
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.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
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
18
 */
19

    
20
#include <limits.h>
21
 
22
#include "avformat.h"
23
#include "avi.h"
24

    
25
#ifdef CONFIG_ZLIB
26
#include <zlib.h>
27
#endif
28

    
29
/*
30
 * First version by Francois Revol revol@free.fr
31
 * Seek function by Gael Chardon gael.dev@4now.net 
32
 *
33
 * Features and limitations:
34
 * - reads most of the QT files I have (at least the structure),
35
 *   the exceptions are .mov with zlib compressed headers ('cmov' section). It shouldn't be hard to implement.
36
 *   FIXED, Francois Revol, 07/17/2002
37
 * - ffmpeg has nearly none of the usual QuickTime codecs,
38
 *   although I succesfully dumped raw and mp3 audio tracks off .mov files.
39
 *   Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
40
 * - .mp4 parsing is still hazardous, although the format really is QuickTime with some minor changes
41
 *   (to make .mov parser crash maybe ?), despite what they say in the MPEG FAQ at
42
 *   http://mpeg.telecomitalialab.com/faq.htm
43
 * - the code is quite ugly... maybe I won't do it recursive next time :-)
44
 * - seek is not supported with files that contain edit list
45
 *
46
 * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
47
 * when coding this :) (it's a writer anyway)
48
 *
49
 * Reference documents:
50
 * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
51
 * Apple:
52
 *  http://developer.apple.com/documentation/QuickTime/QTFF/
53
 *  http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
54
 * QuickTime is a trademark of Apple (AFAIK :))
55
 */
56

    
57
//#define DEBUG
58
#ifdef DEBUG
59
#include <stdio.h>
60
#include <fcntl.h>
61
#endif
62

    
63
#include "qtpalette.h"
64

    
65

    
66
/* Allows seeking (MOV_SPLIT_CHUNKS should also be defined) */
67
#define MOV_SEEK
68

    
69
/* allows chunk splitting - should work now... */
70
/* in case you can't read a file, try commenting */
71
#define MOV_SPLIT_CHUNKS
72

    
73
/* Special handling for movies created with Minolta Dimaxe Xi*/
74
/* this fix should not interfere with other .mov files, but just in case*/
75
#define MOV_MINOLTA_FIX
76

    
77
/* some streams in QT (and in MP4 mostly) aren't either video nor audio */
78
/* so we first list them as this, then clean up the list of streams we give back, */
79
/* getting rid of these */
80
#define CODEC_TYPE_MOV_OTHER        (enum CodecType) 2
81

    
82
static const CodecTag mov_video_tags[] = {
83
/*  { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
84
/*  { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
85
/*  { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
86
/*    { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
87
/* Graphics */
88
/* Animation */
89
/* Apple video */
90
/* Kodak Photo CD */
91
    { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
92
    { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
93
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
94
    { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
95
    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
96
/*    { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
97
/*    { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
98
/* Sorenson video */
99
    { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
100
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
101
    { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
102
    { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
103
    { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
104
    { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
105
    { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
106
/*    { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
107
    { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
108
    { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
109
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
110
    { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
111
/*    { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, *//* AVID dv */
112
    { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
113
    { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
114
    { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
115
    { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
116
    { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
117
    { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
118
    { CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
119
    { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
120
    { CODEC_ID_NONE, 0 },
121
};
122

    
123
static const CodecTag mov_audio_tags[] = {
124
/*    { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, *//* uncompressed */
125
    { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
126
    /* { CODEC_ID_PCM_S8, MKTAG('t', 'w', 'o', 's') },*/ /* 8 bits */
127
    { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
128
    { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /*  */
129
    { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /*  */
130
    { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /*  */
131
    { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
132
    { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
133
    { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
134

    
135
    { CODEC_ID_MP2, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
136
    { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
137
    { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
138
/*    { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
139
/* MP4 tags */
140
    { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
141
    /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
142
    { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
143
    { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
144
    { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
145
    { CODEC_ID_NONE, 0 },
146
};
147

    
148
/* the QuickTime file format is quite convoluted...
149
 * it has lots of index tables, each indexing something in another one...
150
 * Here we just use what is needed to read the chunks
151
 */
152

    
153
typedef struct MOV_sample_to_chunk_tbl {
154
    long first;
155
    long count;
156
    long id;
157
} MOV_sample_to_chunk_tbl;
158

    
159
typedef struct {
160
    uint32_t type;
161
    int64_t offset;
162
    int64_t size; /* total size (excluding the size and type fields) */
163
} MOV_atom_t;
164

    
165
typedef struct {
166
    int seed;
167
    int flags;
168
    int size;
169
    void* clrs;
170
} MOV_ctab_t;
171

    
172
typedef struct {
173
    uint8_t  version;
174
    uint32_t flags; // 24bit
175

    
176
    /* 0x03 ESDescrTag */
177
    uint16_t es_id;
178
#define MP4ODescrTag                        0x01
179
#define MP4IODescrTag                        0x02
180
#define MP4ESDescrTag                        0x03
181
#define MP4DecConfigDescrTag                0x04
182
#define MP4DecSpecificDescrTag                0x05
183
#define MP4SLConfigDescrTag                0x06
184
#define MP4ContentIdDescrTag                0x07
185
#define MP4SupplContentIdDescrTag        0x08
186
#define MP4IPIPtrDescrTag                0x09
187
#define MP4IPMPPtrDescrTag                0x0A
188
#define MP4IPMPDescrTag                        0x0B
189
#define MP4RegistrationDescrTag                0x0D
190
#define MP4ESIDIncDescrTag                0x0E
191
#define MP4ESIDRefDescrTag                0x0F
192
#define MP4FileIODescrTag                0x10
193
#define MP4FileODescrTag                0x11
194
#define MP4ExtProfileLevelDescrTag        0x13
195
#define MP4ExtDescrTagsStart                0x80
196
#define MP4ExtDescrTagsEnd                0xFE
197
    uint8_t  stream_priority;
198

    
199
    /* 0x04 DecConfigDescrTag */
200
    uint8_t  object_type_id;
201
    uint8_t  stream_type;
202
    /* XXX: really streamType is
203
     * only 6bit, followed by:
204
     * 1bit  upStream
205
     * 1bit  reserved
206
     */
207
    uint32_t buffer_size_db; // 24
208
    uint32_t max_bitrate;
209
    uint32_t avg_bitrate;
210

    
211
    /* 0x05 DecSpecificDescrTag */
212
    uint8_t  decoder_cfg_len;
213
    uint8_t *decoder_cfg;
214

    
215
    /* 0x06 SLConfigDescrTag */
216
    uint8_t  sl_config_len;
217
    uint8_t *sl_config;
218
} MOV_esds_t;
219

    
220
struct MOVParseTableEntry;
221

    
222
typedef struct MOVStreamContext {
223
    int ffindex; /* the ffmpeg stream id */
224
    int is_ff_stream; /* Is this stream presented to ffmpeg ? i.e. is this an audio or video stream ? */
225
    long next_chunk;
226
    long chunk_count;
227
    int64_t *chunk_offsets;
228
    int32_t stts_count;
229
    uint64_t *stts_data;            /* concatenated data from the time-to-sample atom (count|duration) */
230
    int32_t edit_count;             /* number of 'edit' (elst atom) */
231
    long sample_to_chunk_sz;
232
    MOV_sample_to_chunk_tbl *sample_to_chunk;
233
    long sample_to_chunk_index;
234
    int sample_to_time_index;         
235
    long sample_to_time_sample;         
236
    uint64_t sample_to_time_time;    
237
    long sample_size;
238
    long sample_count;
239
    long *sample_sizes;
240
    long keyframe_count;
241
    long *keyframes;
242
    int time_scale;
243
    long current_sample;
244
    long left_in_chunk; /* how many samples before next chunk */
245
    /* specific MPEG4 header which is added at the beginning of the stream */
246
    unsigned int header_len;
247
    uint8_t *header_data;
248
    MOV_esds_t esds;
249
} MOVStreamContext;
250

    
251
typedef struct MOVContext {
252
    int mp4; /* set to 1 as soon as we are sure that the file is an .mp4 file (even some header parsing depends on this) */
253
    AVFormatContext *fc;
254
    int time_scale;
255
    int duration; /* duration of the longest track */
256
    int found_moov; /* when both 'moov' and 'mdat' sections has been found */
257
    int found_mdat; /* we suppose we have enough data to read the file */
258
    int64_t mdat_size;
259
    int64_t mdat_offset;
260
    int total_streams;
261
    /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
262
     * but we need the info to be able to skip data from those streams in the 'mdat' section
263
     */
264
    MOVStreamContext *streams[MAX_STREAMS];
265

    
266
    int64_t next_chunk_offset;
267
    MOVStreamContext *partial; /* != 0 : there is still to read in the current chunk */
268
    int ctab_size;
269
    MOV_ctab_t **ctab;           /* color tables */
270
    const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
271
    /* NOTE: for recursion save to/ restore from local variable! */
272

    
273
    AVPaletteControl palette_control;
274
} MOVContext;
275

    
276

    
277
/* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
278

    
279
/* those functions parse an atom */
280
/* return code:
281
 1: found what I wanted, exit
282
 0: continue to parse next atom
283
 -1: error occured, exit
284
 */
285
typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
286

    
287
/* links atom IDs to parse functions */
288
typedef struct MOVParseTableEntry {
289
    uint32_t type;
290
    mov_parse_function func;
291
} MOVParseTableEntry;
292

    
293
#ifdef DEBUG
294
/*
295
 * XXX: static sux, even more in a multithreaded environment...
296
 * Avoid them. This is here just to help debugging.
297
 */
298
static int debug_indent = 0;
299
void print_atom(const char *str, MOV_atom_t atom)
300
{
301
    unsigned int tag, i;
302
    tag = (unsigned int) atom.type;
303
    i=debug_indent;
304
    if(tag == 0) tag = MKTAG('N', 'U', 'L', 'L');
305
    while(i--)
306
        av_log(NULL, AV_LOG_DEBUG, "|");
307
    av_log(NULL, AV_LOG_DEBUG, "parse:");
308
    av_log(NULL, AV_LOG_DEBUG, " %s: tag=%c%c%c%c offset=0x%x size=0x%x\n",
309
           str, tag & 0xff,
310
           (tag >> 8) & 0xff,
311
           (tag >> 16) & 0xff,
312
           (tag >> 24) & 0xff,
313
           (unsigned int)atom.offset,
314
           (unsigned int)atom.size);
315
    assert((unsigned int)atom.size < 0x7fffffff);// catching errors
316
}
317
#else
318
#define print_atom(a,b)
319
#endif
320

    
321

    
322
static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
323
{
324
    print_atom("leaf", atom);
325

    
326
    if (atom.size>1)
327
        url_fskip(pb, atom.size);
328
/*        url_seek(pb, atom_offset+atom.size, SEEK_SET); */
329
    return 0;
330
}
331

    
332
static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
333
{
334
    int64_t total_size = 0;
335
    MOV_atom_t a;
336
    int i;
337
    int err = 0;
338

    
339
#ifdef DEBUG
340
    print_atom("default", atom);
341
    debug_indent++;
342
#endif
343

    
344
    a.offset = atom.offset;
345

    
346
    if (atom.size < 0)
347
        atom.size = 0x7fffffffffffffffLL;
348
    while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
349
        a.size = atom.size;
350
        a.type=0L;
351
        if(atom.size >= 8) {
352
            a.size = get_be32(pb);
353
            a.type = get_le32(pb);
354
        }
355
        total_size += 8;
356
        a.offset += 8;
357
        //av_log(NULL, AV_LOG_DEBUG, "type: %08x  %.4s  sz: %Lx  %Lx   %Lx\n", type, (char*)&type, size, atom.size, total_size);
358
        if (a.size == 1) { /* 64 bit extended size */
359
            a.size = get_be64(pb) - 8;
360
            a.offset += 8;
361
            total_size += 8;
362
        }
363
        if (a.size == 0) {
364
            a.size = atom.size - total_size;
365
            if (a.size <= 8)
366
                break;
367
        }
368
        for (i = 0; c->parse_table[i].type != 0L
369
             && c->parse_table[i].type != a.type; i++)
370
            /* empty */;
371

    
372
        a.size -= 8;
373
        
374
        if(a.size < 0)
375
            break;
376
        
377
//        av_log(NULL, AV_LOG_DEBUG, " i=%ld\n", i);
378
        if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
379
//            url_seek(pb, atom.offset+atom.size, SEEK_SET);
380
#ifdef DEBUG
381
            print_atom("unknown", a);
382
#endif
383
            url_fskip(pb, a.size);
384
        } else {
385
#ifdef DEBUG
386
            //char b[5] = { type & 0xff, (type >> 8) & 0xff, (type >> 16) & 0xff, (type >> 24) & 0xff, 0 };
387
            //print_atom(b, type, offset, size);
388
#endif
389
            err = (c->parse_table[i].func)(c, pb, a);
390
        }
391

    
392
        a.offset += a.size;
393
        total_size += a.size;
394
    }
395

    
396
    if (!err && total_size < atom.size && atom.size < 0x7ffff) {
397
        //av_log(NULL, AV_LOG_DEBUG, "RESET  %Ld  %Ld  err:%d\n", atom.size, total_size, err);
398
        url_fskip(pb, atom.size - total_size);
399
    }
400

    
401
#ifdef DEBUG
402
    debug_indent--;
403
#endif
404
    return err;
405
}
406

    
407
static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
408
{
409
    unsigned int len;
410
    MOV_ctab_t *t;
411
#if 1
412
    url_fskip(pb, atom.size); // for now
413
#else
414
    VERY VERY BROKEN, NEVER execute this, needs rewrite
415
    c->ctab = av_realloc(c->ctab, ++c->ctab_size);
416
    t = c->ctab[c->ctab_size];
417
    t->seed = get_be32(pb);
418
    t->flags = get_be16(pb);
419
    t->size = get_be16(pb) + 1;
420
    len = 2 * t->size * 4;
421
    if (len > 0) {
422
        t->clrs = av_malloc(len); // 16bit A R G B
423
        if (t->clrs)
424
            get_buffer(pb, t->clrs, len);
425
    }
426
#endif
427

    
428
    return 0;
429
}
430

    
431
static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
432
{
433
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
434
    int len = 0;
435
    uint32_t type;
436
    uint32_t ctype;
437

    
438
    print_atom("hdlr", atom);
439

    
440
    get_byte(pb); /* version */
441
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
442

    
443
    /* component type */
444
    ctype = get_le32(pb);
445
    type = get_le32(pb); /* component subtype */
446

    
447
#ifdef DEBUG
448
    av_log(NULL, AV_LOG_DEBUG, "ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
449
    av_log(NULL, AV_LOG_DEBUG, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
450
#endif
451
#ifdef DEBUG
452
/* XXX: yeah this is ugly... */
453
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
454
        if(type == MKTAG('v', 'i', 'd', 'e'))
455
            puts("hdlr: vide");
456
        else if(type == MKTAG('s', 'o', 'u', 'n'))
457
            puts("hdlr: soun");
458
    } else if(ctype == 0) { /* MP4 */
459
        if(type == MKTAG('v', 'i', 'd', 'e'))
460
            puts("hdlr: vide");
461
        else if(type == MKTAG('s', 'o', 'u', 'n'))
462
            puts("hdlr: soun");
463
        else if(type == MKTAG('o', 'd', 's', 'm'))
464
            puts("hdlr: odsm");
465
        else if(type == MKTAG('s', 'd', 's', 'm'))
466
            puts("hdlr: sdsm");
467
    } else puts("hdlr: meta");
468
#endif
469

    
470
    if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
471
        /* helps parsing the string hereafter... */
472
        c->mp4 = 0;
473
        if(type == MKTAG('v', 'i', 'd', 'e'))
474
            st->codec.codec_type = CODEC_TYPE_VIDEO;
475
        else if(type == MKTAG('s', 'o', 'u', 'n'))
476
            st->codec.codec_type = CODEC_TYPE_AUDIO;
477
    } else if(ctype == 0) { /* MP4 */
478
        /* helps parsing the string hereafter... */
479
        c->mp4 = 1;
480
        if(type == MKTAG('v', 'i', 'd', 'e'))
481
            st->codec.codec_type = CODEC_TYPE_VIDEO;
482
        else if(type == MKTAG('s', 'o', 'u', 'n'))
483
            st->codec.codec_type = CODEC_TYPE_AUDIO;
484
    }
485
    get_be32(pb); /* component  manufacture */
486
    get_be32(pb); /* component flags */
487
    get_be32(pb); /* component flags mask */
488

    
489
    if(atom.size <= 24)
490
        return 0; /* nothing left to read */
491
    /* XXX: MP4 uses a C string, not a pascal one */
492
    /* component name */
493

    
494
    if(c->mp4) {
495
        /* .mp4: C string */
496
        while(get_byte(pb) && (++len < (atom.size - 24)));
497
    } else {
498
        /* .mov: PASCAL string */
499
#ifdef DEBUG
500
        char* buf;
501
#endif
502
        len = get_byte(pb);
503
#ifdef DEBUG
504
        buf = (uint8_t*) av_malloc(len+1);
505
        if (buf) {
506
            get_buffer(pb, buf, len);
507
            buf[len] = '\0';
508
            av_log(NULL, AV_LOG_DEBUG, "**buf='%s'\n", buf);
509
            av_free(buf);
510
        } else
511
#endif
512
            url_fskip(pb, len);
513
    }
514

    
515
    url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
516
    return 0;
517
}
518

    
519
static int mov_mp4_read_descr_len(ByteIOContext *pb)
520
{
521
    int len = 0;
522
    int count = 4;
523
    while (count--) {
524
        int c = get_byte(pb);
525
        len = (len << 7) | (c & 0x7f);
526
        if (!(c & 0x80))
527
            break;
528
    }
529
    return len;
530
}
531

    
532
static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
533
{
534
    int len;
535
    *tag = get_byte(pb);
536
    len = mov_mp4_read_descr_len(pb);
537
#ifdef DEBUG
538
    av_log(NULL, AV_LOG_DEBUG, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
539
#endif
540
    return len;
541
}
542

    
543
static inline unsigned int get_be24(ByteIOContext *s)
544
{
545
    unsigned int val;
546
    val = get_byte(s) << 16;
547
    val |= get_byte(s) << 8;
548
    val |= get_byte(s);
549
    return val;
550
}
551

    
552
static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
553
{
554
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
555
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
556
    int64_t start_pos = url_ftell(pb);
557
    int tag, len;
558

    
559
    print_atom("esds", atom);
560

    
561
    /* Well, broken but suffisant for some MP4 streams */
562
    get_be32(pb); /* version + flags */
563
    len = mov_mp4_read_descr(pb, &tag);
564
    if (tag == MP4ESDescrTag) {
565
        get_be16(pb); /* ID */
566
        get_byte(pb); /* priority */
567
    } else
568
        get_be16(pb); /* ID */
569

    
570
    len = mov_mp4_read_descr(pb, &tag);
571
    if (tag == MP4DecConfigDescrTag) {
572
        sc->esds.object_type_id = get_byte(pb);
573
        sc->esds.stream_type = get_byte(pb);
574
        sc->esds.buffer_size_db = get_be24(pb);
575
        sc->esds.max_bitrate = get_be32(pb);
576
        sc->esds.avg_bitrate = get_be32(pb);
577

    
578
        len = mov_mp4_read_descr(pb, &tag);
579
        //av_log(NULL, AV_LOG_DEBUG, "LEN %d  TAG %d  m:%d a:%d\n", len, tag, sc->esds.max_bitrate, sc->esds.avg_bitrate);
580
        if (tag == MP4DecSpecificDescrTag) {
581
#ifdef DEBUG
582
            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
583
#endif
584
            st->codec.extradata = (uint8_t*) av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
585
            if (st->codec.extradata) {
586
                get_buffer(pb, st->codec.extradata, len);
587
                st->codec.extradata_size = len;
588
            }
589
        }
590
    }
591
    /* in any case, skip garbage */
592
    url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
593
    return 0;
594
}
595

    
596
/* this atom contains actual media data */
597
static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
598
{
599
    print_atom("mdat", atom);
600

    
601
    if(atom.size == 0) /* wrong one (MP4) */
602
        return 0;
603
    c->found_mdat=1;
604
    c->mdat_offset = atom.offset;
605
    c->mdat_size = atom.size;
606
    if(c->found_moov)
607
        return 1; /* found both, just go */
608
    url_fskip(pb, atom.size);
609
    return 0; /* now go for moov */
610
}
611

    
612
/* this atom should contain all header atoms */
613
static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
614
{
615
    int err;
616

    
617
    print_atom("moov", atom);
618

    
619
    err = mov_read_default(c, pb, atom);
620
    /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
621
    /* so we don't parse the whole file if over a network */
622
    c->found_moov=1;
623
    if(c->found_mdat)
624
        return 1; /* found both, just go */
625
    return 0; /* now go for mdat */
626
}
627

    
628

    
629
static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
630
{
631
    print_atom("mdhd", atom);
632

    
633
    get_byte(pb); /* version */
634

    
635
    get_byte(pb); get_byte(pb);
636
    get_byte(pb); /* flags */
637

    
638
    get_be32(pb); /* creation time */
639
    get_be32(pb); /* modification time */
640

    
641
    c->streams[c->fc->nb_streams-1]->time_scale = get_be32(pb);
642

    
643
#ifdef DEBUG
644
    av_log(NULL, AV_LOG_DEBUG, "track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->time_scale); /* time scale */
645
#endif
646
    get_be32(pb); /* duration */
647

    
648
    get_be16(pb); /* language */
649
    get_be16(pb); /* quality */
650

    
651
    return 0;
652
}
653

    
654
static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
655
{
656
    print_atom("mvhd", atom);
657

    
658
    get_byte(pb); /* version */
659
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
660

    
661
    get_be32(pb); /* creation time */
662
    get_be32(pb); /* modification time */
663
    c->time_scale = get_be32(pb); /* time scale */
664
#ifdef DEBUG
665
    av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
666
#endif
667
    c->duration = get_be32(pb); /* duration */
668
    get_be32(pb); /* preferred scale */
669

    
670
    get_be16(pb); /* preferred volume */
671

    
672
    url_fskip(pb, 10); /* reserved */
673

    
674
    url_fskip(pb, 36); /* display matrix */
675

    
676
    get_be32(pb); /* preview time */
677
    get_be32(pb); /* preview duration */
678
    get_be32(pb); /* poster time */
679
    get_be32(pb); /* selection time */
680
    get_be32(pb); /* selection duration */
681
    get_be32(pb); /* current time */
682
    get_be32(pb); /* next track ID */
683

    
684
    return 0;
685
}
686

    
687
static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
688
{
689
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
690

    
691
    if((uint64_t)atom.size > (1<<30))
692
        return -1;
693
    
694
    // currently SVQ3 decoder expect full STSD header - so let's fake it
695
    // this should be fixed and just SMI header should be passed
696
    av_free(st->codec.extradata);
697
    st->codec.extradata_size = 0x5a + atom.size;
698
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
699

    
700
    if (st->codec.extradata) {
701
        strcpy(st->codec.extradata, "SVQ3"); // fake
702
        get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
703
        //av_log(NULL, AV_LOG_DEBUG, "Reading SMI %Ld  %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
704
    } else
705
        url_fskip(pb, atom.size);
706

    
707
    return 0;
708
}
709

    
710
static int mov_read_avcC(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
711
{
712
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
713

    
714
    if((uint64_t)atom.size > (1<<30))
715
        return -1;
716

    
717
    av_free(st->codec.extradata);
718

    
719
    st->codec.extradata_size = atom.size;
720
    st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
721

    
722
    if (st->codec.extradata) {
723
        get_buffer(pb, st->codec.extradata, atom.size);
724
    } else
725
        url_fskip(pb, atom.size);
726

    
727
    return 0;
728
}
729

    
730
static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
731
{
732
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
733
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
734
    unsigned int i, entries;
735

    
736
    print_atom("stco", atom);
737

    
738
    get_byte(pb); /* version */
739
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
740

    
741
    entries = get_be32(pb);
742
        
743
    if(entries >= UINT_MAX/sizeof(int64_t))
744
        return -1;
745
 
746
    sc->chunk_count = entries;
747
    sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
748
    if (!sc->chunk_offsets)
749
        return -1;
750
    if (atom.type == MKTAG('s', 't', 'c', 'o')) {
751
        for(i=0; i<entries; i++) {
752
            sc->chunk_offsets[i] = get_be32(pb);
753
        }
754
    } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
755
        for(i=0; i<entries; i++) {
756
            sc->chunk_offsets[i] = get_be64(pb);
757
        }
758
    } else
759
        return -1;
760
#ifdef DEBUG
761
/*
762
    for(i=0; i<entries; i++) {
763
        av_log(NULL, AV_LOG_DEBUG, "chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
764
    }
765
*/
766
#endif
767
    return 0;
768
}
769

    
770
static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
771
{
772
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
773
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
774
    int entries, frames_per_sample;
775
    uint32_t format;
776
    uint8_t codec_name[32];
777

    
778
    /* for palette traversal */
779
    int color_depth;
780
    int color_start;
781
    int color_count;
782
    int color_end;
783
    int color_index;
784
    int color_dec;
785
    int color_greyscale;
786
    unsigned char *color_table;
787
    int j;
788
    unsigned char r, g, b;
789

    
790
    print_atom("stsd", atom);
791

    
792
    get_byte(pb); /* version */
793
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
794

    
795
    entries = get_be32(pb);
796

    
797
    while(entries--) { //Parsing Sample description table
798
        enum CodecID id;
799
        int size = get_be32(pb); /* size */
800
        format = get_le32(pb); /* data format */
801

    
802
        get_be32(pb); /* reserved */
803
        get_be16(pb); /* reserved */
804
        get_be16(pb); /* index */
805

    
806
        /* for MPEG4: set codec type by looking for it */
807
        id = codec_get_id(mov_video_tags, format);
808
        if (id >= 0) {
809
            AVCodec *codec;
810
            codec = avcodec_find_decoder(id);
811
            if (codec)
812
                st->codec.codec_type = codec->type;
813
        }
814
#ifdef DEBUG
815
        av_log(NULL, AV_LOG_DEBUG, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
816
               size,
817
               (format >> 0) & 0xff,
818
               (format >> 8) & 0xff,
819
               (format >> 16) & 0xff,
820
               (format >> 24) & 0xff,
821
               st->codec.codec_type);
822
#endif
823
        st->codec.codec_tag = format;
824
        if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
825
            MOV_atom_t a = { 0, 0, 0 };
826
            st->codec.codec_id = id;
827
            get_be16(pb); /* version */
828
            get_be16(pb); /* revision level */
829
            get_be32(pb); /* vendor */
830
            get_be32(pb); /* temporal quality */
831
            get_be32(pb); /* spacial quality */
832
            st->codec.width = get_be16(pb); /* width */
833
            st->codec.height = get_be16(pb); /* height */
834
#if 1
835
            if (st->codec.codec_id == CODEC_ID_MPEG4) {
836
                /* in some MPEG4 the width/height are not correct, so
837
                   we ignore this info */
838
                st->codec.width = 0;
839
                st->codec.height = 0;
840
            }
841
#endif
842
            get_be32(pb); /* horiz resolution */
843
            get_be32(pb); /* vert resolution */
844
            get_be32(pb); /* data size, always 0 */
845
            frames_per_sample = get_be16(pb); /* frames per samples */
846
#ifdef DEBUG
847
            av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
848
#endif
849
        get_buffer(pb, codec_name, 32); /* codec name, pascal string (FIXME: true for mp4?) */
850
        if (codec_name[0] <= 31) {
851
            memcpy(st->codec.codec_name, &codec_name[1],codec_name[0]);
852
            st->codec.codec_name[codec_name[0]] = 0;
853
        }
854

    
855
            st->codec.bits_per_sample = get_be16(pb); /* depth */
856
            st->codec.color_table_id = get_be16(pb); /* colortable id */
857

    
858
/*          These are set in mov_read_stts and might already be set!
859
            st->codec.frame_rate      = 25;
860
            st->codec.frame_rate_base = 1;
861
*/
862
            size -= (16+8*4+2+32+2*2);
863
#if 0
864
            while (size >= 8) {
865
                MOV_atom_t a;
866
                int64_t start_pos;
867

868
                a.size = get_be32(pb);
869
                a.type = get_le32(pb);
870
                size -= 8;
871
#ifdef DEBUG
872
                av_log(NULL, AV_LOG_DEBUG, "VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
873
                       (a.type >> 0) & 0xff,
874
                       (a.type >> 8) & 0xff,
875
                       (a.type >> 16) & 0xff,
876
                       (a.type >> 24) & 0xff,
877
                       a.size, size);
878
#endif
879
                start_pos = url_ftell(pb);
880

    
881
                switch(a.type) {
882
                case MKTAG('e', 's', 'd', 's'):
883
                    {
884
                        int tag, len;
885
                        /* Well, broken but suffisant for some MP4 streams */
886
                        get_be32(pb); /* version + flags */
887
                        len = mov_mp4_read_descr(pb, &tag);
888
                        if (tag == 0x03) {
889
                            /* MP4ESDescrTag */
890
                            get_be16(pb); /* ID */
891
                            get_byte(pb); /* priority */
892
                            len = mov_mp4_read_descr(pb, &tag);
893
                            if (tag != 0x04)
894
                                goto fail;
895
                            /* MP4DecConfigDescrTag */
896
                            get_byte(pb); /* objectTypeId */
897
                            get_be32(pb); /* streamType + buffer size */
898
                            get_be32(pb); /* max bit rate */
899
                            get_be32(pb); /* avg bit rate */
900
                            len = mov_mp4_read_descr(pb, &tag);
901
                            if (tag != 0x05)
902
                                goto fail;
903
                            /* MP4DecSpecificDescrTag */
904
#ifdef DEBUG
905
                            av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
906
#endif
907
                            sc->header_data = av_mallocz(len);
908
                            if (sc->header_data) {
909
                                get_buffer(pb, sc->header_data, len);
910
                                sc->header_len = len;
911
                            }
912
                        }
913
                        /* in any case, skip garbage */
914
                    }
915
                    break;
916
                default:
917
                    break;
918
                }
919
            fail:
920
                av_log(NULL, AV_LOG_DEBUG, "ATOMENEWSIZE %Ld   %d\n", atom.size, url_ftell(pb) - start_pos);
921
                if (atom.size > 8) {
922
                    url_fskip(pb, (atom.size - 8) -
923
                              ((url_ftell(pb) - start_pos)));
924
                    size -= atom.size - 8;
925
                }
926
            }
927
            if (size > 0) {
928
                /* unknown extension */
929
                url_fskip(pb, size);
930
            }
931
#else
932

    
933
            /* figure out the palette situation */
934
            color_depth = st->codec.bits_per_sample & 0x1F;
935
            color_greyscale = st->codec.bits_per_sample & 0x20;
936

    
937
            /* if the depth is 2, 4, or 8 bpp, file is palettized */
938
            if ((color_depth == 2) || (color_depth == 4) || 
939
                (color_depth == 8)) {
940

    
941
                if (color_greyscale) {
942

    
943
                    /* compute the greyscale palette */
944
                    color_count = 1 << color_depth;
945
                    color_index = 255;
946
                    color_dec = 256 / (color_count - 1);
947
                    for (j = 0; j < color_count; j++) {
948
                        r = g = b = color_index;
949
                        c->palette_control.palette[j] =
950
                            (r << 16) | (g << 8) | (b);
951
                        color_index -= color_dec;
952
                        if (color_index < 0)
953
                            color_index = 0;
954
                    }
955

    
956
                } else if (st->codec.color_table_id & 0x08) {
957

    
958
                    /* if flag bit 3 is set, use the default palette */
959
                    color_count = 1 << color_depth;
960
                    if (color_depth == 2)
961
                        color_table = ff_qt_default_palette_4;
962
                    else if (color_depth == 4)
963
                        color_table = ff_qt_default_palette_16;
964
                    else
965
                        color_table = ff_qt_default_palette_256;
966

    
967
                    for (j = 0; j < color_count; j++) {
968
                        r = color_table[j * 4 + 0];
969
                        g = color_table[j * 4 + 1];
970
                        b = color_table[j * 4 + 2];
971
                        c->palette_control.palette[j] =
972
                            (r << 16) | (g << 8) | (b);
973
                    }
974

    
975
                } else {
976

    
977
                    /* load the palette from the file */
978
                    color_start = get_be32(pb);
979
                    color_count = get_be16(pb);
980
                    color_end = get_be16(pb);
981
                    for (j = color_start; j <= color_end; j++) {
982
                        /* each R, G, or B component is 16 bits;
983
                         * only use the top 8 bits; skip alpha bytes
984
                         * up front */
985
                        get_byte(pb);
986
                        get_byte(pb);
987
                        r = get_byte(pb);
988
                        get_byte(pb);
989
                        g = get_byte(pb);
990
                        get_byte(pb);
991
                        b = get_byte(pb);
992
                        get_byte(pb);
993
                        c->palette_control.palette[j] =
994
                            (r << 16) | (g << 8) | (b);
995
                    }
996
                }
997

    
998
                st->codec.palctrl = &c->palette_control;
999
                st->codec.palctrl->palette_changed = 1;
1000
            } else
1001
                st->codec.palctrl = NULL;
1002

    
1003
            a.size = size;
1004
            mov_read_default(c, pb, a);
1005
#endif
1006
        } else {
1007
            st->codec.codec_id = codec_get_id(mov_audio_tags, format);
1008
            if(st->codec.codec_id==CODEC_ID_AMR_NB || st->codec.codec_id==CODEC_ID_AMR_WB) //from TS26.244
1009
            {
1010
#ifdef DEBUG
1011
               av_log(NULL, AV_LOG_DEBUG, "AMR-NB or AMR-WB audio identified!!\n");
1012
#endif
1013
               get_be32(pb);get_be32(pb); //Reserved_8
1014
               get_be16(pb);//Reserved_2
1015
               get_be16(pb);//Reserved_2
1016
               get_be32(pb);//Reserved_4
1017
               get_be16(pb);//TimeScale
1018
               get_be16(pb);//Reserved_2
1019

    
1020
                //AMRSpecificBox.(10 bytes)
1021
               
1022
               get_be32(pb); //size
1023
               get_be32(pb); //type=='damr'
1024
               get_be32(pb); //vendor
1025
               get_byte(pb); //decoder version
1026
               get_be16(pb); //mode_set
1027
               get_byte(pb); //mode_change_period
1028
               get_byte(pb); //frames_per_sample
1029

    
1030
               st->duration = AV_NOPTS_VALUE;//Not possible to get from this info, must count number of AMR frames
1031
               if(st->codec.codec_id==CODEC_ID_AMR_NB)
1032
               {
1033
                   st->codec.sample_rate=8000;
1034
                   st->codec.channels=1;
1035
               }
1036
               else //AMR-WB
1037
               {
1038
                   st->codec.sample_rate=16000;
1039
                   st->codec.channels=1;
1040
               }
1041
               st->codec.bits_per_sample=16;
1042
               st->codec.bit_rate=0; /*It is not possible to tell this before we have 
1043
                                       an audio frame and even then every frame can be different*/
1044
            }
1045
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 's' ))
1046
            {
1047
                //This is some stuff for the hint track, lets ignore it!
1048
                //Do some mp4 auto detect.
1049
                c->mp4=1;
1050
                size-=(16);
1051
                url_fskip(pb, size); /* The mp4s atom also contians a esds atom that we can skip*/
1052
            }
1053
            else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 'a' ))
1054
            {
1055
                /* Handle mp4 audio tag */
1056
                get_be32(pb); /* version */
1057
                get_be32(pb);
1058
                st->codec.channels = get_be16(pb); /* channels */
1059
                st->codec.bits_per_sample = get_be16(pb); /* bits per sample */
1060
                get_be32(pb);
1061
                st->codec.sample_rate = get_be16(pb); /* sample rate, not always correct */
1062
                get_be16(pb);
1063
                c->mp4=1;
1064
                {
1065
                MOV_atom_t a = { format, url_ftell(pb), size - (20 + 20 + 8) };
1066
                mov_read_default(c, pb, a);
1067
                }
1068
                /* Get correct sample rate from extradata */
1069
                if(st->codec.extradata_size) {
1070
                   const int samplerate_table[] = {
1071
                     96000, 88200, 64000, 48000, 44100, 32000, 
1072
                     24000, 22050, 16000, 12000, 11025, 8000,
1073
                     7350, 0, 0, 0
1074
                   };
1075
                   unsigned char *px = st->codec.extradata;
1076
                   // 5 bits objectTypeIndex, 4 bits sampleRateIndex, 4 bits channels
1077
                   int samplerate_index = ((px[0] & 7) << 1) + ((px[1] >> 7) & 1);
1078
                   st->codec.sample_rate = samplerate_table[samplerate_index];
1079
                   st->codec.channels = (px[1] >> 3) & 15;
1080
                }
1081
            }
1082
            else if(size>=(16+20))
1083
            {//16 bytes read, reading atleast 20 more
1084
                uint16_t version;
1085
#ifdef DEBUG
1086
                av_log(NULL, AV_LOG_DEBUG, "audio size=0x%X\n",size);
1087
#endif
1088
                version = get_be16(pb); /* version */
1089
                get_be16(pb); /* revision level */
1090
                get_be32(pb); /* vendor */
1091

    
1092
                st->codec.channels = get_be16(pb);                /* channel count */
1093
                st->codec.bits_per_sample = get_be16(pb);        /* sample size */
1094

    
1095
                /* handle specific s8 codec */
1096
                get_be16(pb); /* compression id = 0*/
1097
                get_be16(pb); /* packet size = 0 */
1098

    
1099
                st->codec.sample_rate = ((get_be32(pb) >> 16));
1100
                //av_log(NULL, AV_LOG_DEBUG, "CODECID %d  %d  %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);
1101

    
1102
                switch (st->codec.codec_id) {
1103
                case CODEC_ID_PCM_S16BE:
1104
                    if (st->codec.bits_per_sample == 8)
1105
                        st->codec.codec_id = CODEC_ID_PCM_S8;
1106
                    /* fall */
1107
                case CODEC_ID_PCM_U8:
1108
                    st->codec.bit_rate = st->codec.sample_rate * 8;
1109
                    break;
1110
                default:
1111
                    ;
1112
                }
1113

    
1114
                //Read QT version 1 fields. In version 0 theese dont exist
1115
#ifdef DEBUG
1116
                av_log(NULL, AV_LOG_DEBUG, "version =%d mp4=%d\n",version,c->mp4);
1117
                av_log(NULL, AV_LOG_DEBUG, "size-(16+20+16)=%d\n",size-(16+20+16));
1118
#endif
1119
                if((version==1) && size>=(16+20+16))
1120
                {
1121
                    get_be32(pb); /* samples per packet */
1122
                    get_be32(pb); /* bytes per packet */
1123
                    get_be32(pb); /* bytes per frame */
1124
                    get_be32(pb); /* bytes per sample */
1125
                    if(size>(16+20+16))
1126
                    {
1127
                        //Optional, additional atom-based fields
1128
                        MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
1129
#ifdef DEBUG
1130
                        av_log(NULL, AV_LOG_DEBUG, "offest=0x%X, sizeleft=%d=0x%x,format=%c%c%c%c\n",(int)url_ftell(pb),size - (16 + 20 + 16 ),size - (16 + 20 + 16 ),
1131
                            (format >> 0) & 0xff,
1132
                            (format >> 8) & 0xff,
1133
                            (format >> 16) & 0xff,
1134
                            (format >> 24) & 0xff);
1135
#endif
1136
                        mov_read_default(c, pb, a);
1137
                    }
1138
                }
1139
                else
1140
                {
1141
                    //We should be down to 0 bytes here, but lets make sure.
1142
                    size-=(16+20);
1143
#ifdef DEBUG
1144
                    if(size>0)
1145
                        av_log(NULL, AV_LOG_DEBUG, "skipping 0x%X bytes\n",size-(16+20));
1146
#endif
1147
                    url_fskip(pb, size);
1148
                }
1149
            }
1150
            else
1151
            {
1152
                size-=16;
1153
                //Unknown size, but lets do our best and skip the rest.
1154
#ifdef DEBUG
1155
                av_log(NULL, AV_LOG_DEBUG, "Strange size, skipping 0x%X bytes\n",size);
1156
#endif
1157
                url_fskip(pb, size);
1158
            }
1159
        }
1160
    }
1161

    
1162
    return 0;
1163
}
1164

    
1165
static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1166
{
1167
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1168
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1169
    unsigned int i, entries;
1170

    
1171
    print_atom("stsc", atom);
1172

    
1173
    get_byte(pb); /* version */
1174
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1175

    
1176
    entries = get_be32(pb);
1177
    
1178
    if(entries >= UINT_MAX / sizeof(MOV_sample_to_chunk_tbl))
1179
        return -1;
1180
    
1181
#ifdef DEBUG
1182
av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
1183
#endif
1184
    sc->sample_to_chunk_sz = entries;
1185
    sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
1186
    if (!sc->sample_to_chunk)
1187
        return -1;
1188
    for(i=0; i<entries; i++) {
1189
        sc->sample_to_chunk[i].first = get_be32(pb);
1190
        sc->sample_to_chunk[i].count = get_be32(pb);
1191
        sc->sample_to_chunk[i].id = get_be32(pb);
1192
#ifdef DEBUG
1193
/*        av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id); */
1194
#endif
1195
    }
1196
    return 0;
1197
}
1198

    
1199
static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1200
{
1201
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1202
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1203
    unsigned int i, entries;
1204

    
1205
    print_atom("stss", atom);
1206

    
1207
    get_byte(pb); /* version */
1208
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1209

    
1210
    entries = get_be32(pb);
1211
    
1212
    if(entries >= UINT_MAX / sizeof(long))
1213
        return -1;
1214
    
1215
    sc->keyframe_count = entries;
1216
#ifdef DEBUG
1217
    av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
1218
#endif
1219
    sc->keyframes = (long*) av_malloc(entries * sizeof(long));
1220
    if (!sc->keyframes)
1221
        return -1;
1222
    for(i=0; i<entries; i++) {
1223
        sc->keyframes[i] = get_be32(pb);
1224
#ifdef DEBUG
1225
/*        av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
1226
#endif
1227
    }
1228
    return 0;
1229
}
1230

    
1231
static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1232
{
1233
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1234
    MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1235
    unsigned int i, entries;
1236

    
1237
    print_atom("stsz", atom);
1238

    
1239
    get_byte(pb); /* version */
1240
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1241

    
1242
    sc->sample_size = get_be32(pb);
1243
    entries = get_be32(pb);
1244
    if(entries >= UINT_MAX / sizeof(long))
1245
        return -1;
1246

    
1247
    sc->sample_count = entries;
1248
#ifdef DEBUG
1249
    av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
1250
#endif
1251
    if(sc->sample_size)
1252
        return 0; /* there isn't any table following */
1253
    sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
1254
    if (!sc->sample_sizes)
1255
        return -1;
1256
    for(i=0; i<entries; i++) {
1257
        sc->sample_sizes[i] = get_be32(pb);
1258
#ifdef DEBUG
1259
        av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]);
1260
#endif
1261
    }
1262
    return 0;
1263
}
1264

    
1265
static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1266
{
1267
    AVStream *st = c->fc->streams[c->fc->nb_streams-1];
1268
    //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
1269
    unsigned int i, entries;
1270
    int64_t duration=0;
1271
    int64_t total_sample_count=0;
1272

    
1273
    print_atom("stts", atom);
1274

    
1275
    get_byte(pb); /* version */
1276
    get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1277
    entries = get_be32(pb);
1278
    if(entries >= UINT_MAX / sizeof(uint64_t))
1279
        return -1;
1280

    
1281
    c->streams[c->fc->nb_streams-1]->stts_count = entries;
1282
    c->streams[c->fc->nb_streams-1]->stts_data = (uint64_t*) av_malloc(entries * sizeof(uint64_t));
1283

    
1284
#ifdef DEBUG
1285
av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
1286
#endif
1287
    for(i=0; i<entries; i++) {
1288
        int32_t sample_duration;
1289
        int32_t sample_count;
1290

    
1291
        sample_count=get_be32(pb);
1292
        sample_duration = get_be32(pb);
1293
        c->streams[c->fc->nb_streams - 1]->stts_data[i] = (uint64_t)sample_count<<32 | (uint64_t)sample_duration;
1294
#ifdef DEBUG
1295
        av_log(NULL, AV_LOG_DEBUG, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
1296
#endif
1297
        duration+=sample_duration*sample_count;
1298
        total_sample_count+=sample_count;
1299

    
1300
#if 0 //We calculate an average instead, needed by .mp4-files created with nec e606 3g phone
1301

1302
        if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
1303
            st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
1304
            st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1305
#ifdef DEBUG
1306
            av_log(NULL, AV_LOG_DEBUG, "VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
1307
#endif
1308
        }
1309
#endif
1310
    }
1311

    
1312
    /*The stsd atom which contain codec type sometimes comes after the stts so we cannot check for codec_type*/
1313
    if(duration>0)
1314
    {
1315
        av_reduce(
1316
            &st->codec.frame_rate, 
1317
            &st->codec.frame_rate_base, 
1318
            c->streams[c->fc->nb_streams-1]->time_scale * total_sample_count,
1319
            duration,
1320
            INT_MAX
1321
        );
1322

    
1323
#ifdef DEBUG
1324
        av_log(NULL, AV_LOG_DEBUG, "FRAME RATE average (video or audio)= %f (tot sample count= %i ,tot dur= %i timescale=%d)\n", (float)st->codec.frame_rate/st->codec.frame_rate_base,total_sample_count,duration,c->streams[c->fc->nb_streams-1]->time_scale);
1325
#endif
1326
    }
1327
    else
1328
    {
1329
        st->codec.frame_rate_base = 1;
1330
        st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
1331
    }
1332
    return 0;
1333
}
1334

    
1335
static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1336
{
1337
    AVStream *st;
1338
    MOVStreamContext *sc;
1339

    
1340
    print_atom("trak", atom);
1341

    
1342
    st = av_new_stream(c->fc, c->fc->nb_streams);
1343
    if (!st) return -2;
1344
    sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
1345
    if (!sc) {
1346
        av_free(st);
1347
        return -1;
1348
    }
1349

    
1350
    sc->sample_to_chunk_index = -1;
1351
    st->priv_data = sc;
1352
    st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
1353
    st->start_time = 0; /* XXX: check */
1354
    st->duration = (c->duration * (int64_t)AV_TIME_BASE) / c->time_scale;
1355
    c->streams[c->fc->nb_streams-1] = sc;
1356

    
1357
    return mov_read_default(c, pb, atom);
1358
}
1359

    
1360
static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1361
{
1362
    AVStream *st;
1363

    
1364
    print_atom("tkhd", atom);
1365

    
1366
    st = c->fc->streams[c->fc->nb_streams-1];
1367

    
1368
    get_byte(pb); /* version */
1369

    
1370
    get_byte(pb); get_byte(pb);
1371
    get_byte(pb); /* flags */
1372
    /*
1373
    MOV_TRACK_ENABLED 0x0001
1374
    MOV_TRACK_IN_MOVIE 0x0002
1375
    MOV_TRACK_IN_PREVIEW 0x0004
1376
    MOV_TRACK_IN_POSTER 0x0008
1377
    */
1378

    
1379
    get_be32(pb); /* creation time */
1380
    get_be32(pb); /* modification time */
1381
    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
1382
    get_be32(pb); /* reserved */
1383
    st->start_time = 0; /* check */
1384
    st->duration = (get_be32(pb) * (int64_t)AV_TIME_BASE) / c->time_scale; /* duration */
1385
    get_be32(pb); /* reserved */
1386
    get_be32(pb); /* reserved */
1387

    
1388
    get_be16(pb); /* layer */
1389
    get_be16(pb); /* alternate group */
1390
    get_be16(pb); /* volume */
1391
    get_be16(pb); /* reserved */
1392

    
1393
    url_fskip(pb, 36); /* display matrix */
1394

    
1395
    /* those are fixed-point */
1396
    st->codec.width = get_be32(pb) >> 16; /* track width */
1397
    st->codec.height = get_be32(pb) >> 16; /* track height */
1398

    
1399
    return 0;
1400
}
1401

    
1402
/* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
1403
/* like the files created with Adobe Premiere 5.0, for samples see */
1404
/* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
1405
static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1406
{
1407
    int err;
1408

    
1409
#ifdef DEBUG
1410
    print_atom("wide", atom);
1411
    debug_indent++;
1412
#endif
1413
    if (atom.size < 8)
1414
        return 0; /* continue */
1415
    if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
1416
        url_fskip(pb, atom.size - 4);
1417
        return 0;
1418
    }
1419
    atom.type = get_le32(pb);
1420
    atom.offset += 8;
1421
    atom.size -= 8;
1422
    if (atom.type != MKTAG('m', 'd', 'a', 't')) {
1423
        url_fskip(pb, atom.size);
1424
        return 0;
1425
    }
1426
    err = mov_read_mdat(c, pb, atom);
1427
#ifdef DEBUG
1428
    debug_indent--;
1429
#endif
1430
    return err;
1431
}
1432

    
1433

    
1434
#ifdef CONFIG_ZLIB
1435
static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
1436
{
1437
    return -1;
1438
}
1439

    
1440
static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1441
{
1442
    ByteIOContext ctx;
1443
    uint8_t *cmov_data;
1444
    uint8_t *moov_data; /* uncompressed data */
1445
    long cmov_len, moov_len;
1446
    int ret;
1447

    
1448
    print_atom("cmov", atom);
1449

    
1450
    get_be32(pb); /* dcom atom */
1451
    if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
1452
        return -1;
1453
    if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
1454
        av_log(NULL, AV_LOG_DEBUG, "unknown compression for cmov atom !");
1455
        return -1;
1456
    }
1457
    get_be32(pb); /* cmvd atom */
1458
    if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
1459
        return -1;
1460
    moov_len = get_be32(pb); /* uncompressed size */
1461
    cmov_len = atom.size - 6 * 4;
1462

    
1463
    cmov_data = (uint8_t *) av_malloc(cmov_len);
1464
    if (!cmov_data)
1465
        return -1;
1466
    moov_data = (uint8_t *) av_malloc(moov_len);
1467
    if (!moov_data) {
1468
        av_free(cmov_data);
1469
        return -1;
1470
    }
1471
    get_buffer(pb, cmov_data, cmov_len);
1472
    if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
1473
        return -1;
1474
    if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
1475
        return -1;
1476
    ctx.buf_end = ctx.buffer + moov_len;
1477
    atom.type = MKTAG( 'm', 'o', 'o', 'v' );
1478
    atom.offset = 0;
1479
    atom.size = moov_len;
1480
#ifdef DEBUG
1481
    { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
1482
#endif
1483
    ret = mov_read_default(c, &ctx, atom);
1484
    av_free(moov_data);
1485
    av_free(cmov_data);
1486

    
1487
    return ret;
1488
}
1489
#endif
1490

    
1491
/* edit list atom */
1492
static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
1493
{
1494
  int i, edit_count;
1495
  print_atom("elst", atom);
1496

    
1497
  get_byte(pb); /* version */
1498
  get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
1499
  edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb);     /* entries */
1500
  
1501
  for(i=0; i<edit_count; i++){
1502
    get_be32(pb); /* Track duration */
1503
    get_be32(pb); /* Media time */
1504
    get_be32(pb); /* Media rate */
1505
  }
1506
#ifdef DEBUG
1507
  av_log(NULL, AV_LOG_DEBUG, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
1508
#endif
1509
  return 0;
1510
}
1511

    
1512
static const MOVParseTableEntry mov_default_parse_table[] = {
1513
/* mp4 atoms */
1514
{ MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
1515
{ MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
1516
{ MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
1517
{ MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
1518
{ MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
1519
{ MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
1520
{ MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
1521
{ MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
1522
{ MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
1523
{ MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
1524
{ MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
1525
{ MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
1526
{ MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
1527
{ MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
1528
{ MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
1529
{ MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
1530
{ MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
1531
{ MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
1532
{ MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
1533
{ MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
1534
{ MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
1535
{ MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
1536
{ MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
1537
{ MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
1538
{ MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
1539
{ MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
1540
{ MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
1541
{ MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
1542
{ MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
1543
{ MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorenson extension ??? */
1544
{ MKTAG( 'a', 'v', 'c', 'C' ), mov_read_avcC }, 
1545
{ MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
1546
{ MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
1547
{ MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
1548
{ MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
1549
{ MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
1550
{ MKTAG( 's', 't', 's', 'h' ), mov_read_default },
1551
{ MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
1552
{ MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
1553
{ MKTAG( 's', 't', 't', 's' ), mov_read_stts },
1554
{ MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
1555
{ MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
1556
{ MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
1557
{ MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
1558
{ MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
1559
{ MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
1560
{ MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
1561
{ MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
1562
{ MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
1563
/* extra mp4 */
1564
{ MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
1565
/* QT atoms */
1566
{ MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
1567
{ MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
1568
{ MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
1569
{ MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
1570
{ MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
1571
{ MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
1572
{ MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
1573
{ MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
1574
{ MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
1575
{ MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
1576
{ MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
1577
{ MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
1578
{ MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
1579
{ MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
1580
{ MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
1581
{ MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
1582
//{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
1583
#ifdef CONFIG_ZLIB
1584
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
1585
#else
1586
{ MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
1587
#endif
1588
{ 0L, mov_read_leaf }
1589
};
1590

    
1591
static void mov_free_stream_context(MOVStreamContext *sc)
1592
{
1593
    if(sc) {
1594
        av_free(sc->chunk_offsets);
1595
        av_free(sc->sample_to_chunk);
1596
        av_free(sc->sample_sizes);
1597
        av_free(sc->keyframes);
1598
        av_free(sc->header_data);
1599
        av_free(sc->stts_data);        
1600
        av_free(sc);
1601
    }
1602
}
1603

    
1604
static inline uint32_t mov_to_tag(uint8_t *buf)
1605
{
1606
    return MKTAG(buf[0], buf[1], buf[2], buf[3]);
1607
}
1608

    
1609
static inline uint32_t to_be32(uint8_t *buf)
1610
{
1611
    return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
1612
}
1613

    
1614
/* XXX: is it sufficient ? */
1615
static int mov_probe(AVProbeData *p)
1616
{
1617
    unsigned int offset;
1618
    uint32_t tag;
1619

    
1620
    /* check file header */
1621
    if (p->buf_size <= 12)
1622
        return 0;
1623
    offset = 0;
1624
    for(;;) {
1625
        /* ignore invalid offset */
1626
        if ((offset + 8) > (unsigned int)p->buf_size)
1627
            return 0;
1628
        tag = mov_to_tag(p->buf + offset + 4);
1629
        switch(tag) {
1630
        case MKTAG( 'm', 'o', 'o', 'v' ):
1631
        case MKTAG( 'w', 'i', 'd', 'e' ):
1632
        case MKTAG( 'f', 'r', 'e', 'e' ):
1633
        case MKTAG( 'm', 'd', 'a', 't' ):
1634
        case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
1635
        case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
1636
            return AVPROBE_SCORE_MAX;
1637
        case MKTAG( 'f', 't', 'y', 'p' ):
1638
        case MKTAG( 's', 'k', 'i', 'p' ):
1639
            offset = to_be32(p->buf+offset) + offset;
1640
            break;
1641
        default:
1642
            /* unrecognized tag */
1643
            return 0;
1644
        }
1645
    }
1646
    return 0;
1647
}
1648

    
1649
static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
1650
{
1651
    MOVContext *mov = (MOVContext *) s->priv_data;
1652
    ByteIOContext *pb = &s->pb;
1653
    int i, j, nb, err;
1654
    MOV_atom_t atom = { 0, 0, 0 };
1655

    
1656
    mov->fc = s;
1657
    mov->parse_table = mov_default_parse_table;
1658
#if 0
1659
    /* XXX: I think we should auto detect */
1660
    if(s->iformat->name[1] == 'p')
1661
        mov->mp4 = 1;
1662
#endif
1663
    if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
1664
        atom.size = url_filesize(url_fileno(pb));
1665
    else
1666
        atom.size = 0x7FFFFFFFFFFFFFFFLL;
1667

    
1668
#ifdef DEBUG
1669
    av_log(NULL, AV_LOG_DEBUG, "filesz=%Ld\n", atom.size);
1670
#endif
1671

    
1672
    /* check MOV header */
1673
    err = mov_read_default(mov, pb, atom);
1674
    if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
1675
        av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%lld\n",
1676
                err, mov->found_moov, mov->found_mdat, url_ftell(pb));
1677
        return -1;
1678
    }
1679
#ifdef DEBUG
1680
    av_log(NULL, AV_LOG_DEBUG, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
1681
#endif
1682
    /* some cleanup : make sure we are on the mdat atom */
1683
    if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
1684
        url_fseek(pb, mov->mdat_offset, SEEK_SET);
1685

    
1686
    mov->next_chunk_offset = mov->mdat_offset; /* initialise reading */
1687

    
1688
#ifdef DEBUG
1689
    av_log(NULL, AV_LOG_DEBUG, "mdat_reset_offset=%d\n", (int) url_ftell(pb));
1690
#endif
1691

    
1692
#ifdef DEBUG
1693
    av_log(NULL, AV_LOG_DEBUG, "streams= %d\n", s->nb_streams);
1694
#endif
1695
    mov->total_streams = nb = s->nb_streams;
1696

    
1697
#if 1
1698
    for(i=0; i<s->nb_streams;) {
1699
        if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
1700
            av_free(s->streams[i]);
1701
            for(j=i+1; j<s->nb_streams; j++)
1702
                s->streams[j-1] = s->streams[j];
1703
            s->nb_streams--;
1704
        } else
1705
            i++;
1706
    }
1707
    for(i=0; i<s->nb_streams;i++) {
1708
        MOVStreamContext *sc;
1709
        sc = (MOVStreamContext *)s->streams[i]->priv_data;
1710
        sc->ffindex = i;
1711
        sc->is_ff_stream = 1;
1712
    }
1713
#endif
1714
#ifdef DEBUG
1715
    av_log(NULL, AV_LOG_DEBUG, "real streams= %d\n", s->nb_streams);
1716
#endif
1717
    return 0;
1718
}
1719

    
1720
/* Yes, this is ugly... I didn't write the specs of QT :p */
1721
/* XXX:remove useless commented code sometime */
1722
static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
1723
{
1724
    MOVContext *mov = (MOVContext *) s->priv_data;
1725
    MOVStreamContext *sc;
1726
    int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
1727
    int i, a, b, m;
1728
    int size;
1729
    int idx;
1730
    size = 0x0FFFFFFF;
1731

    
1732
#ifdef MOV_SPLIT_CHUNKS
1733
    if (mov->partial) {
1734
        sc = mov->partial;
1735
        idx = sc->sample_to_chunk_index;
1736

    
1737
        if (idx < 0) return 0;
1738
#ifdef DEBUG
1739
        fprintf(stderr, "sc[ffid %d]->sample_size = %d\n", sc->ffindex, sc->sample_size);
1740
#endif
1741
        //size = sc->sample_sizes[sc->current_sample];
1742
        // that ain't working...
1743
        //size = (sc->sample_size)?sc->sample_size:sc->sample_sizes[sc->current_sample];
1744
        size = (sc->sample_size > 1)?sc->sample_size:sc->sample_sizes[sc->current_sample];
1745

    
1746
        sc->current_sample++;
1747
        sc->left_in_chunk--;
1748

    
1749
        if (sc->left_in_chunk <= 0)
1750
            mov->partial = 0;
1751
        offset = mov->next_chunk_offset;
1752
        /* extract the sample */
1753

    
1754
        goto readchunk;
1755
    }
1756
#endif
1757

    
1758
again:
1759
    sc = 0;
1760
    for(i=0; i<mov->total_streams; i++) {
1761
        MOVStreamContext *msc = mov->streams[i];
1762
        //av_log(NULL, AV_LOG_DEBUG, "MOCHUNK %ld  %d   %p  pos:%Ld\n", mov->streams[i]->next_chunk, mov->total_streams, mov->streams[i], url_ftell(&s->pb));
1763
        if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
1764
           && (msc->chunk_offsets[msc->next_chunk] < offset)) {
1765
            sc = msc;
1766
            offset = msc->chunk_offsets[msc->next_chunk];
1767
            //av_log(NULL, AV_LOG_DEBUG, "SELETED  %Ld  i:%d\n", offset, i);
1768
        }
1769
    }
1770
    if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
1771
        return -1;
1772

    
1773
    sc->next_chunk++;
1774

    
1775
    if(mov->next_chunk_offset < offset) { /* some meta data */
1776
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1777
        mov->next_chunk_offset = offset;
1778
    }
1779

    
1780
//av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
1781
    if(!sc->is_ff_stream || s->streams[sc->ffindex]->discard) {
1782
        url_fskip(&s->pb, (offset - mov->next_chunk_offset));
1783
        mov->next_chunk_offset = offset;
1784
        offset = 0x0FFFFFFFFFFFFFFFLL;
1785
        goto again;
1786
    }
1787

    
1788
    /* now get the chunk size... */
1789

    
1790
    for(i=0; i<mov->total_streams; i++) {
1791
        MOVStreamContext *msc = mov->streams[i];
1792
        if ((msc->next_chunk < msc->chunk_count)
1793
            && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
1794
            size = msc->chunk_offsets[msc->next_chunk] - offset;
1795
    }
1796

    
1797
#ifdef MOV_MINOLTA_FIX
1798
    //Make sure that size is according to sample_size (Needed by .mov files 
1799
    //created on a Minolta Dimage Xi where audio chunks contains waste data in the end)
1800
    //Maybe we should really not only check sc->sample_size, but also sc->sample_sizes
1801
    //but I have no such movies
1802
    if (sc->sample_size > 0) { 
1803
        int foundsize=0;
1804
        for(i=0; i<(sc->sample_to_chunk_sz); i++) {
1805
            if( (sc->sample_to_chunk[i].first)<=(sc->next_chunk) && (sc->sample_size>0) )
1806
            {
1807
                // I can't figure out why for PCM audio sample_size is always 1
1808
                // (it should actually be channels*bits_per_second/8) but it is.
1809
                AVCodecContext* cod = &s->streams[sc->ffindex]->codec;
1810
                if (sc->sample_size == 1 && (cod->codec_id == CODEC_ID_PCM_S16BE || cod->codec_id == CODEC_ID_PCM_S16LE))
1811
                    foundsize=(sc->sample_to_chunk[i].count*cod->channels*cod->bits_per_sample)/8;
1812
                else
1813
                    foundsize=sc->sample_to_chunk[i].count*sc->sample_size;
1814
            }
1815
#ifdef DEBUG
1816
            av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id);
1817
#endif
1818
        }
1819
        if( (foundsize>0) && (foundsize<size) )
1820
        {
1821
#ifdef DEBUG
1822
            /*av_log(NULL, AV_LOG_DEBUG, "this size should actually be %d\n",foundsize);*/
1823
#endif
1824
            size=foundsize;
1825
        }
1826
    }
1827
#endif //MOV_MINOLTA_FIX
1828

    
1829
#ifdef MOV_SPLIT_CHUNKS
1830
    /* split chunks into samples */
1831
    if (sc->sample_size == 0) {
1832
        idx = sc->sample_to_chunk_index;
1833
        if ((idx + 1 < sc->sample_to_chunk_sz)
1834
                && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
1835
            idx++;
1836
        sc->sample_to_chunk_index = idx;
1837
        if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
1838
            mov->partial = sc;
1839
            /* we'll have to get those samples before next chunk */
1840
            sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
1841
            size = (sc->sample_size > 1)?sc->sample_size:sc->sample_sizes[sc->current_sample];
1842
        }
1843

    
1844
        sc->current_sample++;
1845
    }
1846
#endif
1847

    
1848
readchunk:
1849
#ifdef DEBUG
1850
    av_log(NULL, AV_LOG_DEBUG, "chunk: %lli -> %lli (%i)\n", offset, offset + size, size);
1851
#endif
1852
    if(size == 0x0FFFFFFF)
1853
        size = mov->mdat_size + mov->mdat_offset - offset;
1854
    if(size < 0)
1855
        return -1;
1856
    if(size == 0)
1857
        return -1;
1858
    url_fseek(&s->pb, offset, SEEK_SET);
1859

    
1860
    //av_log(NULL, AV_LOG_DEBUG, "READCHUNK hlen: %d  %d off: %Ld   pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
1861
    if (sc->header_len > 0) {
1862
        av_new_packet(pkt, size + sc->header_len);
1863
        memcpy(pkt->data, sc->header_data, sc->header_len);
1864
        get_buffer(&s->pb, pkt->data + sc->header_len, size);
1865
        /* free header */
1866
        av_freep(&sc->header_data);
1867
        sc->header_len = 0;
1868
    } else {
1869
        av_new_packet(pkt, size);
1870
        get_buffer(&s->pb, pkt->data, pkt->size);
1871
    }
1872
    pkt->stream_index = sc->ffindex;
1873
    
1874
    // If the keyframes table exists, mark any samples that are in the table as key frames.
1875
    // If no table exists, treat very sample as a key frame.
1876
    if (sc->keyframes) {        
1877
        a = 0;
1878
        b = sc->keyframe_count - 1;
1879
        
1880
        while (a < b) {
1881
            m = (a + b + 1) >> 1;
1882
            if (sc->keyframes[m] > sc->current_sample) {
1883
                b = m - 1;
1884
            } else {
1885
                a = m;
1886
            }    
1887
        }
1888
        
1889
        if (sc->keyframes[a] == sc->current_sample)
1890
            pkt->flags |= PKT_FLAG_KEY;
1891
    }
1892
    else
1893
        pkt->flags |= PKT_FLAG_KEY;
1894

    
1895
#ifdef DEBUG
1896
/*
1897
    av_log(NULL, AV_LOG_DEBUG, "Packet (%d, %ld) ", pkt->stream_index, pkt->size);
1898
    for(i=0; i<8; i++)
1899
        av_log(NULL, AV_LOG_DEBUG, "%02x ", pkt->data[i]);
1900
    for(i=0; i<8; i++)
1901
        av_log(NULL, AV_LOG_DEBUG, "%c ", (pkt->data[i]) & 0x7F);
1902
    av_log(NULL, AV_LOG_DEBUG, "\n");
1903
*/
1904
#endif
1905

    
1906
    mov->next_chunk_offset = offset + size;
1907
    
1908
    /* find the corresponding dts */         
1909
    if (sc && sc->sample_to_time_index < sc->stts_count && pkt) {         
1910
      uint32_t count;         
1911
      uint64_t dts;         
1912
      uint32_t duration = (uint32_t)(sc->stts_data[sc->sample_to_time_index]&0xffff);         
1913
      count = (uint32_t)(sc->stts_data[sc->sample_to_time_index]>>32);         
1914
      if ((sc->sample_to_time_sample + count) < sc->current_sample) {         
1915
        sc->sample_to_time_sample += count;         
1916
        sc->sample_to_time_time   += count*duration;         
1917
        sc->sample_to_time_index ++;         
1918
        duration = (uint32_t)(sc->stts_data[sc->sample_to_time_index]&0xffff);         
1919
      }         
1920
      dts = sc->sample_to_time_time + (sc->current_sample-1 - sc->sample_to_time_sample) * duration;         
1921
      dts = av_rescale( dts,          
1922
                        (int64_t)s->streams[sc->ffindex]->time_base.den,          
1923
                        (int64_t)sc->time_scale * (int64_t)s->streams[sc->ffindex]->time_base.num );         
1924
      pkt->dts = dts;         
1925
      // audio pts = dts, true for video only in low_latency mode (FIXME a good way to know if we are in a low latency stream ?)         
1926
      if (s->streams[sc->ffindex]->codec.codec_type == CODEC_TYPE_AUDIO)         
1927
        pkt->pts = dts;         
1928
      else          
1929
        pkt->pts = AV_NOPTS_VALUE;         
1930
#ifdef DEBUG          
1931
/*    av_log(NULL, AV_LOG_DEBUG, "stream #%d smp #%ld dts = %ld (smp:%ld time:%ld idx:%ld ent:%d count:%ld dur:%ld)\n"         
1932
      , pkt->stream_index, sc->current_sample-1, (long)pkt->dts         
1933
      , (long)sc->sample_to_time_sample         
1934
      , (long)sc->sample_to_time_time         
1935
      , (long)sc->sample_to_time_index         
1936
      , (long)sc->stts_count         
1937
      , count         
1938
      , duration);*/         
1939
#endif                 
1940
    } 
1941

    
1942
    return 0;
1943
}
1944

    
1945
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
1946
/**
1947
 * Seek method based on the one described in the Appendix C of QTFileFormat.pdf
1948
 */
1949
static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1950
{
1951
    MOVContext* mov = (MOVContext *) s->priv_data;
1952
    MOVStreamContext* sc;
1953
    int32_t i, a, b, m;
1954
    int64_t sample_time;
1955
    int64_t start_time;
1956
    int32_t seek_sample, sample;
1957
    int32_t duration;
1958
    int32_t count;
1959
    int32_t chunk;
1960
    int32_t left_in_chunk;
1961
    int64_t chunk_file_offset;
1962
    int64_t sample_file_offset;
1963
    int32_t first_chunk_sample;
1964
    int32_t sample_to_chunk_idx;
1965
    int sample_to_time_index;         
1966
    long sample_to_time_sample = 0;         
1967
    uint64_t sample_to_time_time = 0;      
1968
    int mov_idx;
1969

    
1970
    // Find the corresponding mov stream
1971
    for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++)
1972
        if (mov->streams[mov_idx]->ffindex == stream_index)
1973
            break;
1974
    if (mov_idx == mov->total_streams) {
1975
        av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index);
1976
        return -1;
1977
    }
1978
    sc = mov->streams[mov_idx];
1979

    
1980
    // Step 1. Find the edit that contains the requested time (elst)
1981
    if (sc->edit_count) {
1982
        // FIXME should handle edit list
1983
        av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count);
1984
        return -1;
1985
    }
1986

    
1987
    // Step 2. Find the corresponding sample using the Time-to-sample atom (stts) */
1988
#ifdef DEBUG
1989
  av_log(s, AV_LOG_DEBUG, "Searching for time %li in stream #%i (time_scale=%i)\n", (long)timestamp, mov_idx, sc->time_scale);
1990
#endif
1991
    // convert timestamp from time_base unit to timescale unit
1992
    sample_time = av_rescale( timestamp,
1993
                            (int64_t)sc->time_scale * s->streams[stream_index]->time_base.num,
1994
                            (int64_t)s->streams[stream_index]->time_base.den);
1995
    start_time = 0; // FIXME use elst atom
1996
    sample = 1; // sample are 0 based in table
1997
#ifdef DEBUG
1998
    av_log(s, AV_LOG_DEBUG, "Searching for sample_time %li \n", (long)sample_time);
1999
#endif
2000
    for (i = 0; i < sc->stts_count; i++) {
2001
        count = (uint32_t)(sc->stts_data[i]>>32);
2002
        duration = (uint32_t)(sc->stts_data[i]&0xffff);
2003
//av_log(s, AV_LOG_DEBUG, "> sample_time %lli \n", (long)sample_time);                
2004
//av_log(s, AV_LOG_DEBUG, "> count=%i duration=%i\n", count, duration);        
2005
        if ((start_time + count*duration) > sample_time) {
2006
            sample_to_time_time = start_time;         
2007
            sample_to_time_index = i;         
2008
            sample_to_time_sample = sample;         
2009
            sample += (sample_time - start_time) / duration;
2010
            break;
2011
        }
2012
        sample += count;
2013
        start_time += count * duration;
2014
    }   
2015
    sample_to_time_time = start_time;         
2016
    sample_to_time_index = i;       
2017
    /* NOTE: despite what qt doc say, the dt value (Display Time in qt vocabulary) computed with the stts atom
2018
       is a decoding time stamp (dts) not a presentation time stamp. And as usual dts != pts for stream with b frames */
2019

    
2020
#ifdef DEBUG
2021
    av_log(s, AV_LOG_DEBUG, "Found time %li at sample #%u\n", (long)sample_time, sample);
2022
#endif
2023
    if (sample > sc->sample_count) {
2024
        av_log(s, AV_LOG_ERROR, "mov: sample pos is too high, unable to seek (req. sample=%i, sample count=%ld)\n", sample, sc->sample_count);
2025
        return -1;
2026
    }
2027

    
2028
    // Step 3. Find the prior sync. sample using the Sync sample atom (stss)
2029
    if (sc->keyframes) {
2030
        a = 0;
2031
        b = sc->keyframe_count - 1;
2032
        while (a < b) {
2033
            m = (a + b + 1) >> 1;
2034
            if (sc->keyframes[m] > sample) {
2035
                b = m - 1;
2036
            } else {
2037
                a = m;
2038
            }
2039
#ifdef DEBUG
2040
         // av_log(s, AV_LOG_DEBUG, "a=%i (%i) b=%i (%i) m=%i (%i) stream #%i\n", a, sc->keyframes[a], b, sc->keyframes[b], m, sc->keyframes[m], mov_idx);
2041
#endif
2042
        }
2043
        // for low latency prob: always use the previous keyframe, just uncomment the next line
2044
        // if (a) a--;
2045
        seek_sample = sc->keyframes[a];
2046
    }
2047
    else
2048
        seek_sample = sample; // else all samples are key frames
2049
#ifdef DEBUG
2050
    av_log(s, AV_LOG_DEBUG, "Found nearest keyframe at sample #%i \n", seek_sample);
2051
#endif
2052

    
2053
    // Step 4. Find the chunk of the sample using the Sample-to-chunk-atom (stsc)
2054
    for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) {
2055
        b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count;
2056
        if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b))
2057
            break;
2058
        first_chunk_sample += b;
2059
    }
2060
    chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count;
2061
    left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count;
2062
    first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count;
2063
    sample_to_chunk_idx = i;
2064
#ifdef DEBUG
2065
    av_log(s, AV_LOG_DEBUG, "Sample was found in chunk #%i at sample offset %i (idx %i)\n", chunk, seek_sample - first_chunk_sample, sample_to_chunk_idx);
2066
#endif
2067

    
2068
    // Step 5. Find the offset of the chunk using the chunk offset atom
2069
    if (!sc->chunk_offsets) {
2070
        av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n");
2071
        return -1;
2072
    }
2073
    if (chunk > sc->chunk_count) {
2074
        av_log(s, AV_LOG_ERROR, "mov: chunk offset atom too short, unable to seek (req. chunk=%i, chunk count=%li)\n", chunk, sc->chunk_count);
2075
        return -1;
2076
    }
2077
    chunk_file_offset = sc->chunk_offsets[chunk - 1];
2078
#ifdef DEBUG
2079
    av_log(s, AV_LOG_DEBUG, "Chunk file offset is #%llu \n", chunk_file_offset);
2080
#endif
2081

    
2082
    // Step 6. Find the byte offset within the chunk using the sample size atom
2083
    sample_file_offset = chunk_file_offset;
2084
    if (sc->sample_size)
2085
        sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size;
2086
    else {
2087
        for (i = 0; i < (seek_sample - first_chunk_sample); i++) {
2088
        sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1];
2089
        }
2090
    }
2091
#ifdef DEBUG
2092
    av_log(s, AV_LOG_DEBUG, "Sample file offset is #%llu \n", sample_file_offset);
2093
#endif
2094

    
2095
    // Step 6. Update the parser
2096
    mov->partial = sc;
2097
    mov->next_chunk_offset = sample_file_offset;
2098
    // Update current stream state
2099
    sc->current_sample = seek_sample - 1;  // zero based
2100
    sc->left_in_chunk = left_in_chunk;
2101
    sc->next_chunk = chunk; // +1 -1 (zero based)
2102
    sc->sample_to_chunk_index = sample_to_chunk_idx;
2103

    
2104
    // Update other streams    
2105
    for (i = 0; i<mov->total_streams; i++) {
2106
        MOVStreamContext *msc;
2107
        if (i == mov_idx) continue;
2108
        // Find the nearest 'next' chunk
2109
        msc = mov->streams[i];
2110
        a = 0;
2111
        b = msc->chunk_count - 1;
2112
        while (a < b) {
2113
            m = (a + b + 1) >> 1;
2114
            if (msc->chunk_offsets[m] > chunk_file_offset) {
2115
                b = m - 1;
2116
            } else {
2117
                a = m;
2118
            }
2119
#ifdef DEBUG            
2120
/*            av_log(s, AV_LOG_DEBUG, "a=%i (%li) b=%i (%li) m=%i (%li) stream #%i\n"
2121
            , a, (long)msc->chunk_offsets[a], b, (long)msc->chunk_offsets[b], m, (long)msc->chunk_offsets[m],  i); */
2122
#endif                  
2123
        }
2124
        msc->next_chunk = a;
2125
        if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1))
2126
            msc->next_chunk ++;
2127
#ifdef DEBUG        
2128
        av_log(s, AV_LOG_DEBUG, "Nearest next chunk for stream #%i is #%i @%lli\n", i, msc->next_chunk+1, msc->chunk_offsets[msc->next_chunk]);
2129
#endif        
2130
        // Compute sample count and index in the sample_to_chunk table (what a pity)
2131
        msc->sample_to_chunk_index = 0;
2132
        msc->current_sample = 0;
2133
        for(;  msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1)
2134
            && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) {
2135
            msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \
2136
            * msc->sample_to_chunk[msc->sample_to_chunk_index].count;
2137
        }
2138
        msc->current_sample += (msc->next_chunk - (msc->sample_to_chunk[msc->sample_to_chunk_index].first - 1)) * sc->sample_to_chunk[msc->sample_to_chunk_index].count;
2139
        msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1;
2140
        // Find corresponding position in stts (used later to compute dts)         
2141
        sample = 0;         
2142
        start_time = 0;         
2143
        for (msc->sample_to_time_index = 0; msc->sample_to_time_index < msc->stts_count; msc->sample_to_time_index++) {         
2144
            count = (uint32_t)(msc->stts_data[msc->sample_to_time_index]>>32);         
2145
            duration = (uint32_t)(msc->stts_data[msc->sample_to_time_index]&0xffff);         
2146
            if ((sample + count - 1) > msc->current_sample) {         
2147
                msc->sample_to_time_time = start_time;         
2148
                msc->sample_to_time_sample = sample;         
2149
                break;         
2150
            }         
2151
            sample += count;         
2152
            start_time += count * duration;         
2153
        }        
2154
#ifdef DEBUG        
2155
        av_log(s, AV_LOG_DEBUG, "Next Sample for stream #%i is #%i @%i\n", i, msc->current_sample + 1, msc->sample_to_chunk_index + 1);
2156
#endif        
2157
    }                
2158
    return 0;
2159
}
2160
#endif
2161

    
2162
static int mov_read_close(AVFormatContext *s)
2163
{
2164
    int i;
2165
    MOVContext *mov = (MOVContext *) s->priv_data;
2166
    for(i=0; i<mov->total_streams; i++)
2167
        mov_free_stream_context(mov->streams[i]);
2168
    /* free color tabs */
2169
    for(i=0; i<mov->ctab_size; i++)
2170
        av_freep(&mov->ctab[i]);
2171
    av_freep(&mov->ctab);
2172
    return 0;
2173
}
2174

    
2175
static AVInputFormat mov_iformat = {
2176
    "mov,mp4,m4a,3gp",
2177
    "QuickTime/MPEG4 format",
2178
    sizeof(MOVContext),
2179
    mov_probe,
2180
    mov_read_header,
2181
    mov_read_packet,
2182
    mov_read_close,
2183
#if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
2184
    mov_read_seek,
2185
#endif    
2186
};
2187

    
2188
int mov_init(void)
2189
{
2190
    av_register_input_format(&mov_iformat);
2191
    return 0;
2192
}