]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
input_item: compress two functions into one and rename "Add" into "Post" for clarity...
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 the VideoLAN team
5  * $Id$
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33
34
35 #include <vlc_demux.h>
36 #include <vlc_md5.h>
37 #include <vlc_charset.h>
38 #include <vlc_iso_lang.h>
39 #include <vlc_meta.h>
40 #include <vlc_input.h>
41
42 #include "libmp4.h"
43 #include "drms.h"
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 static int  Open ( vlc_object_t * );
49 static void Close( vlc_object_t * );
50
51 vlc_module_begin ()
52     set_category( CAT_INPUT )
53     set_subcategory( SUBCAT_INPUT_DEMUX )
54     set_description( N_("MP4 stream demuxer") )
55     set_shortname( N_("MP4") )
56     set_capability( "demux", 242 )
57     set_callbacks( Open, Close )
58 vlc_module_end ()
59
60 /*****************************************************************************
61  * Local prototypes
62  *****************************************************************************/
63 static int   Demux   ( demux_t * );
64 static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
65 static int   Seek    ( demux_t *, mtime_t );
66 static int   Control ( demux_t *, int, va_list );
67
68 /* Contain all information about a chunk */
69 typedef struct
70 {
71     uint64_t     i_offset; /* absolute position of this chunk in the file */
72     uint32_t     i_sample_description_index; /* index for SampleEntry to use */
73     uint32_t     i_sample_count; /* how many samples in this chunk */
74     uint32_t     i_sample_first; /* index of the first sample in this chunk */
75
76     /* now provide way to calculate pts, dts, and offset without too
77         much memory and with fast access */
78
79     /* with this we can calculate dts/pts without waste memory */
80     uint64_t     i_first_dts;   /* DTS of the first sample */
81     uint64_t     i_last_dts;    /* DTS of the last sample */
82     uint32_t     *p_sample_count_dts;
83     uint32_t     *p_sample_delta_dts;   /* dts delta */
84
85     uint32_t     *p_sample_count_pts;
86     int32_t      *p_sample_offset_pts;  /* pts-dts */
87
88     /* TODO if needed add pts
89         but quickly *add* support for edts and seeking */
90
91 } mp4_chunk_t;
92
93  /* Contain all needed information for read all track with vlc */
94 typedef struct
95 {
96     unsigned int i_track_ID;/* this should be unique */
97
98     int b_ok;               /* The track is usable */
99     int b_enable;           /* is the trak enable by default */
100     bool b_selected;  /* is the trak being played */
101     bool b_chapter;   /* True when used for chapter only */
102
103     bool b_mac_encoding;
104
105     es_format_t fmt;
106     es_out_id_t *p_es;
107
108     /* display size only ! */
109     int i_width;
110     int i_height;
111
112     /* more internal data */
113     uint64_t        i_timescale;    /* time scale for this track only */
114
115     /* elst */
116     int             i_elst;         /* current elst */
117     int64_t         i_elst_time;    /* current elst start time (in movie time scale)*/
118     MP4_Box_t       *p_elst;        /* elst (could be NULL) */
119
120     /* give the next sample to read, i_chunk is to find quickly where
121       the sample is located */
122     uint32_t         i_sample;       /* next sample to read */
123     uint32_t         i_chunk;        /* chunk where next sample is stored */
124     /* total count of chunk and sample */
125     uint32_t         i_chunk_count;
126     uint32_t         i_sample_count;
127
128     mp4_chunk_t    *chunk; /* always defined  for each chunk */
129
130     /* sample size, p_sample_size defined only if i_sample_size == 0
131         else i_sample_size is size for all sample */
132     uint32_t         i_sample_size;
133     uint32_t         *p_sample_size; /* XXX perhaps add file offset if take
134                                     too much time to do sumations each time*/
135
136     MP4_Box_t *p_stbl;  /* will contain all timing information */
137     MP4_Box_t *p_stsd;  /* will contain all data to initialize decoder */
138     MP4_Box_t *p_sample;/* point on actual sdsd */
139
140     bool b_drms;
141     void      *p_drms;
142     MP4_Box_t *p_skcr;
143
144 } mp4_track_t;
145
146
147 struct demux_sys_t
148 {
149     MP4_Box_t    *p_root;      /* container for the whole file */
150
151     mtime_t      i_pcr;
152
153     uint64_t     i_time;         /* time position of the presentation
154                                   * in movie timescale */
155     uint64_t     i_timescale;    /* movie time scale */
156     uint64_t     i_duration;     /* movie duration */
157     unsigned int i_tracks;       /* number of tracks */
158     mp4_track_t  *track;         /* array of track */
159     float        f_fps;          /* number of frame per seconds */
160
161     /* */
162     MP4_Box_t    *p_tref_chap;
163
164     /* */
165     input_title_t *p_title;
166 };
167
168 /*****************************************************************************
169  * Declaration of local function
170  *****************************************************************************/
171 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_force_enable );
172 static void MP4_TrackDestroy(  mp4_track_t * );
173
174 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
175 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
176
177 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
178
179 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
180 static int      MP4_TrackSampleSize( mp4_track_t * );
181 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
182 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
183
184 static void     MP4_UpdateSeekpoint( demux_t * );
185 static const char *MP4_ConvertMacCode( uint16_t );
186
187 /* Return time in s of a track */
188 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
189 {
190 #define chunk p_track->chunk[p_track->i_chunk]
191
192     unsigned int i_index = 0;
193     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
194     int64_t i_dts = chunk.i_first_dts;
195
196     while( i_sample > 0 )
197     {
198         if( i_sample > chunk.p_sample_count_dts[i_index] )
199         {
200             i_dts += chunk.p_sample_count_dts[i_index] *
201                 chunk.p_sample_delta_dts[i_index];
202             i_sample -= chunk.p_sample_count_dts[i_index];
203             i_index++;
204         }
205         else
206         {
207             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
208             break;
209         }
210     }
211
212 #undef chunk
213
214     /* now handle elst */
215     if( p_track->p_elst )
216     {
217         demux_sys_t         *p_sys = p_demux->p_sys;
218         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
219
220         /* convert to offset */
221         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
222               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
223             elst->i_media_time[p_track->i_elst] > 0 )
224         {
225             i_dts -= elst->i_media_time[p_track->i_elst];
226         }
227
228         /* add i_elst_time */
229         i_dts += p_track->i_elst_time * p_track->i_timescale /
230             p_sys->i_timescale;
231
232         if( i_dts < 0 ) i_dts = 0;
233     }
234
235     return INT64_C(1000000) * i_dts / p_track->i_timescale;
236 }
237
238 static inline int64_t MP4_TrackGetPTSDelta( mp4_track_t *p_track )
239 {
240     mp4_chunk_t *ck = &p_track->chunk[p_track->i_chunk];
241     unsigned int i_index = 0;
242     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
243
244     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
245         return -1;
246
247     for( i_index = 0;; i_index++ )
248     {
249         if( i_sample < ck->p_sample_count_pts[i_index] )
250             return ck->p_sample_offset_pts[i_index] * INT64_C(1000000) /
251                    (int64_t)p_track->i_timescale;
252
253         i_sample -= ck->p_sample_count_pts[i_index];
254     }
255 }
256
257 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
258 {
259     return INT64_C(1000000) * p_sys->i_time / p_sys->i_timescale;
260 }
261
262 static void LoadChapter( demux_t  *p_demux );
263
264 /*****************************************************************************
265  * Open: check file and initializes MP4 structures
266  *****************************************************************************/
267 static int Open( vlc_object_t * p_this )
268 {
269     demux_t  *p_demux = (demux_t *)p_this;
270     demux_sys_t     *p_sys;
271
272     const uint8_t   *p_peek;
273
274     MP4_Box_t       *p_ftyp;
275     MP4_Box_t       *p_rmra;
276     MP4_Box_t       *p_mvhd;
277     MP4_Box_t       *p_trak;
278
279     unsigned int    i;
280     bool      b_seekable;
281     bool      b_enabled_es;
282
283     /* A little test to see if it could be a mp4 */
284     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 ) return VLC_EGENERIC;
285
286     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
287     {
288         case FOURCC_ftyp:
289         case FOURCC_moov:
290         case FOURCC_foov:
291         case FOURCC_moof:
292         case FOURCC_mdat:
293         case FOURCC_udta:
294         case FOURCC_free:
295         case FOURCC_skip:
296         case FOURCC_wide:
297         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
298             break;
299          default:
300             return VLC_EGENERIC;
301     }
302
303     /* I need to seek */
304     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
305     if( !b_seekable )
306     {
307         msg_Warn( p_demux, "MP4 plugin discarded (unseekable)" );
308         return VLC_EGENERIC;
309     }
310
311     /*Set exported functions */
312     p_demux->pf_demux = Demux;
313     p_demux->pf_control = Control;
314
315     /* create our structure that will contains all data */
316     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
317     memset( p_sys, 0, sizeof( demux_sys_t ) );
318
319     /* Now load all boxes ( except raw data ) */
320     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
321     {
322         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
323         goto error;
324     }
325
326     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
327
328     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
329     {
330         switch( p_ftyp->data.p_ftyp->i_major_brand )
331         {
332             case( FOURCC_isom ):
333                 msg_Dbg( p_demux,
334                          "ISO Media file (isom) version %d.",
335                          p_ftyp->data.p_ftyp->i_minor_version );
336                 break;
337             default:
338                 msg_Dbg( p_demux,
339                          "unrecognized major file specification (%4.4s).",
340                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
341                 break;
342         }
343     }
344     else
345     {
346         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
347     }
348
349     /* the file need to have one moov box */
350     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
351     {
352         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
353
354         if( !p_foov )
355         {
356             msg_Err( p_demux, "MP4 plugin discarded (no moov box)" );
357             goto error;
358         }
359         /* we have a free box as a moov, rename it */
360         p_foov->i_type = FOURCC_moov;
361     }
362
363     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
364     {
365         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
366         int        i;
367
368         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
369
370         input_thread_t *p_input = demux_GetParentInput( p_demux );
371         input_item_t *p_current = input_GetItem( p_input );
372
373         input_item_node_t *p_subitems = input_item_node_Create( p_current );
374
375         for( i = 0; i < i_count; i++ )
376         {
377             MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
378             char      *psz_ref;
379             uint32_t  i_ref_type;
380
381             if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
382             {
383                 continue;
384             }
385             i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
386
387             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
388                      psz_ref, (char*)&i_ref_type );
389
390             if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
391             {
392                 if( strstr( psz_ref, "qt5gateQT" ) )
393                 {
394                     msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
395                     continue;
396                 }
397                 if( !strncmp( psz_ref, "http://", 7 ) ||
398                     !strncmp( psz_ref, "rtsp://", 7 ) )
399                 {
400                     ;
401                 }
402                 else
403                 {
404                     char *psz_absolute;
405                     char *psz_path = strdup( p_demux->psz_path );
406                     char *end = strrchr( psz_path, '/' );
407                     if( end ) end[1] = '\0';
408                     else *psz_path = '\0';
409
410                     if( asprintf( &psz_absolute, "%s://%s%s",
411                                   p_demux->psz_access, psz_path, psz_ref ) < 0 )
412                     {
413                         free( psz_ref );
414                         free( psz_path );
415                         vlc_object_release( p_input) ;
416                         return VLC_ENOMEM;
417                     }
418
419                     free( psz_ref );
420                     psz_ref = psz_absolute;
421                     free( psz_path );
422                 }
423                 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
424                 input_item_t *p_input = input_item_New( p_demux, psz_ref, NULL );
425                 input_item_CopyOptions( p_current, p_input );
426                 input_item_node_AppendItem( p_subitems, p_input );
427                 vlc_gc_decref( p_input );
428             }
429             else
430             {
431                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
432                          (char*)&p_rdrf->data.p_rdrf->i_ref_type );
433             }
434             free( psz_ref );
435         }
436         input_item_node_PostAndDelete( p_subitems );
437         vlc_object_release( p_input );
438     }
439
440     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
441     {
442         if( !p_rmra )
443         {
444             msg_Err( p_demux, "cannot find /moov/mvhd" );
445             goto error;
446         }
447         else
448         {
449             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
450             p_demux->pf_demux = DemuxRef;
451             return VLC_SUCCESS;
452         }
453     }
454     else
455     {
456         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
457         if( p_sys->i_timescale == 0 )
458         {
459             msg_Err( p_this, "bad timescale" );
460             goto error;
461         }
462         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
463     }
464
465     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
466     {
467         msg_Err( p_demux, "cannot find any /moov/trak" );
468         goto error;
469     }
470     msg_Dbg( p_demux, "found %d track%c",
471                         p_sys->i_tracks,
472                         p_sys->i_tracks ? 's':' ' );
473
474     /* allocate memory */
475     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
476     if( p_sys->track == NULL )
477         goto error;
478     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( mp4_track_t ) );
479
480     /* Search the first chap reference (like quicktime) and
481      * check that at least 1 stream is enabled */
482     p_sys->p_tref_chap = NULL;
483     b_enabled_es = false;
484     for( i = 0; i < p_sys->i_tracks; i++ )
485     {
486         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
487
488
489         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
490         if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
491             b_enabled_es = true;
492
493         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
494         if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
495             p_sys->p_tref_chap = p_chap;
496     }
497
498     /* now process each track and extract all usefull information */
499     for( i = 0; i < p_sys->i_tracks; i++ )
500     {
501         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
502         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
503
504         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
505         {
506             const char *psz_cat;
507             switch( p_sys->track[i].fmt.i_cat )
508             {
509                 case( VIDEO_ES ):
510                     psz_cat = "video";
511                     break;
512                 case( AUDIO_ES ):
513                     psz_cat = "audio";
514                     break;
515                 case( SPU_ES ):
516                     psz_cat = "subtitle";
517                     break;
518
519                 default:
520                     psz_cat = "unknown";
521                     break;
522             }
523
524             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
525                      p_sys->track[i].i_track_ID, psz_cat,
526                      p_sys->track[i].b_enable ? "enable":"disable",
527                      p_sys->track[i].fmt.psz_language ?
528                      p_sys->track[i].fmt.psz_language : "undef" );
529         }
530         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
531         {
532             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
533                      p_sys->track[i].i_track_ID,
534                      p_sys->track[i].fmt.psz_language ?
535                      p_sys->track[i].fmt.psz_language : "undef" );
536         }
537         else
538         {
539             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
540                      p_sys->track[i].i_track_ID );
541         }
542     }
543
544     /* */
545     LoadChapter( p_demux );
546
547     return VLC_SUCCESS;
548
549 error:
550     if( p_sys->p_root )
551     {
552         MP4_BoxFree( p_demux->s, p_sys->p_root );
553     }
554     free( p_sys );
555     return VLC_EGENERIC;
556 }
557
558 /*****************************************************************************
559  * Demux: read packet and send them to decoders
560  *****************************************************************************
561  * TODO check for newly selected track (ie audio upt to now )
562  *****************************************************************************/
563 static int Demux( demux_t *p_demux )
564 {
565     demux_sys_t *p_sys = p_demux->p_sys;
566     unsigned int i_track;
567
568
569     unsigned int i_track_selected;
570
571     /* check for newly selected/unselected track */
572     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
573          i_track++ )
574     {
575         mp4_track_t *tk = &p_sys->track[i_track];
576         bool b;
577
578         if( !tk->b_ok || tk->b_chapter ||
579             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
580         {
581             continue;
582         }
583
584         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
585
586         if( tk->b_selected && !b )
587         {
588             MP4_TrackUnselect( p_demux, tk );
589         }
590         else if( !tk->b_selected && b)
591         {
592             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
593         }
594
595         if( tk->b_selected )
596         {
597             i_track_selected++;
598         }
599     }
600
601     if( i_track_selected <= 0 )
602     {
603         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
604         if( p_sys->i_timescale > 0 )
605         {
606             int64_t i_length = (mtime_t)1000000 *
607                                (mtime_t)p_sys->i_duration /
608                                (mtime_t)p_sys->i_timescale;
609             if( MP4_GetMoviePTS( p_sys ) >= i_length )
610                 return 0;
611             return 1;
612         }
613
614         msg_Warn( p_demux, "no track selected, exiting..." );
615         return 0;
616     }
617
618     /* */
619     MP4_UpdateSeekpoint( p_demux );
620
621     /* first wait for the good time to read a packet */
622     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
623
624     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
625
626     /* we will read 100ms for each stream so ...*/
627     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
628
629     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
630     {
631         mp4_track_t *tk = &p_sys->track[i_track];
632
633         if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
634             continue;
635
636         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
637         {
638 #if 0
639             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
640                      MP4_TrackGetDTS( p_demux, tk ),
641                      MP4_GetMoviePTS( p_sys ) );
642 #endif
643
644             if( MP4_TrackSampleSize( tk ) > 0 )
645             {
646                 block_t *p_block;
647                 int64_t i_delta;
648
649                 /* go,go go ! */
650                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
651                 {
652                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
653                               tk->i_track_ID );
654                     MP4_TrackUnselect( p_demux, tk );
655                     break;
656                 }
657
658                 /* now read pes */
659                 if( !(p_block =
660                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
661                 {
662                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
663                               tk->i_track_ID );
664                     MP4_TrackUnselect( p_demux, tk );
665                     break;
666                 }
667
668                 if( tk->b_drms && tk->p_drms )
669                 {
670                     if( tk->p_skcr )
671                     {
672                         uint32_t p_key[4];
673                         drms_get_p_key( tk->p_drms, p_key );
674
675                         for( size_t i_pos = tk->p_skcr->data.p_skcr->i_init; i_pos < p_block->i_buffer; )
676                         {
677                             int n = __MIN( tk->p_skcr->data.p_skcr->i_encr, p_block->i_buffer - i_pos );
678                             drms_decrypt( tk->p_drms, (uint32_t*)&p_block->p_buffer[i_pos], n, p_key );
679                             i_pos += n;
680                             i_pos += __MIN( tk->p_skcr->data.p_skcr->i_decr, p_block->i_buffer - i_pos );
681                         }
682                     }
683                     else
684                     {
685                         drms_decrypt( tk->p_drms, (uint32_t*)p_block->p_buffer,
686                                       p_block->i_buffer, NULL );
687                     }
688                 }
689                 else if( tk->fmt.i_cat == SPU_ES )
690                 {
691                     if( tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
692                         p_block->i_buffer >= 2 )
693                     {
694                         uint16_t i_size = GetWBE( p_block->p_buffer );
695
696                         if( i_size + 2 <= p_block->i_buffer )
697                         {
698                             char *p;
699                             /* remove the length field, and append a '\0' */
700                             memmove( &p_block->p_buffer[0],
701                                      &p_block->p_buffer[2], i_size );
702                             p_block->p_buffer[i_size] = '\0';
703                             p_block->i_buffer = i_size + 1;
704
705                             /* convert \r -> \n */
706                             while( ( p = strchr((char *) p_block->p_buffer, '\r' ) ) )
707                             {
708                                 *p = '\n';
709                             }
710                         }
711                         else
712                         {
713                             /* Invalid */
714                             p_block->i_buffer = 0;
715                         }
716                     }
717                 }
718                 /* dts */
719                 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
720                 /* pts */
721                 i_delta = MP4_TrackGetPTSDelta( tk );
722                 if( i_delta != -1 )
723                     p_block->i_pts = p_block->i_dts + i_delta;
724                 else if( tk->fmt.i_cat != VIDEO_ES )
725                     p_block->i_pts = p_block->i_dts;
726                 else
727                     p_block->i_pts = VLC_TS_INVALID;
728
729                 if( !tk->b_drms || ( tk->b_drms && tk->p_drms ) )
730                     es_out_Send( p_demux->out, tk->p_es, p_block );
731             }
732
733             /* Next sample */
734             if( MP4_TrackNextSample( p_demux, tk ) )
735                 break;
736         }
737     }
738
739     return 1;
740 }
741
742 static void MP4_UpdateSeekpoint( demux_t *p_demux )
743 {
744     demux_sys_t *p_sys = p_demux->p_sys;
745     int64_t i_time;
746     int i;
747     if( !p_sys->p_title )
748         return;
749     i_time = MP4_GetMoviePTS( p_sys );
750     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
751     {
752         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
753             break;
754     }
755     i--;
756
757     if( i != p_demux->info.i_seekpoint && i >= 0 )
758     {
759         p_demux->info.i_seekpoint = i;
760         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
761     }
762 }
763 /*****************************************************************************
764  * Seek: Go to i_date
765 ******************************************************************************/
766 static int Seek( demux_t *p_demux, mtime_t i_date )
767 {
768     demux_sys_t *p_sys = p_demux->p_sys;
769     unsigned int i_track;
770
771     /* First update update global time */
772     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
773     p_sys->i_pcr  = i_date;
774
775     /* Now for each stream try to go to this time */
776     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
777     {
778         mp4_track_t *tk = &p_sys->track[i_track];
779         MP4_TrackSeek( p_demux, tk, i_date );
780     }
781     MP4_UpdateSeekpoint( p_demux );
782
783     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
784
785     return VLC_SUCCESS;
786 }
787
788 /*****************************************************************************
789  * Control:
790  *****************************************************************************/
791 static int Control( demux_t *p_demux, int i_query, va_list args )
792 {
793     demux_sys_t *p_sys = p_demux->p_sys;
794
795     double f, *pf;
796     int64_t i64, *pi64;
797
798     switch( i_query )
799     {
800         case DEMUX_GET_POSITION:
801             pf = (double*)va_arg( args, double * );
802             if( p_sys->i_duration > 0 )
803             {
804                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
805             }
806             else
807             {
808                 *pf = 0.0;
809             }
810             return VLC_SUCCESS;
811
812         case DEMUX_SET_POSITION:
813             f = (double)va_arg( args, double );
814             if( p_sys->i_timescale > 0 )
815             {
816                 i64 = (int64_t)( f * (double)1000000 *
817                                  (double)p_sys->i_duration /
818                                  (double)p_sys->i_timescale );
819                 return Seek( p_demux, i64 );
820             }
821             else return VLC_SUCCESS;
822
823         case DEMUX_GET_TIME:
824             pi64 = (int64_t*)va_arg( args, int64_t * );
825             if( p_sys->i_timescale > 0 )
826             {
827                 *pi64 = (mtime_t)1000000 *
828                         (mtime_t)p_sys->i_time /
829                         (mtime_t)p_sys->i_timescale;
830             }
831             else *pi64 = 0;
832             return VLC_SUCCESS;
833
834         case DEMUX_SET_TIME:
835             i64 = (int64_t)va_arg( args, int64_t );
836             return Seek( p_demux, i64 );
837
838         case DEMUX_GET_LENGTH:
839             pi64 = (int64_t*)va_arg( args, int64_t * );
840             if( p_sys->i_timescale > 0 )
841             {
842                 *pi64 = (mtime_t)1000000 *
843                         (mtime_t)p_sys->i_duration /
844                         (mtime_t)p_sys->i_timescale;
845             }
846             else *pi64 = 0;
847             return VLC_SUCCESS;
848
849         case DEMUX_GET_FPS:
850             pf = (double*)va_arg( args, double* );
851             *pf = p_sys->f_fps;
852             return VLC_SUCCESS;
853
854         case DEMUX_GET_META:
855         {
856             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
857             MP4_Box_t  *p_0xa9xxx;
858
859             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
860             if( p_udta == NULL )
861             {
862                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
863                 if( p_udta == NULL )
864                 {
865                     return VLC_EGENERIC;
866                 }
867             }
868
869             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
870                  p_0xa9xxx = p_0xa9xxx->p_next )
871             {
872
873                 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
874                     continue;
875
876                 /* FIXME FIXME: should convert from whatever the character
877                  * encoding of MP4 meta data is to UTF-8. */
878 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
879     if( psz_utf ) { EnsureUTF8( psz_utf );  \
880                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
881
882                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
883                 switch( p_0xa9xxx->i_type )
884                 {
885                 case FOURCC_0xa9nam: /* Full name */
886                     SET( vlc_meta_SetTitle );
887                     break;
888                 case FOURCC_0xa9aut:
889                     SET( vlc_meta_SetArtist );
890                     break;
891                 case FOURCC_0xa9ART:
892                     SET( vlc_meta_SetArtist );
893                     break;
894                 case FOURCC_0xa9cpy:
895                     SET( vlc_meta_SetCopyright );
896                     break;
897                 case FOURCC_0xa9day: /* Creation Date */
898                     SET( vlc_meta_SetDate );
899                     break;
900                 case FOURCC_0xa9des: /* Description */
901                     SET( vlc_meta_SetDescription );
902                     break;
903                 case FOURCC_0xa9gen: /* Genre */
904                     SET( vlc_meta_SetGenre );
905                     break;
906
907                 case FOURCC_0xa9alb: /* Album */
908                     SET( vlc_meta_SetAlbum );
909                     break;
910
911                 case FOURCC_0xa9trk: /* Track */
912                     SET( vlc_meta_SetTrackNum );
913                     break;
914
915                 case FOURCC_0xa9cmt: /* Commment */
916                     SET( vlc_meta_SetDescription );
917                     break;
918
919                 case FOURCC_0xa9url: /* URL */
920                     SET( vlc_meta_SetURL );
921                     break;
922
923                 case FOURCC_0xa9enc: /* Encoded By */
924                     SET( vlc_meta_SetEncodedBy );
925                     break;
926                     
927                 case FOURCC_0xa9swr:
928                 case FOURCC_0xa9inf: /* Information */
929                 case FOURCC_0xa9dir: /* Director */
930                 case FOURCC_0xa9dis: /* Disclaimer */
931                 case FOURCC_0xa9req: /* Requirements */
932                 case FOURCC_0xa9fmt: /* Original Format */
933                 case FOURCC_0xa9dsa: /* Display Source As */
934                 case FOURCC_0xa9hst: /* Host Computer */
935                 case FOURCC_0xa9prd: /* Producer */
936                 case FOURCC_0xa9prf: /* Performers */
937                 case FOURCC_0xa9ope: /* Original Performer */
938                 case FOURCC_0xa9src: /* Providers Source Content */
939                 case FOURCC_0xa9wrt: /* Writer */
940                 case FOURCC_0xa9com: /* Composer */
941                 case FOURCC_WLOC:    /* Window Location */
942                     /* TODO one day, but they aren't really meaningfull */
943                     break;
944 #undef SET
945
946                 default:
947                     break;
948                 }
949             }
950             return VLC_SUCCESS;
951         }
952
953         case DEMUX_GET_TITLE_INFO:
954         {
955             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
956             int *pi_int    = (int*)va_arg( args, int* );
957             int *pi_title_offset = (int*)va_arg( args, int* );
958             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
959
960             if( !p_sys->p_title )
961                 return VLC_EGENERIC;
962
963             *pi_int = 1;
964             *ppp_title = malloc( sizeof( input_title_t**) );
965             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
966             *pi_title_offset = 0;
967             *pi_seekpoint_offset = 0;
968             return VLC_SUCCESS;
969         }
970         case DEMUX_SET_TITLE:
971         {
972             const int i_title = (int)va_arg( args, int );
973             if( !p_sys->p_title || i_title != 0 )
974                 return VLC_EGENERIC;
975             return VLC_SUCCESS;
976         }
977         case DEMUX_SET_SEEKPOINT:
978         {
979             const int i_seekpoint = (int)va_arg( args, int );
980             if( !p_sys->p_title )
981                 return VLC_EGENERIC;
982             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
983         }
984
985         case DEMUX_SET_NEXT_DEMUX_TIME:
986         case DEMUX_SET_GROUP:
987         case DEMUX_HAS_UNSUPPORTED_META:
988         case DEMUX_GET_ATTACHMENTS:
989             return VLC_EGENERIC;
990
991         default:
992             msg_Warn( p_demux, "control query %u unimplemented", i_query );
993             return VLC_EGENERIC;
994     }
995 }
996
997 /*****************************************************************************
998  * Close: frees unused data
999  *****************************************************************************/
1000 static void Close ( vlc_object_t * p_this )
1001 {
1002     demux_t *  p_demux = (demux_t *)p_this;
1003     demux_sys_t *p_sys = p_demux->p_sys;
1004     unsigned int i_track;
1005
1006     msg_Dbg( p_demux, "freeing all memory" );
1007
1008     MP4_BoxFree( p_demux->s, p_sys->p_root );
1009     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1010     {
1011         MP4_TrackDestroy(  &p_sys->track[i_track] );
1012     }
1013     FREENULL( p_sys->track );
1014
1015     if( p_sys->p_title )
1016         vlc_input_title_Delete( p_sys->p_title );
1017
1018     free( p_sys );
1019 }
1020
1021
1022
1023 /****************************************************************************
1024  * Local functions, specific to vlc
1025  ****************************************************************************/
1026 /* Chapters */
1027 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
1028 {
1029     demux_sys_t *p_sys = p_demux->p_sys;
1030     int i;
1031
1032     p_sys->p_title = vlc_input_title_New();
1033     for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1034     {
1035         seekpoint_t *s = vlc_seekpoint_New();
1036
1037         s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1038         EnsureUTF8( s->psz_name );
1039         s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1040         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1041     }
1042 }
1043 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1044 {
1045     demux_sys_t *p_sys = p_demux->p_sys;
1046
1047     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1048     {
1049         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1050         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( tk );
1051         const unsigned int i_size = MP4_TrackSampleSize( tk );
1052
1053         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1054         {
1055             char p_buffer[256];
1056             const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1057             const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1058
1059             if( i_len > 0 )
1060             {
1061                 seekpoint_t *s = vlc_seekpoint_New();
1062
1063                 s->psz_name = strndup( &p_buffer[2], i_len );
1064                 EnsureUTF8( s->psz_name );
1065
1066                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1067
1068                 if( !p_sys->p_title )
1069                     p_sys->p_title = vlc_input_title_New();
1070                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1071             }
1072         }
1073         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1074                               tk->chunk[tk->i_chunk].i_sample_count )
1075             tk->i_chunk++;
1076     }
1077 }
1078 static void LoadChapter( demux_t  *p_demux )
1079 {
1080     demux_sys_t *p_sys = p_demux->p_sys;
1081     MP4_Box_t *p_chpl;
1082
1083     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1084     {
1085         LoadChapterGpac( p_demux, p_chpl );
1086     }
1087     else if( p_sys->p_tref_chap )
1088     {
1089         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1090         unsigned int i, j;
1091
1092         /* Load the first subtitle track like quicktime */
1093         for( i = 0; i < p_chap->i_entry_count; i++ )
1094         {
1095             for( j = 0; j < p_sys->i_tracks; j++ )
1096             {
1097                 mp4_track_t *tk = &p_sys->track[j];
1098                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1099                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) )
1100                     break;
1101             }
1102             if( j < p_sys->i_tracks )
1103             {
1104                 LoadChapterApple( p_demux, &p_sys->track[j] );
1105                 break;
1106             }
1107         }
1108     }
1109 }
1110
1111 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1112 static int TrackCreateChunksIndex( demux_t *p_demux,
1113                                    mp4_track_t *p_demux_track )
1114 {
1115     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1116     MP4_Box_t *p_stsc;
1117
1118     unsigned int i_chunk;
1119     unsigned int i_index, i_last;
1120
1121     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1122           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1123         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1124     {
1125         return( VLC_EGENERIC );
1126     }
1127
1128     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1129     if( !p_demux_track->i_chunk_count )
1130     {
1131         msg_Warn( p_demux, "no chunk defined" );
1132         return( VLC_EGENERIC );
1133     }
1134     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1135                                    sizeof( mp4_chunk_t ) );
1136     if( p_demux_track->chunk == NULL )
1137     {
1138         return VLC_ENOMEM;
1139     }
1140
1141     /* first we read chunk offset */
1142     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1143     {
1144         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1145
1146         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1147
1148         ck->i_first_dts = 0;
1149         ck->p_sample_count_dts = NULL;
1150         ck->p_sample_delta_dts = NULL;
1151         ck->p_sample_count_pts = NULL;
1152         ck->p_sample_offset_pts = NULL;
1153     }
1154
1155     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1156         to be used for the sample XXX begin to 1
1157         We construct it begining at the end */
1158     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1159     i_index = p_stsc->data.p_stsc->i_entry_count;
1160     if( !i_index )
1161     {
1162         msg_Warn( p_demux, "cannot read chunk table or table empty" );
1163         return( VLC_EGENERIC );
1164     }
1165
1166     while( i_index-- )
1167     {
1168         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1169              i_chunk < i_last; i_chunk++ )
1170         {
1171             if( i_chunk >= p_demux_track->i_chunk_count )
1172             {
1173                 msg_Warn( p_demux, "corrupted chunk table" );
1174                 return VLC_EGENERIC;
1175             }
1176
1177             p_demux_track->chunk[i_chunk].i_sample_description_index =
1178                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
1179             p_demux_track->chunk[i_chunk].i_sample_count =
1180                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1181         }
1182         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1183     }
1184
1185     p_demux_track->chunk[0].i_sample_first = 0;
1186     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1187     {
1188         p_demux_track->chunk[i_chunk].i_sample_first =
1189             p_demux_track->chunk[i_chunk-1].i_sample_first +
1190                 p_demux_track->chunk[i_chunk-1].i_sample_count;
1191     }
1192
1193     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1194              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1195
1196     return VLC_SUCCESS;
1197 }
1198
1199 static int TrackCreateSamplesIndex( demux_t *p_demux,
1200                                     mp4_track_t *p_demux_track )
1201 {
1202     MP4_Box_t *p_box;
1203     MP4_Box_data_stsz_t *stsz;
1204     MP4_Box_data_stts_t *stts;
1205     /* TODO use also stss and stsh table for seeking */
1206     /* FIXME use edit table */
1207     int64_t i_sample;
1208     int64_t i_chunk;
1209
1210     int64_t i_index;
1211     int64_t i_index_sample_used;
1212
1213     int64_t i_next_dts;
1214
1215     /* Find stsz
1216      *  Gives the sample size for each samples. There is also a stz2 table
1217      *  (compressed form) that we need to implement TODO */
1218     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1219     if( !p_box )
1220     {
1221         /* FIXME and stz2 */
1222         msg_Warn( p_demux, "cannot find STSZ box" );
1223         return VLC_EGENERIC;
1224     }
1225     stsz = p_box->data.p_stsz;
1226
1227     /* Find stts
1228      *  Gives mapping between sample and decoding time
1229      */
1230     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1231     if( !p_box )
1232     {
1233         msg_Warn( p_demux, "cannot find STTS box" );
1234         return VLC_EGENERIC;
1235     }
1236     stts = p_box->data.p_stts;
1237
1238     /* Use stsz table to create a sample number -> sample size table */
1239     p_demux_track->i_sample_count = stsz->i_sample_count;
1240     if( stsz->i_sample_size )
1241     {
1242         /* 1: all sample have the same size, so no need to construct a table */
1243         p_demux_track->i_sample_size = stsz->i_sample_size;
1244         p_demux_track->p_sample_size = NULL;
1245     }
1246     else
1247     {
1248         /* 2: each sample can have a different size */
1249         p_demux_track->i_sample_size = 0;
1250         p_demux_track->p_sample_size =
1251             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1252         if( p_demux_track->p_sample_size == NULL )
1253             return VLC_ENOMEM;
1254
1255         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1256         {
1257             p_demux_track->p_sample_size[i_sample] =
1258                     stsz->i_entry_size[i_sample];
1259         }
1260     }
1261
1262     /* Use stts table to create a sample number -> dts table.
1263      * XXX: if we don't want to waste too much memory, we can't expand
1264      *  the box! so each chunk will contain an "extract" of this table
1265      *  for fast research (problem with raw stream where a sample is sometime
1266      *  just channels*bits_per_sample/8 */
1267
1268     i_next_dts = 0;
1269     i_index = 0; i_index_sample_used = 0;
1270     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1271     {
1272         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1273         int64_t i_entry, i_sample_count, i;
1274
1275         /* save first dts */
1276         ck->i_first_dts = i_next_dts;
1277         ck->i_last_dts  = i_next_dts;
1278
1279         /* count how many entries are needed for this chunk
1280          * for p_sample_delta_dts and p_sample_count_dts */
1281         i_sample_count = ck->i_sample_count;
1282
1283         i_entry = 0;
1284         while( i_sample_count > 0 )
1285         {
1286             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1287             /* don't count already used sample in this entry */
1288             if( i_entry == 0 )
1289                 i_sample_count += i_index_sample_used;
1290
1291             i_entry++;
1292         }
1293
1294         /* allocate them */
1295         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1296         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1297
1298         if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1299             return VLC_ENOMEM;
1300
1301         /* now copy */
1302         i_sample_count = ck->i_sample_count;
1303         for( i = 0; i < i_entry; i++ )
1304         {
1305             int64_t i_used;
1306             int64_t i_rest;
1307
1308             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1309
1310             i_used = __MIN( i_rest, i_sample_count );
1311
1312             i_index_sample_used += i_used;
1313             i_sample_count -= i_used;
1314             i_next_dts += i_used * stts->i_sample_delta[i_index];
1315
1316             ck->p_sample_count_dts[i] = i_used;
1317             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1318             if( i_used > 0 )
1319                 ck->i_last_dts = i_next_dts - ck->p_sample_delta_dts[i];
1320
1321             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1322             {
1323                 i_index++;
1324                 i_index_sample_used = 0;
1325             }
1326         }
1327     }
1328
1329     /* Find ctts
1330      *  Gives the delta between decoding time (dts) and composition table (pts)
1331      */
1332     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1333     if( p_box )
1334     {
1335         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1336
1337         msg_Warn( p_demux, "CTTS table" );
1338
1339         /* Create pts-dts table per chunk */
1340         i_index = 0; i_index_sample_used = 0;
1341         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1342         {
1343             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1344             int64_t i_entry, i_sample_count, i;
1345
1346             /* count how many entries are needed for this chunk
1347              * for p_sample_delta_dts and p_sample_count_dts */
1348             i_sample_count = ck->i_sample_count;
1349
1350             i_entry = 0;
1351             while( i_sample_count > 0 )
1352             {
1353                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1354
1355                 /* don't count already used sample in this entry */
1356                 if( i_entry == 0 )
1357                     i_sample_count += i_index_sample_used;
1358
1359                 i_entry++;
1360             }
1361
1362             /* allocate them */
1363             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1364             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1365             if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1366                 return VLC_ENOMEM;
1367
1368             /* now copy */
1369             i_sample_count = ck->i_sample_count;
1370             for( i = 0; i < i_entry; i++ )
1371             {
1372                 int64_t i_used;
1373                 int64_t i_rest;
1374
1375                 i_rest = ctts->i_sample_count[i_index] -
1376                     i_index_sample_used;
1377
1378                 i_used = __MIN( i_rest, i_sample_count );
1379
1380                 i_index_sample_used += i_used;
1381                 i_sample_count -= i_used;
1382
1383                 ck->p_sample_count_pts[i] = i_used;
1384                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1385
1386                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1387                 {
1388                     i_index++;
1389                     i_index_sample_used = 0;
1390                 }
1391             }
1392         }
1393     }
1394
1395     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:%"PRId64"s",
1396              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1397              i_next_dts / p_demux_track->i_timescale );
1398
1399     return VLC_SUCCESS;
1400 }
1401
1402 /**
1403  * It computes the sample rate for a video track using the given sample
1404  * description index
1405  */
1406 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1407                                   const mp4_track_t *p_track,
1408                                   unsigned i_sd_index,
1409                                   unsigned i_chunk )
1410 {
1411     *pi_num = 0;
1412     *pi_den = 0;
1413
1414     if( p_track->i_chunk_count <= 0 )
1415         return;
1416
1417     /* */
1418     const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1419     while( p_chunk > &p_track->chunk[0] &&
1420            p_chunk[-1].i_sample_description_index == i_sd_index )
1421     {
1422         p_chunk--;
1423     }
1424
1425     uint64_t i_sample = 0;
1426     uint64_t i_first_dts = p_chunk->i_first_dts;
1427     uint64_t i_last_dts;
1428     do
1429     {
1430         i_sample += p_chunk->i_sample_count;
1431         i_last_dts = p_chunk->i_last_dts;
1432         p_chunk++;
1433     }
1434     while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1435            p_chunk->i_sample_description_index == i_sd_index );
1436
1437     if( i_sample > 1 && i_first_dts < i_last_dts )
1438         vlc_ureduce( pi_num, pi_den,
1439                      ( i_sample - 1) *  p_track->i_timescale,
1440                      i_last_dts - i_first_dts,
1441                      UINT16_MAX);
1442 }
1443
1444 /*
1445  * TrackCreateES:
1446  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1447  */
1448 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1449                           unsigned int i_chunk, es_out_id_t **pp_es )
1450 {
1451     const unsigned i_sample_description_index =
1452         p_track->chunk[i_chunk].i_sample_description_index;
1453     MP4_Box_t   *p_sample;
1454     MP4_Box_t   *p_esds;
1455     MP4_Box_t   *p_frma;
1456
1457     if( pp_es )
1458         *pp_es = NULL;
1459
1460     if( !i_sample_description_index )
1461     {
1462         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1463                   p_track->i_track_ID );
1464         return VLC_EGENERIC;
1465     }
1466
1467     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1468                             i_sample_description_index - 1 );
1469
1470     if( !p_sample ||
1471         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1472     {
1473         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1474                   p_track->i_track_ID );
1475         return VLC_EGENERIC;
1476     }
1477
1478     p_track->p_sample = p_sample;
1479
1480     if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1481     {
1482         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1483
1484         p_sample->i_type = p_frma->data.p_frma->i_type;
1485     }
1486
1487     if( p_track->fmt.i_cat == AUDIO_ES && ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1488     {
1489         MP4_Box_data_sample_soun_t *p_soun;
1490
1491         p_soun = p_sample->data.p_sample_soun;
1492
1493         if( p_soun->i_qt_version == 0 )
1494         {
1495             switch( p_sample->i_type )
1496             {
1497                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1498                     p_soun->i_qt_version = 1;
1499                     p_soun->i_sample_per_packet = 64;
1500                     p_soun->i_bytes_per_packet  = 34;
1501                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1502                     p_soun->i_bytes_per_sample  = 2;
1503                     break;
1504                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1505                     p_soun->i_qt_version = 1;
1506                     p_soun->i_sample_per_packet = 6;
1507                     p_soun->i_bytes_per_packet  = 2;
1508                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1509                     p_soun->i_bytes_per_sample  = 2;
1510                     break;
1511                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1512                     p_soun->i_qt_version = 1;
1513                     p_soun->i_sample_per_packet = 12;
1514                     p_soun->i_bytes_per_packet  = 2;
1515                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1516                     p_soun->i_bytes_per_sample  = 2;
1517                     break;
1518                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1519                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1520                     p_soun->i_samplesize = 8;
1521                     break;
1522                 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1523                 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1524                 case VLC_FOURCC( 't', 'w', 'o', 's' ):
1525                 case VLC_FOURCC( 's', 'o', 'w', 't' ):
1526                     /* What would be the fun if you could trust the .mov */
1527                     p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1528                     break;
1529                 default:
1530                     break;
1531             }
1532
1533         }
1534         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1535         {
1536             p_soun->i_qt_version = 0;
1537         }
1538     }
1539
1540     /* */
1541     switch( p_track->fmt.i_cat )
1542     {
1543     case VIDEO_ES:
1544         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1545         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1546         p_track->fmt.video.i_bits_per_pixel =
1547             p_sample->data.p_sample_vide->i_depth;
1548
1549         /* fall on display size */
1550         if( p_track->fmt.video.i_width <= 0 )
1551             p_track->fmt.video.i_width = p_track->i_width;
1552         if( p_track->fmt.video.i_height <= 0 )
1553             p_track->fmt.video.i_height = p_track->i_height;
1554
1555         /* Find out apect ratio from display size */
1556         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1557             /* Work-around buggy muxed files */
1558             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1559         {
1560             p_track->fmt.video.i_sar_num = p_track->i_width  * p_track->fmt.video.i_height;
1561             p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1562         }
1563
1564         /* Support for cropping (eg. in H263 files) */
1565         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1566         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1567
1568         /* Frame rate */
1569         TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1570                               &p_track->fmt.video.i_frame_rate_base,
1571                               p_track, i_sample_description_index, i_chunk );
1572         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1573                                 (float)p_track->fmt.video.i_frame_rate_base;
1574         break;
1575
1576     case AUDIO_ES:
1577         p_track->fmt.audio.i_channels =
1578             p_sample->data.p_sample_soun->i_channelcount;
1579         p_track->fmt.audio.i_rate =
1580             p_sample->data.p_sample_soun->i_sampleratehi;
1581         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1582             p_sample->data.p_sample_soun->i_sampleratehi *
1583                 p_sample->data.p_sample_soun->i_samplesize;
1584         p_track->fmt.audio.i_bitspersample =
1585             p_sample->data.p_sample_soun->i_samplesize;
1586
1587         if( p_track->i_sample_size != 0 &&
1588             p_sample->data.p_sample_soun->i_qt_version == 1 && p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
1589         {
1590             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1" );
1591             return VLC_EGENERIC;
1592         }
1593         break;
1594
1595     default:
1596         break;
1597     }
1598
1599
1600     /* It's a little ugly but .. there are special cases */
1601     switch( p_sample->i_type )
1602     {
1603         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1604         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1605         {
1606             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1607             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1608             if( p_track->i_sample_size > 1 )
1609                 p_soun->i_qt_version = 0;
1610             break;
1611         }
1612         case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1613         {
1614             MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
1615
1616             p_track->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1617             if( p_dac3_box )
1618             {
1619                 static const int pi_bitrate[] = {
1620                      32,  40,  48,  56,
1621                      64,  80,  96, 112,
1622                     128, 160, 192, 224,
1623                     256, 320, 384, 448,
1624                     512, 576, 640,
1625                 };
1626                 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
1627                 p_track->fmt.audio.i_channels = 0;
1628                 p_track->fmt.i_bitrate = 0;
1629                 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
1630                     p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
1631                 p_track->fmt.audio.i_bitspersample = 0;
1632             }
1633             break;
1634         }
1635         case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1636         {
1637             p_track->fmt.i_codec = VLC_FOURCC( 'e', 'a', 'c', '3' );
1638             break;
1639         }
1640
1641         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1642         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
1643         {
1644             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1645
1646             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
1647                 p_track->fmt.i_codec = VLC_FOURCC( 'u', '8', ' ', ' ' );
1648             else
1649                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1650
1651             /* Buggy files workaround */
1652             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
1653                 p_sample->data.p_sample_soun->i_sampleratehi) )
1654             {
1655                 MP4_Box_data_sample_soun_t *p_soun =
1656                     p_sample->data.p_sample_soun;
1657
1658                 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
1659                           "(%u), making both equal (report any problem).",
1660                           p_track->i_timescale, p_soun->i_sampleratehi );
1661
1662                 if( p_soun->i_sampleratehi )
1663                     p_track->i_timescale = p_soun->i_sampleratehi;
1664                 else
1665                     p_soun->i_sampleratehi = p_track->i_timescale;
1666             }
1667             break;
1668         }
1669
1670         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1671             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1672             break;
1673
1674         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1675         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
1676             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1677             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1678             /* FIXME UTF-8 doesn't work here ? */
1679             if( p_track->b_mac_encoding )
1680                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
1681             else
1682                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
1683             break;
1684
1685         case VLC_FOURCC('y','v','1','2'):
1686             p_track->fmt.i_codec = VLC_FOURCC('Y','V','1','2');
1687             break;
1688         case VLC_FOURCC('y','u','v','2'):
1689             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
1690             break;
1691
1692         case VLC_FOURCC('i','n','2','4'):
1693             /* in in24/in32 there's enda-atom to tell it's little-endian (if present) */
1694             if( ( MP4_BoxGet( p_sample, "wave/enda" ) ) ||
1695                 ( MP4_BoxGet( p_sample, "enda" ) ) )
1696             {
1697                 p_track->fmt.i_codec = VLC_FOURCC('4','2','n','i');
1698             } else {
1699                 p_track->fmt.i_codec = p_sample->i_type;
1700             }
1701             break;
1702
1703         default:
1704             p_track->fmt.i_codec = p_sample->i_type;
1705             break;
1706     }
1707
1708     /* now see if esds is present and if so create a data packet
1709         with decoder_specific_info  */
1710 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1711     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1712           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1713         ( p_esds->data.p_esds )&&
1714         ( p_decconfig ) )
1715     {
1716         /* First update information based on i_objectTypeIndication */
1717         switch( p_decconfig->i_objectTypeIndication )
1718         {
1719             case( 0x20 ): /* MPEG4 VIDEO */
1720                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1721                 break;
1722             case( 0x40):
1723                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1724                 break;
1725             case( 0x60):
1726             case( 0x61):
1727             case( 0x62):
1728             case( 0x63):
1729             case( 0x64):
1730             case( 0x65): /* MPEG2 video */
1731                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1732                 break;
1733             /* Theses are MPEG2-AAC */
1734             case( 0x66): /* main profile */
1735             case( 0x67): /* Low complexity profile */
1736             case( 0x68): /* Scaleable Sampling rate profile */
1737                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1738                 break;
1739             /* true MPEG 2 audio */
1740             case( 0x69):
1741                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1742                 break;
1743             case( 0x6a): /* MPEG1 video */
1744                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1745                 break;
1746             case( 0x6b): /* MPEG1 audio */
1747                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1748                 break;
1749             case( 0x6c ): /* jpeg */
1750                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1751                 break;
1752             case( 0x6d ): /* png */
1753                 p_track->fmt.i_codec = VLC_FOURCC( 'p','n','g',' ' );
1754                 break;
1755             case( 0x6e ): /* jpeg200 */
1756                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
1757                 break;
1758             case( 0xa3 ): /* vc1 */
1759                 p_track->fmt.i_codec = VLC_FOURCC( 'W','V','C','1' );
1760                 break;
1761
1762             /* Private ID */
1763             case( 0xe0 ): /* NeroDigital: dvd subs */
1764                 if( p_track->fmt.i_cat == SPU_ES )
1765                 {
1766                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1767                     if( p_track->i_width > 0 )
1768                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
1769                     if( p_track->i_height > 0 )
1770                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
1771                     break;
1772                 }
1773             case( 0xe1 ): /* QCelp for 3gp */
1774                 if( p_track->fmt.i_cat == AUDIO_ES )
1775                 {
1776                     p_track->fmt.i_codec = VLC_FOURCC( 'Q','c','l','p' );
1777                 }
1778                 break;
1779
1780             /* Fallback */
1781             default:
1782                 /* Unknown entry, but don't touch i_fourcc */
1783                 msg_Warn( p_demux,
1784                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1785                           p_decconfig->i_objectTypeIndication,
1786                           p_track->i_track_ID );
1787                 break;
1788         }
1789         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1790         if( p_track->fmt.i_extra > 0 )
1791         {
1792             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1793             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1794                     p_track->fmt.i_extra );
1795         }
1796     }
1797     else
1798     {
1799         switch( p_sample->i_type )
1800         {
1801             /* qt decoder, send the complete chunk */
1802             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
1803             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
1804             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
1805             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
1806             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
1807             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
1808             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
1809             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
1810             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
1811             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
1812             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
1813             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
1814                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1815                 break;
1816             /* qt decoder, send the complete chunk */
1817             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1818             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1819             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1820             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1821             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1822                 p_track->fmt.i_extra =
1823                     p_sample->data.p_sample_vide->i_qt_image_description;
1824                 if( p_track->fmt.i_extra > 0 )
1825                 {
1826                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1827                     memcpy( p_track->fmt.p_extra,
1828                             p_sample->data.p_sample_vide->p_qt_image_description,
1829                             p_track->fmt.i_extra);
1830                 }
1831                 break;
1832             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1833             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1834             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1835             case VLC_FOURCC( 'a', 'l', 'a', 'c' ):
1836                 p_track->fmt.i_extra =
1837                     p_sample->data.p_sample_soun->i_qt_description;
1838                 if( p_track->fmt.i_extra > 0 )
1839                 {
1840                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1841                     memcpy( p_track->fmt.p_extra,
1842                             p_sample->data.p_sample_soun->p_qt_description,
1843                             p_track->fmt.i_extra);
1844                 }
1845                 break;
1846
1847             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1848             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1849             {
1850                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1851
1852                 if( p_avcC )
1853                 {
1854                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1855                     if( p_track->fmt.i_extra > 0 )
1856                     {
1857                         p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1858                         memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
1859                                 p_track->fmt.i_extra );
1860                     }
1861                 }
1862                 else
1863                 {
1864                     msg_Err( p_demux, "missing avcC" );
1865                 }
1866                 break;
1867             }
1868
1869             case VLC_FOURCC('m','s',0x00,0x02):
1870             case VLC_FOURCC('m','s',0x00,0x11):
1871             case VLC_FOURCC('Q','c','l','p'):
1872                 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
1873                 break;
1874
1875             default:
1876                 break;
1877         }
1878     }
1879
1880 #undef p_decconfig
1881
1882     if( pp_es )
1883         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1884
1885     return VLC_SUCCESS;
1886 }
1887
1888 /* given a time it return sample/chunk
1889  * it also update elst field of the track
1890  */
1891 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1892                                    int64_t i_start, uint32_t *pi_chunk,
1893                                    uint32_t *pi_sample )
1894 {
1895     demux_sys_t *p_sys = p_demux->p_sys;
1896     MP4_Box_t   *p_stss;
1897     uint64_t     i_dts;
1898     unsigned int i_sample;
1899     unsigned int i_chunk;
1900     int          i_index;
1901
1902     /* FIXME see if it's needed to check p_track->i_chunk_count */
1903     if( p_track->i_chunk_count == 0 )
1904         return( VLC_EGENERIC );
1905
1906     /* handle elst (find the correct one) */
1907     MP4_TrackSetELST( p_demux, p_track, i_start );
1908     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1909     {
1910         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1911         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1912
1913         /* now calculate i_start for this elst */
1914         /* offset */
1915         i_start -= p_track->i_elst_time * INT64_C(1000000) / p_sys->i_timescale;
1916         if( i_start < 0 )
1917         {
1918             *pi_chunk = 0;
1919             *pi_sample= 0;
1920
1921             return VLC_SUCCESS;
1922         }
1923         /* to track time scale */
1924         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1925         /* add elst offset */
1926         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1927              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1928             elst->i_media_time[p_track->i_elst] > 0 )
1929         {
1930             i_start += elst->i_media_time[p_track->i_elst];
1931         }
1932
1933         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
1934                  "ms (track)", p_track->i_elst,
1935                  i_mvt * 1000 / p_sys->i_timescale,
1936                  i_start * 1000 / p_track->i_timescale );
1937     }
1938     else
1939     {
1940         /* convert absolute time to in timescale unit */
1941         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1942     }
1943
1944     /* we start from sample 0/chunk 0, hope it won't take too much time */
1945     /* *** find good chunk *** */
1946     for( i_chunk = 0; ; i_chunk++ )
1947     {
1948         if( i_chunk + 1 >= p_track->i_chunk_count )
1949         {
1950             /* at the end and can't check if i_start in this chunk,
1951                it will be check while searching i_sample */
1952             i_chunk = p_track->i_chunk_count - 1;
1953             break;
1954         }
1955
1956         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
1957             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1958         {
1959             break;
1960         }
1961     }
1962
1963     /* *** find sample in the chunk *** */
1964     i_sample = p_track->chunk[i_chunk].i_sample_first;
1965     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1966     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1967     {
1968         if( i_dts +
1969             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1970             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
1971         {
1972             i_dts    +=
1973                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1974                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1975
1976             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1977             i_index++;
1978         }
1979         else
1980         {
1981             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1982             {
1983                 break;
1984             }
1985             i_sample += ( i_start - i_dts ) /
1986                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1987             break;
1988         }
1989     }
1990
1991     if( i_sample >= p_track->i_sample_count )
1992     {
1993         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1994                   "(seeking too far) chunk=%d sample=%d",
1995                   p_track->i_track_ID, i_chunk, i_sample );
1996         return( VLC_EGENERIC );
1997     }
1998
1999
2000     /* *** Try to find nearest sync points *** */
2001     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2002     {
2003         unsigned int i_index;
2004         msg_Dbg( p_demux,
2005                     "track[Id 0x%x] using Sync Sample Box (stss)",
2006                     p_track->i_track_ID );
2007         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
2008         {
2009             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
2010             {
2011                 if( i_index > 0 )
2012                 {
2013                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2014                             i_sample,
2015                             p_stss->data.p_stss->i_sample_number[i_index-1] );
2016                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
2017                     /* new i_sample is less than old so i_chunk can only decreased */
2018                     while( i_chunk > 0 &&
2019                             i_sample < p_track->chunk[i_chunk].i_sample_first )
2020                     {
2021                         i_chunk--;
2022                     }
2023                 }
2024                 else
2025                 {
2026                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2027                             i_sample,
2028                             p_stss->data.p_stss->i_sample_number[i_index] );
2029                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
2030                     /* new i_sample is more than old so i_chunk can only increased */
2031                     while( i_chunk < p_track->i_chunk_count - 1 &&
2032                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
2033                              p_track->chunk[i_chunk].i_sample_count )
2034                     {
2035                         i_chunk++;
2036                     }
2037                 }
2038                 break;
2039             }
2040         }
2041     }
2042     else
2043     {
2044         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2045                  "Sample Box (stss)", p_track->i_track_ID );
2046     }
2047
2048     *pi_chunk  = i_chunk;
2049     *pi_sample = i_sample;
2050
2051     return VLC_SUCCESS;
2052 }
2053
2054 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2055                                  unsigned int i_chunk, unsigned int i_sample )
2056 {
2057     bool b_reselect = false;
2058
2059     /* now see if actual es is ok */
2060     if( p_track->i_chunk >= p_track->i_chunk_count ||
2061         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2062             p_track->chunk[i_chunk].i_sample_description_index )
2063     {
2064         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2065                   p_track->i_track_ID );
2066
2067         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2068                         p_track->p_es, &b_reselect );
2069
2070         es_out_Del( p_demux->out, p_track->p_es );
2071
2072         p_track->p_es = NULL;
2073
2074         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2075         {
2076             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2077                      p_track->i_track_ID );
2078
2079             p_track->b_ok       = false;
2080             p_track->b_selected = false;
2081             return VLC_EGENERIC;
2082         }
2083     }
2084
2085     /* select again the new decoder */
2086     if( b_reselect )
2087     {
2088         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2089     }
2090
2091     p_track->i_chunk    = i_chunk;
2092     p_track->i_sample   = i_sample;
2093
2094     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2095 }
2096
2097 /****************************************************************************
2098  * MP4_TrackCreate:
2099  ****************************************************************************
2100  * Parse track information and create all needed data to run a track
2101  * If it succeed b_ok is set to 1 else to 0
2102  ****************************************************************************/
2103 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2104                              MP4_Box_t *p_box_trak,
2105                              bool b_force_enable )
2106 {
2107     demux_sys_t *p_sys = p_demux->p_sys;
2108
2109     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2110     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2111     MP4_Box_t *p_elst;
2112
2113     MP4_Box_t *p_mdhd;
2114     MP4_Box_t *p_udta;
2115     MP4_Box_t *p_hdlr;
2116
2117     MP4_Box_t *p_vmhd;
2118     MP4_Box_t *p_smhd;
2119
2120     MP4_Box_t *p_drms;
2121
2122     unsigned int i;
2123     char language[4];
2124
2125     /* hint track unsupported */
2126
2127     /* set default value (-> track unusable) */
2128     p_track->b_ok       = false;
2129     p_track->b_enable   = false;
2130     p_track->b_selected = false;
2131     p_track->b_chapter  = false;
2132     p_track->b_mac_encoding = false;
2133
2134     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2135
2136     if( !p_tkhd )
2137     {
2138         return;
2139     }
2140
2141     /* do we launch this track by default ? */
2142     p_track->b_enable =
2143         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2144     if( !p_track->b_enable )
2145         p_track->fmt.i_priority = -1;
2146
2147     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2148     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
2149     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
2150
2151     if( p_tref )
2152     {
2153 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2154     }
2155
2156     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2157     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2158
2159     if( ( !p_mdhd )||( !p_hdlr ) )
2160     {
2161         return;
2162     }
2163
2164     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2165     if( !p_track->i_timescale )
2166         return;
2167
2168     if( p_mdhd->data.p_mdhd->i_language_code < 0x800 )
2169     {
2170         /* We can convert i_language_code into iso 639 code,
2171          * I won't */
2172         strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2173         p_track->b_mac_encoding = true;
2174     }
2175     else
2176     {
2177         for( i = 0; i < 3; i++ )
2178             language[i] = p_mdhd->data.p_mdhd->i_language[i];
2179         language[3] = '\0';
2180     }
2181
2182     switch( p_hdlr->data.p_hdlr->i_handler_type )
2183     {
2184         case( FOURCC_soun ):
2185             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2186             {
2187                 return;
2188             }
2189             p_track->fmt.i_cat = AUDIO_ES;
2190             break;
2191
2192         case( FOURCC_vide ):
2193             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2194             {
2195                 return;
2196             }
2197             p_track->fmt.i_cat = VIDEO_ES;
2198             break;
2199
2200         case( FOURCC_text ):
2201         case( FOURCC_subp ):
2202         case( FOURCC_tx3g ):
2203         case( FOURCC_sbtl ):
2204             p_track->fmt.i_cat = SPU_ES;
2205             break;
2206
2207         default:
2208             return;
2209     }
2210
2211     p_track->i_elst = 0;
2212     p_track->i_elst_time = 0;
2213     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2214     {
2215         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2216         unsigned int i;
2217
2218         msg_Warn( p_demux, "elst box found" );
2219         for( i = 0; i < elst->i_entry_count; i++ )
2220         {
2221             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
2222                      "ms) rate=%d.%d", i,
2223                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2224                      elst->i_media_time[i] >= 0 ?
2225                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2226                      INT64_C(-1),
2227                      elst->i_media_rate_integer[i],
2228                      elst->i_media_rate_fraction[i] );
2229         }
2230     }
2231
2232
2233 /*  TODO
2234     add support for:
2235     p_dinf = MP4_BoxGet( p_minf, "dinf" );
2236 */
2237     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2238         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2239     {
2240         return;
2241     }
2242
2243     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
2244     p_track->b_drms = p_drms != NULL;
2245     p_track->p_drms = p_track->b_drms ?
2246         p_drms->data.p_sample_soun->p_drms : NULL;
2247
2248     if ( !p_drms )
2249     {
2250         p_drms = MP4_BoxGet( p_track->p_stsd, "drmi" );
2251         p_track->b_drms = p_drms != NULL;
2252         p_track->p_drms = p_track->b_drms ?
2253             p_drms->data.p_sample_vide->p_drms : NULL;
2254     }
2255
2256     if( p_drms )
2257         p_track->p_skcr = MP4_BoxGet( p_drms, "sinf/skcr" );
2258
2259     /* Set language */
2260     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2261     {
2262         p_track->fmt.psz_language = strdup( language );
2263     }
2264
2265     p_udta = MP4_BoxGet( p_box_trak, "udta" );
2266     if( p_udta )
2267     {
2268         MP4_Box_t *p_0xa9xxx;
2269         for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
2270                  p_0xa9xxx = p_0xa9xxx->p_next )
2271         {
2272             switch( p_0xa9xxx->i_type )
2273             {
2274                 case FOURCC_0xa9nam:
2275                     p_track->fmt.psz_description =
2276                         strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text );
2277                     break;
2278             }
2279         }
2280     }
2281
2282     /* Create chunk index table and sample index table */
2283     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
2284         TrackCreateSamplesIndex( p_demux, p_track ) )
2285     {
2286         return; /* cannot create chunks index */
2287     }
2288
2289     p_track->i_chunk  = 0;
2290     p_track->i_sample = 0;
2291
2292     /* Mark chapter only track */
2293     if( p_sys->p_tref_chap )
2294     {
2295         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2296         unsigned int i;
2297
2298         for( i = 0; i < p_chap->i_entry_count; i++ )
2299         {
2300             if( p_track->i_track_ID == p_chap->i_track_ID[i] )
2301             {
2302                 p_track->b_chapter = true;
2303                 p_track->b_enable = false;
2304                 break;
2305             }
2306         }
2307     }
2308
2309     /* now create es */
2310     if( b_force_enable &&
2311         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2312     {
2313         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2314                   p_track->i_track_ID );
2315         p_track->b_enable = true;
2316         p_track->fmt.i_priority = 0;
2317     }
2318
2319     p_track->p_es = NULL;
2320     if( TrackCreateES( p_demux,
2321                        p_track, p_track->i_chunk,
2322                        p_track->b_chapter ? NULL : &p_track->p_es ) )
2323     {
2324         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2325                  p_track->i_track_ID );
2326         return;
2327     }
2328     p_track->b_ok = true;
2329 #if 0
2330     {
2331         int i;
2332         for( i = 0; i < p_track->i_chunk_count; i++ )
2333         {
2334             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2335                      i, p_track->chunk[i].i_sample_count,
2336                      p_track->chunk[i].i_first_dts );
2337
2338         }
2339     }
2340 #endif
2341 }
2342
2343 /****************************************************************************
2344  * MP4_TrackDestroy:
2345  ****************************************************************************
2346  * Destroy a track created by MP4_TrackCreate.
2347  ****************************************************************************/
2348 static void MP4_TrackDestroy( mp4_track_t *p_track )
2349 {
2350     unsigned int i_chunk;
2351
2352     p_track->b_ok = false;
2353     p_track->b_enable   = false;
2354     p_track->b_selected = false;
2355
2356     es_format_Clean( &p_track->fmt );
2357
2358     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2359     {
2360         if( p_track->chunk )
2361         {
2362            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2363            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2364
2365            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2366            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2367         }
2368     }
2369     FREENULL( p_track->chunk );
2370
2371     if( !p_track->i_sample_size )
2372     {
2373         FREENULL( p_track->p_sample_size );
2374     }
2375 }
2376
2377 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2378                             mtime_t i_start )
2379 {
2380     if( !p_track->b_ok || p_track->b_chapter )
2381     {
2382         return VLC_EGENERIC;
2383     }
2384
2385     if( p_track->b_selected )
2386     {
2387         msg_Warn( p_demux, "track[Id 0x%x] already selected",
2388                   p_track->i_track_ID );
2389         return VLC_SUCCESS;
2390     }
2391
2392     return MP4_TrackSeek( p_demux, p_track, i_start );
2393 }
2394
2395 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2396 {
2397     if( !p_track->b_ok || p_track->b_chapter )
2398     {
2399         return;
2400     }
2401
2402     if( !p_track->b_selected )
2403     {
2404         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2405                   p_track->i_track_ID );
2406         return;
2407     }
2408     if( p_track->p_es )
2409     {
2410         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2411                         p_track->p_es, false );
2412     }
2413
2414     p_track->b_selected = false;
2415 }
2416
2417 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2418                           mtime_t i_start )
2419 {
2420     uint32_t i_chunk;
2421     uint32_t i_sample;
2422
2423     if( !p_track->b_ok || p_track->b_chapter )
2424         return VLC_EGENERIC;
2425
2426     p_track->b_selected = false;
2427
2428     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2429                                 &i_chunk, &i_sample ) )
2430     {
2431         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2432                   p_track->i_track_ID );
2433         return VLC_EGENERIC;
2434     }
2435
2436     p_track->b_selected = true;
2437
2438     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
2439         p_track->b_selected = true;
2440
2441     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2442 }
2443
2444
2445 /*
2446  * 3 types: for audio
2447  *
2448  */
2449 #define QT_V0_MAX_SAMPLES 1024
2450 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2451 {
2452     int i_size;
2453     MP4_Box_data_sample_soun_t *p_soun;
2454
2455     if( p_track->i_sample_size == 0 )
2456     {
2457         /* most simple case */
2458         return p_track->p_sample_size[p_track->i_sample];
2459     }
2460     if( p_track->fmt.i_cat != AUDIO_ES )
2461     {
2462         return p_track->i_sample_size;
2463     }
2464
2465     p_soun = p_track->p_sample->data.p_sample_soun;
2466
2467     if( p_soun->i_qt_version == 1 )
2468     {
2469         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
2470         if( p_track->fmt.audio.i_blockalign > 1 )
2471             i_samples = p_soun->i_sample_per_packet;
2472
2473         i_size = i_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2474     }
2475     else if( p_track->i_sample_size > 256 )
2476     {
2477         /* We do that so we don't read too much data
2478          * (in this case we are likely dealing with compressed data) */
2479         i_size = p_track->i_sample_size;
2480     }
2481     else
2482     {
2483         /* Read a bunch of samples at once */
2484         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2485             ( p_track->i_sample -
2486               p_track->chunk[p_track->i_chunk].i_sample_first );
2487
2488         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2489         i_size = i_samples * p_track->i_sample_size;
2490     }
2491
2492     //fprintf( stderr, "size=%d\n", i_size );
2493     return i_size;
2494 }
2495
2496 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2497 {
2498     unsigned int i_sample;
2499     uint64_t i_pos;
2500
2501     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2502
2503     if( p_track->i_sample_size )
2504     {
2505         MP4_Box_data_sample_soun_t *p_soun =
2506             p_track->p_sample->data.p_sample_soun;
2507
2508         if( p_soun->i_qt_version == 0 )
2509         {
2510             i_pos += ( p_track->i_sample -
2511                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2512                      p_track->i_sample_size;
2513         }
2514         else
2515         {
2516             /* we read chunk by chunk unless a blockalign is requested */
2517             if( p_track->fmt.audio.i_blockalign > 1 )
2518                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
2519                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2520         }
2521     }
2522     else
2523     {
2524         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2525              i_sample < p_track->i_sample; i_sample++ )
2526         {
2527             i_pos += p_track->p_sample_size[i_sample];
2528         }
2529     }
2530
2531     return i_pos;
2532 }
2533
2534 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2535 {
2536     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2537     {
2538         MP4_Box_data_sample_soun_t *p_soun;
2539
2540         p_soun = p_track->p_sample->data.p_sample_soun;
2541
2542         if( p_soun->i_qt_version == 1 )
2543         {
2544             /* we read chunk by chunk unless a blockalign is requested */
2545             if( p_track->fmt.audio.i_blockalign > 1 )
2546                 p_track->i_sample += p_soun->i_sample_per_packet;
2547             else
2548                 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
2549         }
2550         else if( p_track->i_sample_size > 256 )
2551         {
2552             /* We do that so we don't read too much data
2553              * (in this case we are likely dealing with compressed data) */
2554             p_track->i_sample += 1;
2555         }
2556         else
2557         {
2558             /* FIXME */
2559             p_track->i_sample += QT_V0_MAX_SAMPLES;
2560             if( p_track->i_sample >
2561                 p_track->chunk[p_track->i_chunk].i_sample_first +
2562                 p_track->chunk[p_track->i_chunk].i_sample_count )
2563             {
2564                 p_track->i_sample =
2565                     p_track->chunk[p_track->i_chunk].i_sample_first +
2566                     p_track->chunk[p_track->i_chunk].i_sample_count;
2567             }
2568         }
2569     }
2570     else
2571     {
2572         p_track->i_sample++;
2573     }
2574
2575     if( p_track->i_sample >= p_track->i_sample_count )
2576         return VLC_EGENERIC;
2577
2578     /* Have we changed chunk ? */
2579     if( p_track->i_sample >=
2580             p_track->chunk[p_track->i_chunk].i_sample_first +
2581             p_track->chunk[p_track->i_chunk].i_sample_count )
2582     {
2583         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2584                                   p_track->i_sample ) )
2585         {
2586             msg_Warn( p_demux, "track[0x%x] will be disabled "
2587                       "(cannot restart decoder)", p_track->i_track_ID );
2588             MP4_TrackUnselect( p_demux, p_track );
2589             return VLC_EGENERIC;
2590         }
2591     }
2592
2593     /* Have we changed elst */
2594     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2595     {
2596         demux_sys_t *p_sys = p_demux->p_sys;
2597         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2598         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2599                         p_sys->i_timescale / (int64_t)1000000;
2600
2601         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
2602             i_mvt >= p_track->i_elst_time +
2603                      elst->i_segment_duration[p_track->i_elst] )
2604         {
2605             MP4_TrackSetELST( p_demux, p_track,
2606                               MP4_TrackGetDTS( p_demux, p_track ) );
2607         }
2608     }
2609
2610     return VLC_SUCCESS;
2611 }
2612
2613 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2614                               int64_t i_time )
2615 {
2616     demux_sys_t *p_sys = p_demux->p_sys;
2617     int         i_elst_last = tk->i_elst;
2618
2619     /* handle elst (find the correct one) */
2620     tk->i_elst      = 0;
2621     tk->i_elst_time = 0;
2622     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2623     {
2624         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2625         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2626
2627         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2628         {
2629             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2630
2631             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2632             {
2633                 break;
2634             }
2635             tk->i_elst_time += i_dur;
2636         }
2637
2638         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
2639         {
2640             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2641             tk->i_elst = elst->i_entry_count - 1;
2642             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2643         }
2644
2645         if( elst->i_media_time[tk->i_elst] < 0 )
2646         {
2647             /* track offset */
2648             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2649         }
2650     }
2651     if( i_elst_last != tk->i_elst )
2652     {
2653         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2654     }
2655 }
2656
2657 /* */
2658 static const char *MP4_ConvertMacCode( uint16_t i_code )
2659 {
2660     static const struct { const char *psz_iso639_1; uint16_t i_code; } p_cvt[] = {
2661         { "en",   0 }, { "fr",   1 }, { "de",   2 }, { "it",   3 }, { "nl",   4 },
2662         { "sv",   5 }, { "es",   6 }, { "da",   7 }, { "pt",   8 }, { "no",   9 },
2663         { "he",  10 }, { "ja",  11 }, { "ar",  12 }, { "fi",  13 }, { "el",  14 },
2664         { "is",  15 }, { "mt",  16 }, { "tr",  17 }, { "hr",  18 }, { "zh",  19 },
2665         { "ur",  20 }, { "hi",  21 }, { "th",  22 }, { "ko",  23 }, { "lt",  24 },
2666         { "pl",  25 }, { "hu",  26 }, { "et",  27 }, { "lv",  28 }, //{ "??",  29 },
2667         { "fo",  30 }, { "fa",  31 }, { "ru",  32 }, { "zh",  33 }, { "nl",  34 },
2668         { "ga",  35 }, { "sq",  36 }, { "ro",  37 }, { "cs",  38 }, { "sk",  39 },
2669         { "sl",  40 }, { "yi",  41 }, { "sr",  42 }, { "mk",  43 }, { "bg",  44 },
2670         { "uk",  45 }, { "be",  46 }, { "uz",  47 }, { "az",  48 }, { "kk",  48 },
2671         { "az",  50 }, { "hy",  51 }, { "ka",  52 }, { "mo",  53 }, { "ky",  54 },
2672         { "tg",  55 }, { "tk",  56 }, { "mn",  57 }, { "mn",  58 }, { "ps",  59 },
2673         { "ku",  60 }, { "ks",  61 }, { "sd",  62 }, { "bo",  63 }, { "ne",  64 },
2674         { "sa",  65 }, { "mr",  66 }, { "bn",  67 }, { "as",  68 }, { "gu",  69 },
2675         { "pa",  70 }, { "or",  71 }, { "ml",  72 }, { "kn",  73 }, { "ta",  74 },
2676         { "te",  75 }, { "si",  76 }, { "my",  77 }, { "km",  78 }, { "lo",  79 },
2677         { "vi",  80 }, { "id",  81 }, { "tl",  82 }, { "ms",  83 }, { "ms",  84 },
2678         { "am",  85 }, { "ti",  86 }, { "om",  87 }, { "so",  88 }, { "sw",  89 },
2679         { "rw",  90 }, { "rn",  91 }, { "ny",  92 }, { "mg",  93 }, { "eo",  94 },
2680
2681                                                      { "cy", 128 }, { "eu", 129 },
2682         { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
2683         { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
2684         { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
2685         { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
2686         /* */
2687         { NULL, 0 }
2688     };
2689     int i;
2690     for( i = 0; p_cvt[i].psz_iso639_1 != NULL; i++ )
2691     {
2692         if( p_cvt[i].i_code == i_code )
2693             return p_cvt[i].psz_iso639_1;
2694     }
2695     return "";
2696 }