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