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