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