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