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