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