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