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