]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
* modules/demux/mp4/mp4.c: avoid reading raw audio (or slightly compressed) a sample...
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #include <stdlib.h>                                      /* malloc(), free() */
27
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30 #include <vlc_playlist.h>
31 #include "iso_lang.h"
32 #include "vlc_meta.h"
33
34 #include "libmp4.h"
35 #include "drms.h"
36
37 #ifdef UNDER_CE
38 #define uint64_t int64_t
39 #endif
40
41 /*****************************************************************************
42  * Module descriptor
43  *****************************************************************************/
44 static int  Open ( vlc_object_t * );
45 static void Close( vlc_object_t * );
46
47 vlc_module_begin();
48     set_description( _("MP4 stream demuxer") );
49     set_capability( "demux2", 242 );
50     set_callbacks( Open, Close );
51 vlc_module_end();
52
53 /*****************************************************************************
54  * Local prototypes
55  *****************************************************************************/
56 static int   Demux   ( demux_t * );
57 static int   DemuxRef( demux_t *p_demux ){ return 0;}
58 static int   Seek    ( demux_t *, mtime_t );
59 static int   Control ( demux_t *, int, va_list );
60
61 /* Contain all information about a chunk */
62 typedef struct
63 {
64     uint64_t     i_offset; /* absolute position of this chunk in the file */
65     uint32_t     i_sample_description_index; /* index for SampleEntry to use */
66     uint32_t     i_sample_count; /* how many samples in this chunk */
67     uint32_t     i_sample_first; /* index of the first sample in this chunk */
68
69     /* now provide way to calculate pts, dts, and offset without to
70         much memory and with fast acces */
71
72     /* with this we can calculate dts/pts without waste memory */
73     uint64_t     i_first_dts;
74     uint32_t     *p_sample_count_dts;
75     uint32_t     *p_sample_delta_dts; /* dts delta */
76
77     /* TODO if needed add pts
78         but quickly *add* support for edts and seeking */
79
80 } mp4_chunk_t;
81
82  /* Contain all needed information for read all track with vlc */
83 typedef struct
84 {
85     int i_track_ID;     /* this should be unique */
86
87     int b_ok;           /* The track is usable */
88     int b_enable;       /* is the trak enable by default */
89     vlc_bool_t b_selected;     /* is the trak being played */
90
91     es_format_t fmt;
92     es_out_id_t *p_es;
93
94     /* display size only ! */
95     int i_width;
96     int i_height;
97
98     /* more internal data */
99     uint64_t        i_timescale;    /* time scale for this track only */
100
101     /* elst */
102     int             i_elst;         /* current elst */
103     int64_t         i_elst_time;    /* current elst start time (in movie time scale)*/
104     MP4_Box_t       *p_elst;        /* elst (could be NULL) */
105
106     /* give the next sample to read, i_chunk is to find quickly where
107       the sample is located */
108     uint32_t         i_sample;       /* next sample to read */
109     uint32_t         i_chunk;        /* chunk where next sample is stored */
110     /* total count of chunk and sample */
111     uint32_t         i_chunk_count;
112     uint32_t         i_sample_count;
113
114     mp4_chunk_t    *chunk; /* always defined  for each chunk */
115
116     /* sample size, p_sample_size defined only if i_sample_size == 0
117         else i_sample_size is size for all sample */
118     uint32_t         i_sample_size;
119     uint32_t         *p_sample_size; /* XXX perhaps add file offset if take
120                                     too much time to do sumations each time*/
121
122     MP4_Box_t *p_stbl;  /* will contain all timing information */
123     MP4_Box_t *p_stsd;  /* will contain all data to initialize decoder */
124     MP4_Box_t *p_sample;/* point on actual sdsd */
125
126     vlc_bool_t b_drms;
127     void      *p_drms;
128
129 } mp4_track_t;
130
131
132 struct demux_sys_t
133 {
134     MP4_Box_t    *p_root;      /* container for the whole file */
135
136     mtime_t      i_pcr;
137
138     uint64_t     i_time;        /* time position of the presentation
139                                  * in movie timescale */
140     uint64_t     i_timescale;   /* movie time scale */
141     uint64_t     i_duration;    /* movie duration */
142     unsigned int i_tracks;      /* number of tracks */
143     mp4_track_t *track;    /* array of track */
144 };
145
146 /*****************************************************************************
147  * Declaration of local function
148  *****************************************************************************/
149 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *);
150 static void MP4_TrackDestroy( demux_t *, mp4_track_t * );
151
152 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
153 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
154
155 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
156
157 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
158 static int      MP4_TrackSampleSize( mp4_track_t * );
159 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
160 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
161
162 /* Return time in µs of a track */
163 static inline int64_t MP4_TrackGetPTS( demux_t *p_demux, mp4_track_t *p_track )
164 {
165 #define chunk p_track->chunk[p_track->i_chunk]
166
167     unsigned int i_index = 0;
168     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
169     int64_t i_dts = chunk.i_first_dts;
170
171     while( i_sample > 0 )
172     {
173         if( i_sample > chunk.p_sample_count_dts[i_index] )
174         {
175             i_dts += chunk.p_sample_count_dts[i_index] *
176                 chunk.p_sample_delta_dts[i_index];
177             i_sample -= chunk.p_sample_count_dts[i_index];
178             i_index++;
179         }
180         else
181         {
182             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
183             i_sample = 0;
184             break;
185         }
186     }
187
188 #undef chunk
189
190     /* now handle elst */
191     if( p_track->p_elst )
192     {
193         demux_sys_t         *p_sys = p_demux->p_sys;
194         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
195
196         /* convert to offset */
197         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
198               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
199             elst->i_media_time[p_track->i_elst] > 0 )
200         {
201             i_dts -= elst->i_media_time[p_track->i_elst];
202         }
203
204         /* add i_elst_time */
205         i_dts += p_track->i_elst_time * p_track->i_timescale /
206             p_sys->i_timescale;
207
208         if( i_dts < 0 ) i_dts = 0;
209     }
210
211     return I64C(1000000) * i_dts / p_track->i_timescale;
212 }
213
214 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
215 {
216     return I64C(1000000) * p_sys->i_time / p_sys->i_timescale;
217 }
218
219 #define FREE( p ) if( p ) { free( p ); (p) = NULL;}
220
221 /*****************************************************************************
222  * Open: check file and initializes MP4 structures
223  *****************************************************************************/
224 static int Open( vlc_object_t * p_this )
225 {
226     demux_t  *p_demux = (demux_t *)p_this;
227     demux_sys_t     *p_sys;
228
229     uint8_t         *p_peek;
230
231     MP4_Box_t       *p_ftyp;
232     MP4_Box_t       *p_rmra;
233     MP4_Box_t       *p_mvhd;
234     MP4_Box_t       *p_trak;
235
236     unsigned int    i;
237     vlc_bool_t      b_seekable;
238
239     /* a little test to see if it could be a mp4 */
240     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 )
241     {
242         msg_Warn( p_demux, "MP4 plugin discarded (cannot peek)" );
243         return VLC_EGENERIC;
244     }
245     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
246     {
247         case FOURCC_ftyp:
248         case FOURCC_moov:
249         case FOURCC_foov:
250         case FOURCC_moof:
251         case FOURCC_mdat:
252         case FOURCC_udta:
253         case FOURCC_free:
254         case FOURCC_skip:
255         case FOURCC_wide:
256         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
257             break;
258          default:
259             msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
260             return VLC_EGENERIC;
261     }
262
263     /* I need to seek */
264     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
265     if( !b_seekable )
266     {
267         msg_Warn( p_demux, "MP4 plugin discarded (unseekable)" );
268         return VLC_EGENERIC;
269     }
270
271     /*Set exported functions */
272     p_demux->pf_demux = Demux;
273     p_demux->pf_control = Control;
274
275     /* create our structure that will contains all data */
276     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
277     memset( p_sys, 0, sizeof( demux_sys_t ) );
278
279     /* Now load all boxes ( except raw data ) */
280     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
281     {
282         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
283         goto error;
284     }
285
286     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
287
288     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
289     {
290         switch( p_ftyp->data.p_ftyp->i_major_brand )
291         {
292             case( FOURCC_isom ):
293                 msg_Dbg( p_demux,
294                          "ISO Media file (isom) version %d.",
295                          p_ftyp->data.p_ftyp->i_minor_version );
296                 break;
297             default:
298                 msg_Dbg( p_demux,
299                          "unrecognized major file specification (%4.4s).",
300                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
301                 break;
302         }
303     }
304     else
305     {
306         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
307     }
308
309     /* the file need to have one moov box */
310     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
311     {
312         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
313
314         if( !p_foov )
315         {
316             msg_Err( p_demux, "MP4 plugin discarded (no moov box)" );
317             goto error;
318         }
319         /* we have a free box as a moov, rename it */
320         p_foov->i_type = FOURCC_moov;
321     }
322
323     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
324     {
325         playlist_t *p_playlist;
326         playlist_item_t *p_item;
327         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
328         int        i;
329         vlc_bool_t b_play = VLC_FALSE;
330
331         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
332
333         p_playlist =
334             (playlist_t *)vlc_object_find( p_demux,
335                                            VLC_OBJECT_PLAYLIST,
336                                            FIND_ANYWHERE );
337         if( p_playlist )
338         {
339             p_item = playlist_ItemGetByInput( p_playlist,
340                       ((input_thread_t *)p_demux->p_parent)->input.p_item );
341             playlist_ItemToNode( p_playlist, p_item );
342
343             for( i = 0; i < i_count; i++ )
344             {
345                 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
346                 char      *psz_ref;
347                 uint32_t  i_ref_type;
348
349                 if( !p_rdrf || !( psz_ref = p_rdrf->data.p_rdrf->psz_ref ) )
350                 {
351                     continue;
352                 }
353                 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
354
355                 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
356                          psz_ref, (char*)&i_ref_type );
357
358                 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
359                 {
360                     if( strstr( psz_ref, "qt5gateQT" ) )
361                     {
362                         msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
363                         continue;
364                     }
365                     if( !strncmp( psz_ref, "http://", 7 ) ||
366                         !strncmp( psz_ref, "rtsp://", 7 ) )
367                     {
368                         msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
369                         if( p_item )
370                         {
371                             playlist_item_t *p_child =
372                                         playlist_ItemNew( p_playlist,
373                                                           psz_ref, psz_ref );
374                             if( p_child )
375                             {
376                                 playlist_NodeAddItem( p_playlist, p_child,
377                                                  p_item->pp_parents[0]->i_view,
378                                                  p_item, PLAYLIST_APPEND,
379                                                  PLAYLIST_END );
380                                 playlist_CopyParents( p_item, p_child );
381                                 b_play = VLC_TRUE;
382                             }
383                         }
384                     }
385                     else
386                     {
387                         /* msg dbg relative ? */
388                         char *psz_absolute = alloca( strlen( p_demux->psz_access ) + 3 + strlen( p_demux->psz_path ) + strlen( psz_ref ) + 1);
389                         char *end = strrchr( p_demux->psz_path, '/' );
390
391                         if( end )
392                         {
393                             int i_len = end + 1 - p_demux->psz_path;
394
395                             strcpy( psz_absolute, p_demux->psz_access );
396                             strcat( psz_absolute, "://" );
397                             strncat( psz_absolute, p_demux->psz_path, i_len);
398                         }
399                         else
400                         {
401                             strcpy( psz_absolute, "" );
402                         }
403                         strcat( psz_absolute, psz_ref );
404                         msg_Dbg( p_demux, "adding ref = `%s'", psz_absolute );
405                         if( p_item )
406                         {
407                             playlist_item_t *p_child =
408                                         playlist_ItemNew( p_playlist,
409                                                           psz_absolute,
410                                                           psz_absolute );
411                             if( p_child )
412                             {
413                                 playlist_NodeAddItem( p_playlist, p_child,
414                                                  p_item->pp_parents[0]->i_view,
415                                                  p_item, PLAYLIST_APPEND,
416                                                  PLAYLIST_END );
417                                 playlist_CopyParents( p_item, p_child );
418                                 b_play = VLC_TRUE;
419                             }
420                         }
421                     }
422                 }
423                 else
424                 {
425                     msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
426                              (char*)&p_rdrf->data.p_rdrf->i_ref_type );
427                 }
428             }
429             if( b_play == VLC_TRUE )
430             {
431                  playlist_Control( p_playlist, PLAYLIST_VIEWPLAY,
432                                    p_playlist->status.i_view,
433                                    p_playlist->status.p_item, NULL );
434             }
435             vlc_object_release( p_playlist );
436         }
437         else
438         {
439             msg_Err( p_demux, "can't find playlist" );
440         }
441     }
442
443     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
444     {
445         if( !p_rmra )
446         {
447             msg_Err( p_demux, "cannot find /moov/mvhd" );
448             goto error;
449         }
450         else
451         {
452             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
453             p_demux->pf_demux = DemuxRef;
454             return VLC_SUCCESS;
455         }
456     }
457     else
458     {
459         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
460         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
461     }
462
463     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
464     {
465         msg_Err( p_demux, "cannot find any /moov/trak" );
466         goto error;
467     }
468     msg_Dbg( p_demux, "find %d track%c",
469                         p_sys->i_tracks,
470                         p_sys->i_tracks ? 's':' ' );
471
472     /* allocate memory */
473     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
474     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( mp4_track_t ) );
475
476     /* now process each track and extract all usefull information */
477     for( i = 0; i < p_sys->i_tracks; i++ )
478     {
479         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
480         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak );
481
482         if( p_sys->track[i].b_ok )
483         {
484             char *psz_cat;
485             switch( p_sys->track[i].fmt.i_cat )
486             {
487                 case( VIDEO_ES ):
488                     psz_cat = "video";
489                     break;
490                 case( AUDIO_ES ):
491                     psz_cat = "audio";
492                     break;
493                 case( SPU_ES ):
494                     psz_cat = "subtitle";
495                     break;
496
497                 default:
498                     psz_cat = "unknown";
499                     break;
500             }
501
502             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
503                      p_sys->track[i].i_track_ID, psz_cat,
504                      p_sys->track[i].b_enable ? "enable":"disable",
505                      p_sys->track[i].fmt.psz_language ?
506                      p_sys->track[i].fmt.psz_language : "undef" );
507         }
508         else
509         {
510             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
511                      p_sys->track[i].i_track_ID );
512         }
513
514     }
515     return VLC_SUCCESS;
516
517 error:
518     if( p_sys->p_root )
519     {
520         MP4_BoxFree( p_demux->s, p_sys->p_root );
521     }
522     free( p_sys );
523     return VLC_EGENERIC;
524 }
525
526 /*****************************************************************************
527  * Demux: read packet and send them to decoders
528  *****************************************************************************
529  * TODO check for newly selected track (ie audio upt to now )
530  *****************************************************************************/
531 static int Demux( demux_t *p_demux )
532 {
533     demux_sys_t *p_sys = p_demux->p_sys;
534     unsigned int i_track;
535
536
537     unsigned int i_track_selected;
538
539     /* check for newly selected/unselected track */
540     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
541          i_track++ )
542     {
543         mp4_track_t *tk = &p_sys->track[i_track];
544
545         if( tk->b_selected && tk->i_sample >= tk->i_sample_count )
546         {
547             msg_Warn( p_demux, "track[0x%x] will be disabled", tk->i_track_ID );
548             MP4_TrackUnselect( p_demux, tk);
549         }
550         else if( tk->b_ok )
551         {
552             vlc_bool_t b;
553             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
554
555             if( tk->b_selected && !b )
556             {
557                 MP4_TrackUnselect( p_demux, tk );
558             }
559             else if( !tk->b_selected && b)
560             {
561                 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
562             }
563
564             if( tk->b_selected )
565             {
566                 i_track_selected++;
567             }
568         }
569     }
570
571     if( i_track_selected <= 0 )
572     {
573         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
574         if( p_sys->i_timescale > 0 )
575         {
576             int64_t i_length = (mtime_t)1000000 *
577                                (mtime_t)p_sys->i_duration /
578                                (mtime_t)p_sys->i_timescale;
579             if( MP4_GetMoviePTS( p_sys ) >= i_length )
580                 return 0;
581             return 1;
582         }
583
584         msg_Warn( p_demux, "no track selected, exiting..." );
585         return 0;
586     }
587
588     /* first wait for the good time to read a packet */
589     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr + 1 );
590
591     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
592
593     /* we will read 100ms for each stream so ...*/
594     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
595
596     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
597     {
598         mp4_track_t *tk = &p_sys->track[i_track];
599
600         if( !tk->b_ok || !tk->b_selected )
601         {
602             continue;
603         }
604
605         while( MP4_TrackGetPTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
606         {
607 #if 0
608             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
609                      MP4_TrackGetPTS( p_demux, tk ),
610                      MP4_GetMoviePTS( p_sys ) );
611 #endif
612
613             if( MP4_TrackSampleSize( tk ) > 0 )
614             {
615                 block_t *p_block;
616
617                 /* go,go go ! */
618                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
619                 {
620                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
621                               tk->i_track_ID );
622                     MP4_TrackUnselect( p_demux, tk );
623                     break;
624                 }
625
626                 /* now read pes */
627                 if( !(p_block =
628                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
629                 {
630                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
631                               tk->i_track_ID );
632                     MP4_TrackUnselect( p_demux, tk );
633                     break;
634                 }
635
636                 if( tk->b_drms && tk->p_drms )
637                 {
638                     drms_decrypt( tk->p_drms, (uint32_t*)p_block->p_buffer,
639                                   p_block->i_buffer );
640                 }
641                 else if( tk->fmt.i_cat == SPU_ES )
642                 {
643                     if( tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
644                         p_block->i_buffer >= 2 )
645                     {
646                         uint16_t i_size = GetWBE( p_block->p_buffer );
647
648                         if( i_size + 2 <= p_block->i_buffer )
649                         {
650                             char *p;
651                             /* remove the length field, and append a '\0' */
652                             memmove( &p_block->p_buffer[0],
653                                      &p_block->p_buffer[2], i_size );
654                             p_block->p_buffer[i_size] = '\0';
655                             p_block->i_buffer = i_size + 1;
656
657                             /* convert \r -> \n */
658                             while( ( p = strchr( p_block->p_buffer, '\r' ) ) )
659                             {
660                                 *p = '\n';
661                             }
662                         }
663                         else
664                         {
665                             /* Invalid */
666                             p_block->i_buffer = 0;
667                         }
668                     }
669                 }
670                 p_block->i_dts = MP4_TrackGetPTS( p_demux, tk ) + 1;
671
672                 p_block->i_pts = tk->fmt.i_cat == VIDEO_ES ?
673                     0 : p_block->i_dts + 1;
674
675                 if( !tk->b_drms || ( tk->b_drms && tk->p_drms ) )
676                 {
677                     es_out_Send( p_demux->out, tk->p_es, p_block );
678                 }
679             }
680
681             /* Next sample */
682             if( MP4_TrackNextSample( p_demux, tk ) )
683             {
684                 break;
685             }
686         }
687     }
688
689     return 1;
690 }
691 /*****************************************************************************
692  * Seek: Got to i_date
693 ******************************************************************************/
694 static int Seek( demux_t *p_demux, mtime_t i_date )
695 {
696     demux_sys_t *p_sys = p_demux->p_sys;
697     unsigned int i_track;
698
699     /* First update update global time */
700     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
701     p_sys->i_pcr  = i_date;
702
703     /* Now for each stream try to go to this time */
704     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
705     {
706         mp4_track_t *tk = &p_sys->track[i_track];
707         MP4_TrackSeek( p_demux, tk, i_date );
708     }
709     return VLC_SUCCESS;
710 }
711
712 /*****************************************************************************
713  * Control:
714  *****************************************************************************/
715 static int Control( demux_t *p_demux, int i_query, va_list args )
716 {
717     demux_sys_t *p_sys = p_demux->p_sys;
718
719     double f, *pf;
720     int64_t i64, *pi64;
721
722     switch( i_query )
723     {
724         case DEMUX_GET_POSITION:
725             pf = (double*)va_arg( args, double * );
726             if( p_sys->i_duration > 0 )
727             {
728                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
729             }
730             else
731             {
732                 *pf = 0.0;
733             }
734             return VLC_SUCCESS;
735
736         case DEMUX_SET_POSITION:
737             f = (double)va_arg( args, double );
738             if( p_sys->i_timescale > 0 )
739             {
740                 i64 = (int64_t)( f * (double)1000000 *
741                                  (double)p_sys->i_duration /
742                                  (double)p_sys->i_timescale );
743                 return Seek( p_demux, i64 );
744             }
745             else return VLC_SUCCESS;
746
747         case DEMUX_GET_TIME:
748             pi64 = (int64_t*)va_arg( args, int64_t * );
749             if( p_sys->i_timescale > 0 )
750             {
751                 *pi64 = (mtime_t)1000000 *
752                         (mtime_t)p_sys->i_time /
753                         (mtime_t)p_sys->i_timescale;
754             }
755             else *pi64 = 0;
756             return VLC_SUCCESS;
757
758         case DEMUX_SET_TIME:
759             i64 = (int64_t)va_arg( args, int64_t );
760             return Seek( p_demux, i64 );
761
762         case DEMUX_GET_LENGTH:
763             pi64 = (int64_t*)va_arg( args, int64_t * );
764             if( p_sys->i_timescale > 0 )
765             {
766                 *pi64 = (mtime_t)1000000 *
767                         (mtime_t)p_sys->i_duration /
768                         (mtime_t)p_sys->i_timescale;
769             }
770             else *pi64 = 0;
771             return VLC_SUCCESS;
772
773         case DEMUX_GET_FPS:
774             msg_Warn( p_demux, "DEMUX_GET_FPS unimplemented !!" );
775             return VLC_EGENERIC;
776
777         case DEMUX_GET_META:
778         {
779             vlc_meta_t **pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
780             vlc_meta_t *meta;
781             MP4_Box_t  *p_udta   = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
782             MP4_Box_t  *p_0xa9xxx;
783             if( p_udta == NULL )
784             {
785                 return VLC_EGENERIC;
786             }
787             *pp_meta = meta = vlc_meta_New();
788             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
789                  p_0xa9xxx = p_0xa9xxx->p_next )
790             {
791                 switch( p_0xa9xxx->i_type )
792                 {
793                 case FOURCC_0xa9nam: /* Full name */
794                     vlc_meta_Add( meta, VLC_META_TITLE,
795                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
796                     break;
797                 case FOURCC_0xa9aut:
798                     vlc_meta_Add( meta, VLC_META_AUTHOR,
799                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
800                     break;
801                 case FOURCC_0xa9ART:
802                     vlc_meta_Add( meta, VLC_META_ARTIST,
803                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
804                     break;
805                 case FOURCC_0xa9cpy:
806                     vlc_meta_Add( meta, VLC_META_COPYRIGHT,
807                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
808                     break;
809                 case FOURCC_0xa9day: /* Creation Date */
810                     vlc_meta_Add( meta, VLC_META_DATE,
811                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
812                     break;
813                 case FOURCC_0xa9des: /* Description */
814                     vlc_meta_Add( meta, VLC_META_DESCRIPTION,
815                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
816                     break;
817                 case FOURCC_0xa9gen: /* Genre */
818                     vlc_meta_Add( meta, VLC_META_GENRE,
819                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
820                     break;
821
822                 case FOURCC_0xa9swr:
823                 case FOURCC_0xa9inf: /* Information */
824                 case FOURCC_0xa9alb: /* Album */
825                 case FOURCC_0xa9dir: /* Director */
826                 case FOURCC_0xa9dis: /* Disclaimer */
827                 case FOURCC_0xa9enc: /* Encoded By */
828                 case FOURCC_0xa9trk: /* Track */
829                 case FOURCC_0xa9cmt: /* Commment */
830                 case FOURCC_0xa9url: /* URL */
831                 case FOURCC_0xa9req: /* Requirements */
832                 case FOURCC_0xa9fmt: /* Original Format */
833                 case FOURCC_0xa9dsa: /* Display Source As */
834                 case FOURCC_0xa9hst: /* Host Computer */
835                 case FOURCC_0xa9prd: /* Producer */
836                 case FOURCC_0xa9prf: /* Performers */
837                 case FOURCC_0xa9ope: /* Original Performer */
838                 case FOURCC_0xa9src: /* Providers Source Content */
839                 case FOURCC_0xa9wrt: /* Writer */
840                 case FOURCC_0xa9com: /* Composer */
841                 case FOURCC_WLOC:    /* Window Location */
842                     /* TODO one day, but they aren't really meaningfull */
843                     break;
844
845                 default:
846                     break;
847                 }
848             }
849             return VLC_SUCCESS;
850         }
851
852         case DEMUX_GET_TITLE_INFO:
853         case DEMUX_SET_NEXT_DEMUX_TIME:
854         case DEMUX_SET_GROUP:
855             return VLC_EGENERIC;
856
857         default:
858             msg_Warn( p_demux, "control query unimplemented !!!" );
859             return VLC_EGENERIC;
860     }
861 }
862
863 /*****************************************************************************
864  * Close: frees unused data
865  *****************************************************************************/
866 static void Close ( vlc_object_t * p_this )
867 {
868     unsigned int i_track;
869     demux_t *  p_demux = (demux_t *)p_this;
870     demux_sys_t *p_sys = p_demux->p_sys;
871
872     msg_Dbg( p_demux, "freeing all memory" );
873
874     MP4_BoxFree( p_demux->s, p_sys->p_root );
875     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
876     {
877         MP4_TrackDestroy( p_demux, &p_sys->track[i_track] );
878     }
879     FREE( p_sys->track );
880
881     free( p_sys );
882 }
883
884
885
886 /****************************************************************************
887  * Local functions, specific to vlc
888  ****************************************************************************/
889
890 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
891 static int TrackCreateChunksIndex( demux_t *p_demux,
892                                    mp4_track_t *p_demux_track )
893 {
894     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
895     MP4_Box_t *p_stsc;
896
897     unsigned int i_chunk;
898     unsigned int i_index, i_last;
899
900     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
901           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
902         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
903     {
904         return( VLC_EGENERIC );
905     }
906
907     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
908     if( !p_demux_track->i_chunk_count )
909     {
910         msg_Warn( p_demux, "no chunk defined" );
911         return( VLC_EGENERIC );
912     }
913     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
914                                    sizeof( mp4_chunk_t ) );
915
916     /* first we read chunk offset */
917     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
918     {
919         p_demux_track->chunk[i_chunk].i_offset =
920                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
921     }
922
923     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
924         to be used for the sample XXX begin to 1
925         We construct it begining at the end */
926     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
927     i_index = p_stsc->data.p_stsc->i_entry_count;
928     if( !i_index )
929     {
930         msg_Warn( p_demux, "cannot read chunk table or table empty" );
931         return( VLC_EGENERIC );
932     }
933
934     while( i_index-- )
935     {
936         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
937              i_chunk < i_last; i_chunk++ )
938         {
939             p_demux_track->chunk[i_chunk].i_sample_description_index =
940                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
941             p_demux_track->chunk[i_chunk].i_sample_count =
942                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
943         }
944         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
945     }
946
947     p_demux_track->chunk[0].i_sample_first = 0;
948     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
949     {
950         p_demux_track->chunk[i_chunk].i_sample_first =
951             p_demux_track->chunk[i_chunk-1].i_sample_first +
952                 p_demux_track->chunk[i_chunk-1].i_sample_count;
953     }
954
955     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
956              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
957
958     return VLC_SUCCESS;
959 }
960
961 static int TrackCreateSamplesIndex( demux_t *p_demux,
962                                     mp4_track_t *p_demux_track )
963 {
964     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
965                           ctts make same mapping but for composition time,
966                           not yet used and probably not usefull */
967     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
968                           that uses a compressed form FIXME make them in libmp4
969                           as a unique type */
970     /* TODO use also stss and stsh table for seeking */
971     /* FIXME use edit table */
972     int64_t i_sample;
973     int64_t i_chunk;
974
975     int64_t i_index;
976     int64_t i_index_sample_used;
977
978     int64_t i_last_dts;
979
980     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
981     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
982
983     if( ( !p_stts )||( !p_stsz ) )
984     {
985         msg_Warn( p_demux, "cannot read sample table" );
986         return( VLC_EGENERIC );
987     }
988
989     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
990
991
992     /* for sample size, there are 2 case */
993     if( p_stsz->data.p_stsz->i_sample_size )
994     {
995         /* 1: all sample have the same size, so no need to construct a table */
996         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
997         p_demux_track->p_sample_size = NULL;
998     }
999     else
1000     {
1001         /* 2: each sample can have a different size */
1002         p_demux_track->i_sample_size = 0;
1003         p_demux_track->p_sample_size =
1004             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1005
1006         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1007         {
1008             p_demux_track->p_sample_size[i_sample] =
1009                     p_stsz->data.p_stsz->i_entry_size[i_sample];
1010         }
1011     }
1012     /* we have extracted all the information from stsz, now use stts */
1013
1014     /* if we don't want to waste too much memory, we can't expand
1015        the box! so each chunk will contain an "extract" of this table
1016        for fast research */
1017
1018     i_last_dts = 0;
1019     i_index = 0; i_index_sample_used = 0;
1020
1021     /* create and init last data for each chunk */
1022     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1023     {
1024
1025         int64_t i_entry, i_sample_count, i;
1026
1027         /* save last dts */
1028         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
1029
1030         /* count how many entries are needed for this chunk
1031          * for p_sample_delta_dts and p_sample_count_dts */
1032         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
1033
1034         i_entry = 0;
1035         while( i_sample_count > 0 )
1036         {
1037             i_sample_count -=
1038                 p_stts->data.p_stts->i_sample_count[i_index+i_entry];
1039             if( i_entry == 0 )
1040             {
1041                 /* don't count already used sample in this entry */
1042                 i_sample_count += i_index_sample_used;
1043             }
1044             i_entry++;
1045         }
1046
1047         /* allocate them */
1048         p_demux_track->chunk[i_chunk].p_sample_count_dts =
1049             calloc( i_entry, sizeof( uint32_t ) );
1050         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
1051             calloc( i_entry, sizeof( uint32_t ) );
1052
1053         /* now copy */
1054         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
1055         for( i = 0; i < i_entry; i++ )
1056         {
1057             int64_t i_used;
1058             int64_t i_rest;
1059
1060             i_rest = p_stts->data.p_stts->i_sample_count[i_index] -
1061                 i_index_sample_used;
1062
1063             i_used = __MIN( i_rest, i_sample_count );
1064
1065             i_index_sample_used += i_used;
1066             i_sample_count -= i_used;
1067
1068             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
1069
1070             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
1071                 p_stts->data.p_stts->i_sample_delta[i_index];
1072
1073             i_last_dts += i_used *
1074                 p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
1075
1076             if( i_index_sample_used >=
1077                 p_stts->data.p_stts->i_sample_count[i_index] )
1078             {
1079                 i_index++;
1080                 i_index_sample_used = 0;
1081             }
1082         }
1083     }
1084
1085     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:"I64Fd"s",
1086              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1087              i_last_dts / p_demux_track->i_timescale );
1088
1089     return VLC_SUCCESS;
1090 }
1091
1092 /*
1093  * TrackCreateES:
1094  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1095  */
1096 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1097                           unsigned int i_chunk, es_out_id_t **pp_es )
1098 {
1099     MP4_Box_t   *p_sample;
1100     MP4_Box_t   *p_esds;
1101
1102     *pp_es = NULL;
1103
1104     if( !p_track->chunk[i_chunk].i_sample_description_index )
1105     {
1106         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1107                   p_track->i_track_ID );
1108         return VLC_EGENERIC;
1109     }
1110
1111     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1112                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
1113
1114     if( !p_sample ||
1115         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1116     {
1117         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1118                   p_track->i_track_ID );
1119         return VLC_EGENERIC;
1120     }
1121
1122     p_track->p_sample = p_sample;
1123
1124     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size == 1 )
1125     {
1126         MP4_Box_data_sample_soun_t *p_soun;
1127
1128         p_soun = p_sample->data.p_sample_soun;
1129
1130         if( p_soun->i_qt_version == 0 )
1131         {
1132             switch( p_sample->i_type )
1133             {
1134                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1135                     p_soun->i_qt_version = 1;
1136                     p_soun->i_sample_per_packet = 64;
1137                     p_soun->i_bytes_per_packet  = 34;
1138                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1139                     p_soun->i_bytes_per_sample  = 2;
1140                     break;
1141                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1142                     p_soun->i_qt_version = 1;
1143                     p_soun->i_sample_per_packet = 6;
1144                     p_soun->i_bytes_per_packet  = 2;
1145                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1146                     p_soun->i_bytes_per_sample  = 2;
1147                     break;
1148                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1149                     p_soun->i_qt_version = 1;
1150                     p_soun->i_sample_per_packet = 12;
1151                     p_soun->i_bytes_per_packet  = 2;
1152                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1153                     p_soun->i_bytes_per_sample  = 2;
1154                     break;
1155                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1156                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1157                     p_soun->i_samplesize = 8;
1158                     break;
1159                 default:
1160                     break;
1161             }
1162
1163         }
1164         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1165         {
1166             p_soun->i_qt_version = 0;
1167         }
1168     }
1169
1170
1171     /* It's a little ugly but .. there are special cases */
1172     switch( p_sample->i_type )
1173     {
1174         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1175         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1176             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1177             break;
1178         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1179             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1180             break;
1181         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1182             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1183             break;
1184
1185         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1186             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1187             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1188             /* FIXME UTF-8 doesn't work here ? */
1189             /* p_track->fmt.subs.psz_encoding = strdup( "UTF-8" ); */
1190             break;
1191
1192         default:
1193             p_track->fmt.i_codec = p_sample->i_type;
1194             break;
1195     }
1196
1197     /* now see if esds is present and if so create a data packet
1198         with decoder_specific_info  */
1199 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1200     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1201           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1202         ( p_esds->data.p_esds )&&
1203         ( p_decconfig ) )
1204     {
1205         /* First update information based on i_objectTypeIndication */
1206         switch( p_decconfig->i_objectTypeIndication )
1207         {
1208             case( 0x20 ): /* MPEG4 VIDEO */
1209                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1210                 break;
1211             case( 0x40):
1212                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1213                 break;
1214             case( 0x60):
1215             case( 0x61):
1216             case( 0x62):
1217             case( 0x63):
1218             case( 0x64):
1219             case( 0x65): /* MPEG2 video */
1220                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1221                 break;
1222             /* Theses are MPEG2-AAC */
1223             case( 0x66): /* main profile */
1224             case( 0x67): /* Low complexity profile */
1225             case( 0x68): /* Scaleable Sampling rate profile */
1226                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1227                 break;
1228             /* true MPEG 2 audio */
1229             case( 0x69):
1230                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1231                 break;
1232             case( 0x6a): /* MPEG1 video */
1233                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1234                 break;
1235             case( 0x6b): /* MPEG1 audio */
1236                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1237                 break;
1238             case( 0x6c ): /* jpeg */
1239                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1240                 break;
1241
1242             /* Private ID */
1243             case( 0xe0 ): /* NeroDigital: dvd subs */
1244                 if( p_track->fmt.i_cat == SPU_ES )
1245                 {
1246                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1247                     break;
1248                 }
1249             /* Fallback */
1250             default:
1251                 /* Unknown entry, but don't touch i_fourcc */
1252                 msg_Warn( p_demux,
1253                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1254                           p_decconfig->i_objectTypeIndication,
1255                           p_track->i_track_ID );
1256                 break;
1257         }
1258         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1259         if( p_track->fmt.i_extra > 0 )
1260         {
1261             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1262             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1263                     p_track->fmt.i_extra );
1264         }
1265     }
1266     else
1267     {
1268         switch( p_sample->i_type )
1269         {
1270             /* qt decoder, send the complete chunk */
1271             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1272             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1273             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1274             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1275             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1276                 p_track->fmt.i_extra =
1277                     p_sample->data.p_sample_vide->i_qt_image_description;
1278                 if( p_track->fmt.i_extra > 0 )
1279                 {
1280                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1281                     memcpy( p_track->fmt.p_extra,
1282                             p_sample->data.p_sample_vide->p_qt_image_description,
1283                             p_track->fmt.i_extra);
1284                 }
1285                 break;
1286             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1287             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1288             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1289             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1290                 p_track->fmt.i_extra =
1291                     p_sample->data.p_sample_soun->i_qt_description;
1292                 if( p_track->fmt.i_extra > 0 )
1293                 {
1294                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1295                     memcpy( p_track->fmt.p_extra,
1296                             p_sample->data.p_sample_soun->p_qt_description,
1297                             p_track->fmt.i_extra);
1298                 }
1299                 break;
1300
1301             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1302             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1303             {
1304                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1305
1306                 if( p_avcC )
1307                 {
1308                     /* Hack: use a packetizer to reecampsulate data in anexe B format */
1309                     msg_Dbg( p_demux, "avcC: size=%d", p_avcC->data.p_avcC->i_avcC );
1310                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1311                     p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1312                     memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC, p_track->fmt.i_extra );
1313                     p_track->fmt.b_packetized = VLC_FALSE;
1314                 }
1315                 else
1316                 {
1317                     msg_Err( p_demux, "missing avcC" );
1318                 }
1319                 break;
1320             }
1321
1322             default:
1323                 break;
1324         }
1325     }
1326
1327 #undef p_decconfig
1328
1329     /* some last initialisation */
1330     switch( p_track->fmt.i_cat )
1331     {
1332     case( VIDEO_ES ):
1333         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1334         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1335
1336         /* fall on display size */
1337         if( p_track->fmt.video.i_width <= 0 )
1338             p_track->fmt.video.i_width = p_track->i_width;
1339         if( p_track->fmt.video.i_height <= 0 )
1340             p_track->fmt.video.i_height = p_track->i_height;
1341
1342         /* Find out apect ratio from display size */
1343         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1344             /* Work-around buggy muxed files */
1345             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1346             p_track->fmt.video.i_aspect =
1347                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1348
1349         break;
1350
1351     case( AUDIO_ES ):
1352         p_track->fmt.audio.i_channels =
1353             p_sample->data.p_sample_soun->i_channelcount;
1354         p_track->fmt.audio.i_rate =
1355             p_sample->data.p_sample_soun->i_sampleratehi;
1356         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1357             p_sample->data.p_sample_soun->i_sampleratehi *
1358                 p_sample->data.p_sample_soun->i_samplesize;
1359         p_track->fmt.audio.i_bitspersample =
1360             p_sample->data.p_sample_soun->i_samplesize;
1361         break;
1362
1363     default:
1364         break;
1365     }
1366
1367     *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1368
1369     return VLC_SUCCESS;
1370 }
1371
1372 /* given a time it return sample/chunk
1373  * it also update elst field of the track
1374  */
1375 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1376                                    int64_t i_start, uint32_t *pi_chunk,
1377                                    uint32_t *pi_sample )
1378 {
1379     demux_sys_t *p_sys = p_demux->p_sys;
1380     MP4_Box_t   *p_stss;
1381     uint64_t     i_dts;
1382     unsigned int i_sample;
1383     unsigned int i_chunk;
1384     int          i_index;
1385
1386     /* FIXME see if it's needed to check p_track->i_chunk_count */
1387     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1388     {
1389         return( VLC_EGENERIC );
1390     }
1391
1392     /* handle elst (find the correct one) */
1393     MP4_TrackSetELST( p_demux, p_track, i_start );
1394     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1395     {
1396         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1397         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1398
1399         /* now calculate i_start for this elst */
1400         /* offset */
1401         i_start -= p_track->i_elst_time * I64C(1000000) / p_sys->i_timescale;
1402         if( i_start < 0 )
1403         {
1404             *pi_chunk = 0;
1405             *pi_sample= 0;
1406
1407             return VLC_SUCCESS;
1408         }
1409         /* to track time scale */
1410         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1411         /* add elst offset */
1412         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1413              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1414             elst->i_media_time[p_track->i_elst] > 0 )
1415         {
1416             i_start += elst->i_media_time[p_track->i_elst];
1417         }
1418
1419         msg_Dbg( p_demux, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd
1420                  "ms (track)", p_track->i_elst,
1421                  i_mvt * 1000 / p_sys->i_timescale,
1422                  i_start * 1000 / p_track->i_timescale );
1423     }
1424     else
1425     {
1426         /* convert absolute time to in timescale unit */
1427         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1428     }
1429
1430     /* we start from sample 0/chunk 0, hope it won't take too much time */
1431     /* *** find good chunk *** */
1432     for( i_chunk = 0; ; i_chunk++ )
1433     {
1434         if( i_chunk + 1 >= p_track->i_chunk_count )
1435         {
1436             /* at the end and can't check if i_start in this chunk,
1437                it will be check while searching i_sample */
1438             i_chunk = p_track->i_chunk_count - 1;
1439             break;
1440         }
1441
1442         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1443             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1444         {
1445             break;
1446         }
1447     }
1448
1449     /* *** find sample in the chunk *** */
1450     i_sample = p_track->chunk[i_chunk].i_sample_first;
1451     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1452     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1453     {
1454         if( i_dts +
1455             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1456             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1457         {
1458             i_dts    +=
1459                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1460                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1461
1462             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1463             i_index++;
1464         }
1465         else
1466         {
1467             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1468             {
1469                 break;
1470             }
1471             i_sample += ( i_start - i_dts ) /
1472                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1473             break;
1474         }
1475     }
1476
1477     if( i_sample >= p_track->i_sample_count )
1478     {
1479         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1480                   "(seeking too far) chunk=%d sample=%d",
1481                   p_track->i_track_ID, i_chunk, i_sample );
1482         return( VLC_EGENERIC );
1483     }
1484
1485
1486     /* *** Try to find nearest sync points *** */
1487     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1488     {
1489         unsigned int i_index;
1490         msg_Dbg( p_demux,
1491                     "track[Id 0x%x] using Sync Sample Box (stss)",
1492                     p_track->i_track_ID );
1493         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1494         {
1495             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1496             {
1497                 if( i_index > 0 )
1498                 {
1499                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1500                             i_sample,
1501                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1502                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1503                     /* new i_sample is less than old so i_chunk can only decreased */
1504                     while( i_chunk > 0 &&
1505                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1506                     {
1507                         i_chunk--;
1508                     }
1509                 }
1510                 else
1511                 {
1512                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1513                             i_sample,
1514                             p_stss->data.p_stss->i_sample_number[i_index] );
1515                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1516                     /* new i_sample is more than old so i_chunk can only increased */
1517                     while( i_chunk < p_track->i_chunk_count - 1 &&
1518                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1519                              p_track->chunk[i_chunk].i_sample_count )
1520                     {
1521                         i_chunk++;
1522                     }
1523                 }
1524                 break;
1525             }
1526         }
1527     }
1528     else
1529     {
1530         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
1531                  "Sample Box (stss)", p_track->i_track_ID );
1532     }
1533
1534     *pi_chunk  = i_chunk;
1535     *pi_sample = i_sample;
1536
1537     return VLC_SUCCESS;
1538 }
1539
1540 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
1541                                  unsigned int i_chunk, unsigned int i_sample )
1542 {
1543     vlc_bool_t b_reselect = VLC_FALSE;
1544
1545     /* now see if actual es is ok */
1546     if( p_track->i_chunk < 0 ||
1547         p_track->i_chunk >= p_track->i_chunk_count - 1 ||
1548         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1549             p_track->chunk[i_chunk].i_sample_description_index )
1550     {
1551         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
1552                   p_track->i_track_ID );
1553
1554         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1555                         p_track->p_es, &b_reselect );
1556
1557         es_out_Del( p_demux->out, p_track->p_es );
1558
1559         p_track->p_es = NULL;
1560
1561         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
1562         {
1563             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1564                      p_track->i_track_ID );
1565
1566             p_track->b_ok       = VLC_FALSE;
1567             p_track->b_selected = VLC_FALSE;
1568             return VLC_EGENERIC;
1569         }
1570     }
1571
1572     /* select again the new decoder */
1573     if( b_reselect )
1574     {
1575         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
1576     }
1577
1578     p_track->i_chunk    = i_chunk;
1579     p_track->i_sample   = i_sample;
1580
1581     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1582 }
1583
1584 /****************************************************************************
1585  * MP4_TrackCreate:
1586  ****************************************************************************
1587  * Parse track information and create all needed data to run a track
1588  * If it succeed b_ok is set to 1 else to 0
1589  ****************************************************************************/
1590 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
1591                              MP4_Box_t *p_box_trak )
1592 {
1593     demux_sys_t *p_sys = p_demux->p_sys;
1594
1595     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1596     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1597     MP4_Box_t *p_elst;
1598
1599     MP4_Box_t *p_mdhd;
1600     MP4_Box_t *p_udta;
1601     MP4_Box_t *p_hdlr;
1602
1603     MP4_Box_t *p_vmhd;
1604     MP4_Box_t *p_smhd;
1605
1606     MP4_Box_t *p_drms;
1607
1608     unsigned int i;
1609     char language[4];
1610
1611     /* hint track unsuported */
1612
1613     /* set default value (-> track unusable) */
1614     p_track->b_ok       = VLC_FALSE;
1615     p_track->b_enable   = VLC_FALSE;
1616     p_track->b_selected = VLC_FALSE;
1617
1618     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1619
1620     if( !p_tkhd )
1621     {
1622         return;
1623     }
1624
1625     /* do we launch this track by default ? */
1626     p_track->b_enable =
1627         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1628
1629     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1630     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1631     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1632
1633     if( p_tref )
1634     {
1635 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
1636     }
1637
1638     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1639     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1640
1641     if( ( !p_mdhd )||( !p_hdlr ) )
1642     {
1643         return;
1644     }
1645
1646     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1647
1648     for( i = 0; i < 3; i++ )
1649     {
1650         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1651     }
1652     language[3] = '\0';
1653
1654     switch( p_hdlr->data.p_hdlr->i_handler_type )
1655     {
1656         case( FOURCC_soun ):
1657             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1658             {
1659                 return;
1660             }
1661             p_track->fmt.i_cat = AUDIO_ES;
1662             break;
1663
1664         case( FOURCC_vide ):
1665             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1666             {
1667                 return;
1668             }
1669             p_track->fmt.i_cat = VIDEO_ES;
1670             break;
1671
1672         case( FOURCC_text ):
1673         case( FOURCC_subp ):
1674             p_track->fmt.i_cat = SPU_ES;
1675             break;
1676
1677         default:
1678             return;
1679     }
1680
1681     p_track->i_elst = 0;
1682     p_track->i_elst_time = 0;
1683     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1684     {
1685         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
1686         int i;
1687
1688         msg_Warn( p_demux, "elst box found" );
1689         for( i = 0; i < elst->i_entry_count; i++ )
1690         {
1691             msg_Dbg( p_demux, "   - [%d] duration="I64Fd"ms media time="I64Fd
1692                      "ms) rate=%d.%d", i,
1693                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
1694                      elst->i_media_time[i] >= 0 ?
1695                      elst->i_media_time[i] * 1000 / p_track->i_timescale : -1,
1696                      elst->i_media_rate_integer[i],
1697                      elst->i_media_rate_fraction[i] );
1698         }
1699     }
1700
1701
1702 /*  TODO
1703     add support for:
1704     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1705 */
1706     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1707         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1708     {
1709         return;
1710     }
1711
1712     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
1713     p_track->b_drms = p_drms != NULL;
1714     p_track->p_drms = p_track->b_drms ?
1715         p_drms->data.p_sample_soun->p_drms : NULL;
1716
1717     /* Set language */
1718     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1719     {
1720         p_track->fmt.psz_language = strdup( language );
1721     }
1722
1723     p_udta = MP4_BoxGet( p_box_trak, "udta" );
1724     if( p_udta )
1725     {
1726         MP4_Box_t *p_0xa9xxx;
1727         for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1728                  p_0xa9xxx = p_0xa9xxx->p_next )
1729         {
1730             switch( p_0xa9xxx->i_type )
1731             {
1732                 case FOURCC_0xa9nam:
1733                     p_track->fmt.psz_description =
1734                         strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text );
1735                     break;
1736             }
1737         }
1738     }
1739
1740     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1741     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1742     {
1743         MP4_Box_t *p_sample;
1744
1745         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1746         if( p_sample && p_sample->data.p_sample_soun)
1747         {
1748             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1749             if( p_soun->i_qt_version == 0 &&
1750                 p_track->i_timescale != p_soun->i_sampleratehi )
1751             {
1752                 msg_Warn( p_demux,
1753                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1754                           "qt_version == 0\n"
1755                           "Making both equal. (report any problem)",
1756                           p_track->i_timescale, p_soun->i_sampleratehi );
1757
1758                 if( p_soun->i_sampleratehi )
1759                     p_track->i_timescale = p_soun->i_sampleratehi;
1760                 else
1761                     p_soun->i_sampleratehi = p_track->i_timescale;
1762             }
1763         }
1764     }
1765
1766     /* Create chunk index table and sample index table */
1767     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
1768         TrackCreateSamplesIndex( p_demux, p_track ) )
1769     {
1770         return; /* cannot create chunks index */
1771     }
1772
1773     p_track->i_chunk  = 0;
1774     p_track->i_sample = 0;
1775
1776     /* now create es */
1777     if( TrackCreateES( p_demux,
1778                        p_track, p_track->i_chunk,
1779                        &p_track->p_es ) )
1780     {
1781         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1782                  p_track->i_track_ID );
1783         return;
1784     }
1785
1786 #if 0
1787     {
1788         int i;
1789         for( i = 0; i < p_track->i_chunk_count; i++ )
1790         {
1791             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
1792                      i, p_track->chunk[i].i_sample_count,
1793                      p_track->chunk[i].i_first_dts );
1794
1795         }
1796     }
1797 #endif
1798     p_track->b_ok = VLC_TRUE;
1799 }
1800
1801 /****************************************************************************
1802  * MP4_TrackDestroy:
1803  ****************************************************************************
1804  * Destroy a track created by MP4_TrackCreate.
1805  ****************************************************************************/
1806 static void MP4_TrackDestroy( demux_t *p_demux, mp4_track_t *p_track )
1807 {
1808     unsigned int i_chunk;
1809
1810     p_track->b_ok = VLC_FALSE;
1811     p_track->b_enable   = VLC_FALSE;
1812     p_track->b_selected = VLC_FALSE;
1813
1814     es_format_Clean( &p_track->fmt );
1815
1816     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1817     {
1818         if( p_track->chunk )
1819         {
1820            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1821            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1822         }
1823     }
1824     FREE( p_track->chunk );
1825
1826     if( !p_track->i_sample_size )
1827     {
1828         FREE( p_track->p_sample_size );
1829     }
1830 }
1831
1832 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
1833                             mtime_t i_start )
1834 {
1835     if( !p_track->b_ok )
1836     {
1837         return VLC_EGENERIC;
1838     }
1839
1840     if( p_track->b_selected )
1841     {
1842         msg_Warn( p_demux, "track[Id 0x%x] already selected",
1843                   p_track->i_track_ID );
1844         return VLC_SUCCESS;
1845     }
1846
1847     return MP4_TrackSeek( p_demux, p_track, i_start );
1848 }
1849
1850 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
1851 {
1852     if( !p_track->b_ok )
1853     {
1854         return;
1855     }
1856
1857     if( !p_track->b_selected )
1858     {
1859         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
1860                   p_track->i_track_ID );
1861         return;
1862     }
1863     if( p_track->p_es )
1864     {
1865         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
1866                         p_track->p_es, VLC_FALSE );
1867     }
1868
1869     p_track->b_selected = VLC_FALSE;
1870 }
1871
1872 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
1873                           mtime_t i_start )
1874 {
1875     uint32_t i_chunk;
1876     uint32_t i_sample;
1877
1878     if( !p_track->b_ok )
1879     {
1880         return( VLC_EGENERIC );
1881     }
1882
1883     p_track->b_selected = VLC_FALSE;
1884
1885     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
1886                                 &i_chunk, &i_sample ) )
1887     {
1888         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
1889                   p_track->i_track_ID );
1890         return( VLC_EGENERIC );
1891     }
1892
1893     p_track->b_selected = VLC_TRUE;
1894
1895     if( TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) ==
1896         VLC_SUCCESS )
1897     {
1898         p_track->b_selected = VLC_TRUE;
1899     }
1900     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
1901 }
1902
1903
1904 /*
1905  * 3 types: for audio
1906  * 
1907  */
1908 #define QT_V0_MAX_SAMPLES 1024
1909 static int MP4_TrackSampleSize( mp4_track_t *p_track )
1910 {
1911     int i_size;
1912     MP4_Box_data_sample_soun_t *p_soun;
1913
1914     if( p_track->i_sample_size == 0 )
1915     {
1916         /* most simple case */
1917         return p_track->p_sample_size[p_track->i_sample];
1918     }
1919     if( p_track->fmt.i_cat != AUDIO_ES )
1920     {
1921         return p_track->i_sample_size;
1922     }
1923
1924     p_soun = p_track->p_sample->data.p_sample_soun;
1925
1926     if( p_soun->i_qt_version == 1 )
1927     {
1928         i_size = p_track->chunk[p_track->i_chunk].i_sample_count /
1929             p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
1930     }
1931     else if( p_track->i_sample_size > 256 )
1932     {
1933         /* We do that so we don't read too much data
1934          * (in this case we are likely dealing with compressed data) */
1935         i_size = p_track->i_sample_size;
1936     }
1937     else
1938     {
1939         /* Read a bunch of samples at once */
1940         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
1941             ( p_track->i_sample -
1942               p_track->chunk[p_track->i_chunk].i_sample_first );
1943
1944         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
1945         i_size = i_samples * p_track->i_sample_size;
1946     }
1947
1948     //fprintf( stderr, "size=%d\n", i_size );
1949     return i_size;
1950 }
1951
1952 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
1953 {
1954     unsigned int i_sample;
1955     uint64_t i_pos;
1956
1957     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
1958
1959     if( p_track->i_sample_size )
1960     {
1961         MP4_Box_data_sample_soun_t *p_soun =
1962             p_track->p_sample->data.p_sample_soun;
1963
1964         if( p_soun->i_qt_version == 0 )
1965         {
1966             i_pos += ( p_track->i_sample -
1967                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
1968                      p_track->i_sample_size;
1969         }
1970         else
1971         {
1972             /* we read chunk by chunk */
1973             i_pos += 0;
1974         }
1975     }
1976     else
1977     {
1978         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
1979              i_sample < p_track->i_sample; i_sample++ )
1980         {
1981             i_pos += p_track->p_sample_size[i_sample];
1982         }
1983     }
1984
1985     return i_pos;
1986 }
1987
1988 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
1989 {
1990     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
1991     {
1992         MP4_Box_data_sample_soun_t *p_soun;
1993
1994         p_soun = p_track->p_sample->data.p_sample_soun;
1995
1996         if( p_soun->i_qt_version == 1 )
1997         {
1998             /* chunk by chunk */
1999             p_track->i_sample =
2000                 p_track->chunk[p_track->i_chunk].i_sample_first +
2001                 p_track->chunk[p_track->i_chunk].i_sample_count;
2002         }
2003         else if( p_track->i_sample_size > 256 )
2004         {
2005             /* We do that so we don't read too much data
2006              * (in this case we are likely dealing with compressed data) */
2007             p_track->i_sample += 1;
2008         }
2009         else
2010         {
2011             /* FIXME */
2012             p_track->i_sample += QT_V0_MAX_SAMPLES;
2013             if( p_track->i_sample >
2014                 p_track->chunk[p_track->i_chunk].i_sample_first +
2015                 p_track->chunk[p_track->i_chunk].i_sample_count )
2016             {
2017                 p_track->i_sample =
2018                     p_track->chunk[p_track->i_chunk].i_sample_first +
2019                     p_track->chunk[p_track->i_chunk].i_sample_count;
2020             }
2021         }
2022     }
2023     else
2024     {
2025         p_track->i_sample++;
2026     }
2027
2028     if( p_track->i_sample >= p_track->i_sample_count )
2029     {
2030         /* we have reach end of the track so free decoder stuff */
2031         msg_Warn( p_demux, "track[0x%x] will be disabled", p_track->i_track_ID );
2032         MP4_TrackUnselect( p_demux, p_track );
2033         return VLC_EGENERIC;
2034     }
2035
2036     /* Have we changed chunk ? */
2037     if( p_track->i_sample >=
2038             p_track->chunk[p_track->i_chunk].i_sample_first +
2039             p_track->chunk[p_track->i_chunk].i_sample_count )
2040     {
2041         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2042                                   p_track->i_sample ) )
2043         {
2044             msg_Warn( p_demux, "track[0x%x] will be disabled "
2045                       "(cannot restart decoder)", p_track->i_track_ID );
2046             MP4_TrackUnselect( p_demux, p_track );
2047             return VLC_EGENERIC;
2048         }
2049     }
2050
2051     /* Have we changed elst */
2052     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2053     {
2054         demux_sys_t *p_sys = p_demux->p_sys;
2055         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2056         int64_t i_mvt = MP4_TrackGetPTS( p_demux, p_track ) *
2057                         p_sys->i_timescale / (int64_t)1000000;
2058
2059         if( p_track->i_elst < elst->i_entry_count &&
2060             i_mvt >= p_track->i_elst_time +
2061                      elst->i_segment_duration[p_track->i_elst] )
2062         {
2063             MP4_TrackSetELST( p_demux, p_track,
2064                               MP4_TrackGetPTS( p_demux, p_track ) );
2065         }
2066     }
2067
2068     return VLC_SUCCESS;
2069 }
2070
2071 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2072                               int64_t i_time )
2073 {
2074     demux_sys_t *p_sys = p_demux->p_sys;
2075     int         i_elst_last = tk->i_elst;
2076
2077     /* handle elst (find the correct one) */
2078     tk->i_elst      = 0;
2079     tk->i_elst_time = 0;
2080     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2081     {
2082         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2083         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2084
2085         for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2086         {
2087             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2088
2089             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2090             {
2091                 break;
2092             }
2093             tk->i_elst_time += i_dur;
2094         }
2095
2096         if( tk->i_elst >= elst->i_entry_count )
2097         {
2098             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2099             tk->i_elst = elst->i_entry_count - 1;
2100             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2101         }
2102
2103         if( elst->i_media_time[tk->i_elst] < 0 )
2104         {
2105             /* track offset */
2106             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2107         }
2108     }
2109     if( i_elst_last != tk->i_elst )
2110     {
2111         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2112     }
2113 }