]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
* mp4: support vobsub in .mp4 (NeroRecode), but won't work if the video
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN
5  * $Id$
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #include <stdlib.h>                                      /* malloc(), free() */
27
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30 #include <vlc_playlist.h>
31 #include "iso_lang.h"
32 #include "vlc_meta.h"
33
34 #include "libmp4.h"
35 #include "drms.h"
36
37 /*****************************************************************************
38  * Module descriptor
39  *****************************************************************************/
40 static int  Open ( vlc_object_t * );
41 static void Close( vlc_object_t * );
42
43 vlc_module_begin();
44     set_description( _("MP4 stream demuxer") );
45     set_capability( "demux2", 242 );
46     set_callbacks( Open, Close );
47 vlc_module_end();
48
49 /*****************************************************************************
50  * Local prototypes
51  *****************************************************************************/
52 static int    Demux   ( demux_t * );
53 static int    DemuxRef( demux_t *p_demux )
54 {
55     return 0;
56 }
57 static int   Seek     ( demux_t *, mtime_t );
58 static int   Control  ( demux_t *, int, va_list );
59
60 /* Contain all information about a chunk */
61 typedef struct
62 {
63     uint64_t     i_offset; /* absolute position of this chunk in the file */
64     uint32_t     i_sample_description_index; /* index for SampleEntry to use */
65     uint32_t     i_sample_count; /* how many samples in this chunk */
66     uint32_t     i_sample_first; /* index of the first sample in this chunk */
67
68     /* now provide way to calculate pts, dts, and offset without to
69         much memory and with fast acces */
70
71     /* with this we can calculate dts/pts without waste memory */
72     uint64_t     i_first_dts;
73     uint32_t     *p_sample_count_dts;
74     uint32_t     *p_sample_delta_dts; /* dts delta */
75
76     /* TODO if needed add pts
77         but quickly *add* support for edts and seeking */
78
79 } mp4_chunk_t;
80
81
82  /* Contain all needed information for read all track with vlc */
83 typedef struct
84 {
85     int i_track_ID;     /* this should be unique */
86
87     int b_ok;           /* The track is usable */
88     int b_enable;       /* is the trak enable by default */
89     vlc_bool_t b_selected;     /* is the trak being played */
90
91     es_format_t fmt;
92     es_out_id_t *p_es;
93
94     /* display size only ! */
95     int i_width;
96     int i_height;
97
98     /* more internal data */
99     uint64_t        i_timescale;    /* time scale for this track only */
100
101     /* elst */
102     int             i_elst;         /* current elst */
103     int64_t         i_elst_time;    /* current elst start time (in movie time scale)*/
104     MP4_Box_t       *p_elst;        /* elst (could be NULL) */
105
106     /* give the next sample to read, i_chunk is to find quickly where
107       the sample is located */
108     uint32_t         i_sample;       /* next sample to read */
109     uint32_t         i_chunk;        /* chunk where next sample is stored */
110     /* total count of chunk and sample */
111     uint32_t         i_chunk_count;
112     uint32_t         i_sample_count;
113
114     mp4_chunk_t    *chunk; /* always defined  for each chunk */
115
116     /* sample size, p_sample_size defined only if i_sample_size == 0
117         else i_sample_size is size for all sample */
118     uint32_t         i_sample_size;
119     uint32_t         *p_sample_size; /* XXX perhaps add file offset if take
120                                     too much time to do sumations each time*/
121
122     MP4_Box_t *p_stbl;  /* will contain all timing information */
123     MP4_Box_t *p_stsd;  /* will contain all data to initialize decoder */
124     MP4_Box_t *p_sample;/* point on actual sdsd */
125
126     vlc_bool_t b_drms;
127     void      *p_drms;
128
129 } mp4_track_t;
130
131
132 struct demux_sys_t
133 {
134     MP4_Box_t    *p_root;      /* container for the whole file */
135
136     mtime_t      i_pcr;
137
138     uint64_t     i_time;        /* time position of the presentation
139                                  * in movie timescale */
140     uint64_t     i_timescale;   /* movie time scale */
141     uint64_t     i_duration;    /* movie duration */
142     unsigned int i_tracks;      /* number of tracks */
143     mp4_track_t *track;    /* array of track */
144 };
145
146
147 /*****************************************************************************
148  * Declaration of local function
149  *****************************************************************************/
150 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *);
151 static void MP4_TrackDestroy( demux_t *, mp4_track_t * );
152
153 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
154 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
155
156 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
157
158 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
159 static int      MP4_TrackSampleSize( mp4_track_t * );
160 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
161 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
162
163 /* Return time in µs of a track */
164 static inline int64_t MP4_TrackGetPTS( demux_t *p_demux, mp4_track_t *p_track )
165 {
166     unsigned int i_sample;
167     unsigned int i_index;
168     int64_t i_dts;
169
170     i_sample = p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first;
171     i_dts = p_track->chunk[p_track->i_chunk].i_first_dts;
172     i_index = 0;
173     while( i_sample > 0 )
174     {
175         if( i_sample > p_track->chunk[p_track->i_chunk].p_sample_count_dts[i_index] )
176         {
177             i_dts += p_track->chunk[p_track->i_chunk].p_sample_count_dts[i_index] *
178                         p_track->chunk[p_track->i_chunk].p_sample_delta_dts[i_index];
179             i_sample -= p_track->chunk[p_track->i_chunk].p_sample_count_dts[i_index];
180             i_index++;
181         }
182         else
183         {
184             i_dts += i_sample *
185                         p_track->chunk[p_track->i_chunk].p_sample_delta_dts[i_index];
186             i_sample = 0;
187             break;
188         }
189     }
190
191     /* now handle elst */
192     if( p_track->p_elst )
193     {
194         demux_sys_t         *p_sys = p_demux->p_sys;
195         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
196
197         /* convert to offset */
198         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
199               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
200             elst->i_media_time[p_track->i_elst] > 0 )
201         {
202             i_dts -= elst->i_media_time[p_track->i_elst];
203         }
204
205         /* add i_elst_time */
206         i_dts += p_track->i_elst_time * p_track->i_timescale / p_sys->i_timescale;
207
208         if( i_dts < 0 ) i_dts = 0;
209     }
210
211     return (int64_t)1000000 * i_dts / p_track->i_timescale;
212 }
213 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
214 {
215     return (int64_t)1000000 * p_sys->i_time / p_sys->i_timescale;
216 }
217
218 #define FREE( p ) if( p ) { free( p ); (p) = NULL;}
219
220 /*****************************************************************************
221  * Open: check file and initializes MP4 structures
222  *****************************************************************************/
223 static int Open( vlc_object_t * p_this )
224 {
225     demux_t  *p_demux = (demux_t *)p_this;
226     demux_sys_t     *p_sys;
227
228     uint8_t         *p_peek;
229
230     MP4_Box_t       *p_ftyp;
231     MP4_Box_t       *p_rmra;
232     MP4_Box_t       *p_mvhd;
233     MP4_Box_t       *p_trak;
234
235     unsigned int    i;
236     vlc_bool_t      b_seekable;
237
238     /* a little test to see if it could be a mp4 */
239     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 )
240     {
241         msg_Warn( p_demux, "MP4 plugin discarded (cannot peek)" );
242         return VLC_EGENERIC;
243     }
244     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
245     {
246         case FOURCC_ftyp:
247         case FOURCC_moov:
248         case FOURCC_foov:
249         case FOURCC_moof:
250         case FOURCC_mdat:
251         case FOURCC_udta:
252         case FOURCC_free:
253         case FOURCC_skip:
254         case FOURCC_wide:
255         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
256             break;
257          default:
258             msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
259             return VLC_EGENERIC;
260     }
261
262     /* I need to seek */
263     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
264     if( !b_seekable )
265     {
266         msg_Warn( p_demux, "MP4 plugin discarded (unseekable)" );
267         return VLC_EGENERIC;
268     }
269
270     /*Set exported functions */
271     p_demux->pf_demux = Demux;
272     p_demux->pf_control = Control;
273
274     /* create our structure that will contains all data */
275     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
276     memset( p_sys, 0, sizeof( demux_sys_t ) );
277
278     /* Now load all boxes ( except raw data ) */
279     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
280     {
281         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
282         goto error;
283     }
284
285     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
286
287     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
288     {
289         switch( p_ftyp->data.p_ftyp->i_major_brand )
290         {
291             case( FOURCC_isom ):
292                 msg_Dbg( p_demux,
293                          "ISO Media file (isom) version %d.",
294                          p_ftyp->data.p_ftyp->i_minor_version );
295                 break;
296             default:
297                 msg_Dbg( p_demux,
298                          "unrecognized major file specification (%4.4s).",
299                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
300                 break;
301         }
302     }
303     else
304     {
305         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
306     }
307
308     /* the file need to have one moov box */
309     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
310     {
311         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
312
313         if( !p_foov )
314         {
315             msg_Err( p_demux, "MP4 plugin discarded (no moov box)" );
316             goto error;
317         }
318         /* we have a free box as a moov, rename it */
319         p_foov->i_type = FOURCC_moov;
320     }
321
322     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
323     {
324         playlist_t *p_playlist;
325         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
326         int        i;
327
328         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
329
330         p_playlist =
331             (playlist_t *)vlc_object_find( p_demux,
332                                            VLC_OBJECT_PLAYLIST,
333                                            FIND_ANYWHERE );
334         if( p_playlist )
335         {
336             //p_playlist->pp_items[p_playlist->i_index]->b_autodeletion = VLC_TRUE;
337             for( i = 0; i < i_count; i++ )
338             {
339                 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
340                 char      *psz_ref;
341                 uint32_t  i_ref_type;
342
343                 if( !p_rdrf || !( psz_ref = p_rdrf->data.p_rdrf->psz_ref ) )
344                 {
345                     continue;
346                 }
347                 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
348
349                 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
350                          psz_ref, (char*)&i_ref_type );
351
352                 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
353                 {
354                     if( strstr( psz_ref, "qt5gateQT" ) )
355                     {
356                         msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
357                         continue;
358                     }
359                     if( !strncmp( psz_ref, "http://", 7 ) ||
360                         !strncmp( psz_ref, "rtsp://", 7 ) )
361                     {
362                         msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
363                         playlist_Add( p_playlist, psz_ref, psz_ref,
364                                       PLAYLIST_APPEND, PLAYLIST_END );
365                     }
366                     else
367                     {
368                         /* msg dbg relative ? */
369                         char *psz_absolute = alloca( strlen( p_demux->psz_access ) + 3 + strlen( p_demux->psz_path ) + strlen( psz_ref ) + 1);
370                         char *end = strrchr( p_demux->psz_path, '/' );
371
372                         if( end )
373                         {
374                             int i_len = end + 1 - p_demux->psz_path;
375
376                             strcpy( psz_absolute, p_demux->psz_access );
377                             strcat( psz_absolute, "://" );
378                             strncat( psz_absolute, p_demux->psz_path, i_len);
379                         }
380                         else
381                         {
382                             strcpy( psz_absolute, "" );
383                         }
384                         strcat( psz_absolute, psz_ref );
385                         msg_Dbg( p_demux, "adding ref = `%s'", psz_absolute );
386                         playlist_Add( p_playlist, psz_absolute, psz_absolute,
387                                       PLAYLIST_APPEND, PLAYLIST_END );
388                     }
389                 }
390                 else
391                 {
392                     msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
393                              (char*)&p_rdrf->data.p_rdrf->i_ref_type );
394                 }
395             }
396             vlc_object_release( p_playlist );
397         }
398         else
399         {
400             msg_Err( p_demux, "can't find playlist" );
401         }
402     }
403
404     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
405     {
406         if( !p_rmra )
407         {
408             msg_Err( p_demux, "cannot find /moov/mvhd" );
409             goto error;
410         }
411         else
412         {
413             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
414             p_demux->pf_demux = DemuxRef;
415             return VLC_SUCCESS;
416         }
417     }
418     else
419     {
420         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
421         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
422     }
423
424     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
425     {
426         msg_Err( p_demux, "cannot find any /moov/trak" );
427         goto error;
428     }
429     msg_Dbg( p_demux, "find %d track%c",
430                         p_sys->i_tracks,
431                         p_sys->i_tracks ? 's':' ' );
432
433     /* allocate memory */
434     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
435     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( mp4_track_t ) );
436
437     /* now process each track and extract all usefull information */
438     for( i = 0; i < p_sys->i_tracks; i++ )
439     {
440         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
441         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak );
442
443         if( p_sys->track[i].b_ok )
444         {
445             char *psz_cat;
446             switch( p_sys->track[i].fmt.i_cat )
447             {
448                 case( VIDEO_ES ):
449                     psz_cat = "video";
450                     break;
451                 case( AUDIO_ES ):
452                     psz_cat = "audio";
453                     break;
454                 case( SPU_ES ):
455                     psz_cat = "subtitle";
456                     break;
457
458                 default:
459                     psz_cat = "unknown";
460                     break;
461             }
462
463             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
464                             p_sys->track[i].i_track_ID,
465                             psz_cat,
466                             p_sys->track[i].b_enable ? "enable":"disable",
467                             p_sys->track[i].fmt.psz_language ? p_sys->track[i].fmt.psz_language : "undef" );
468         }
469         else
470         {
471             msg_Dbg( p_demux, "ignoring track[Id 0x%x]", p_sys->track[i].i_track_ID );
472         }
473
474     }
475     return VLC_SUCCESS;
476
477 error:
478     if( p_sys->p_root )
479     {
480         MP4_BoxFree( p_demux->s, p_sys->p_root );
481     }
482     free( p_sys );
483     return VLC_EGENERIC;
484 }
485
486 /*****************************************************************************
487  * Demux: read packet and send them to decoders
488  *****************************************************************************
489  * TODO check for newly selected track (ie audio upt to now )
490  *****************************************************************************/
491 static int Demux( demux_t *p_demux )
492 {
493     demux_sys_t *p_sys = p_demux->p_sys;
494     unsigned int i_track;
495
496
497     unsigned int i_track_selected;
498
499     /* check for newly selected/unselected track */
500     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
501          i_track++ )
502     {
503         mp4_track_t *tk = &p_sys->track[i_track];
504
505         if( tk->b_selected && tk->i_sample >= tk->i_sample_count )
506         {
507             msg_Warn( p_demux, "track[0x%x] will be disabled", tk->i_track_ID );
508             MP4_TrackUnselect( p_demux, tk);
509         }
510         else if( tk->b_ok )
511         {
512             vlc_bool_t b;
513             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
514
515             if( tk->b_selected && !b )
516             {
517                 MP4_TrackUnselect( p_demux, tk );
518             }
519             else if( !tk->b_selected && b)
520             {
521                 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
522             }
523
524             if( tk->b_selected )
525             {
526                 i_track_selected++;
527             }
528         }
529     }
530
531     if( i_track_selected <= 0 )
532     {
533         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
534         if( p_sys->i_timescale > 0 )
535         {
536             int64_t i_length = (mtime_t)1000000 *
537                                (mtime_t)p_sys->i_duration /
538                                (mtime_t)p_sys->i_timescale;
539             if( MP4_GetMoviePTS( p_sys ) >= i_length )
540                 return 0;
541             return 1;
542         }
543
544         msg_Warn( p_demux, "no track selected, exiting..." );
545         return 0;
546     }
547
548     /* first wait for the good time to read a packet */
549     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr + 1 );
550
551     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
552
553     /* we will read 100ms for each stream so ...*/
554     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
555
556     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
557     {
558         mp4_track_t *tk = &p_sys->track[i_track];
559
560         if( !tk->b_ok || !tk->b_selected )
561         {
562             continue;
563         }
564
565         while( MP4_TrackGetPTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
566         {
567 #if 0
568             msg_Dbg( p_demux, "tk=%lld mv=%lld",
569                      MP4_TrackGetPTS( p_demux, tk ),
570                      MP4_GetMoviePTS( p_sys ) );
571 #endif
572
573             if( MP4_TrackSampleSize( tk ) > 0 )
574             {
575                 block_t *p_block;
576
577                 /* go,go go ! */
578                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
579                 {
580                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)", tk->i_track_ID );
581                     MP4_TrackUnselect( p_demux, tk );
582                     break;
583                 }
584
585                 /* now read pes */
586                 if( ( p_block = stream_Block( p_demux->s,
587                                               MP4_TrackSampleSize( tk ) ) ) == NULL )
588                 {
589                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)", tk->i_track_ID );
590                     MP4_TrackUnselect( p_demux, tk );
591                     break;
592                 }
593
594                 if( tk->b_drms && tk->p_drms )
595                 {
596                     drms_decrypt( tk->p_drms,
597                                   (uint32_t*)p_block->p_buffer,
598                                   p_block->i_buffer );
599                 }
600                 else if( tk->fmt.i_cat == SPU_ES )
601                 {
602                     if( tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) && p_block->i_buffer >= 2 )
603                     {
604                         uint16_t i_size = GetWBE( p_block->p_buffer );
605
606                         if( i_size + 2 <= p_block->i_buffer )
607                         {
608                             char *p;
609                             /* remove the length field, and append a '\0' */
610                             memmove( &p_block->p_buffer[0], &p_block->p_buffer[2], i_size );
611                             p_block->p_buffer[i_size] = '\0';
612                             p_block->i_buffer = i_size + 1;
613
614                             /* convert \r -> \n */
615                             while( ( p = strchr( p_block->p_buffer, '\r' ) ) )
616                             {
617                                 *p = '\n';
618                             }
619                         }
620                         else
621                         {
622                             /* Invalid */
623                             p_block->i_buffer = 0;
624                         }
625                     }
626                 }
627                 p_block->i_dts = MP4_TrackGetPTS( p_demux, tk ) + 1;
628                 fprintf( stderr, "dts=%lld\n", p_block->i_dts );
629
630                 p_block->i_pts = tk->fmt.i_cat == VIDEO_ES ? 0 : p_block->i_dts + 1;
631
632                 if( !tk->b_drms || ( tk->b_drms && tk->p_drms ) )
633                 {
634                     es_out_Send( p_demux->out, tk->p_es, p_block );
635                 }
636             }
637
638             /* Next sample */
639             if( MP4_TrackNextSample( p_demux, tk ) )
640             {
641                 break;
642             }
643         }
644     }
645
646     return 1;
647 }
648 /*****************************************************************************
649  * Seek: Got to i_date
650 ******************************************************************************/
651 static int Seek( demux_t *p_demux, mtime_t i_date )
652 {
653     demux_sys_t *p_sys = p_demux->p_sys;
654     unsigned int i_track;
655
656     /* First update update global time */
657     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
658     p_sys->i_pcr  = i_date;
659
660     /* Now for each stream try to go to this time */
661     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
662     {
663         mp4_track_t *tk = &p_sys->track[i_track];
664         MP4_TrackSeek( p_demux, tk, i_date );
665     }
666     return VLC_SUCCESS;
667 }
668
669 /*****************************************************************************
670  * Control:
671  *****************************************************************************/
672 static int Control( demux_t *p_demux, int i_query, va_list args )
673 {
674     demux_sys_t *p_sys = p_demux->p_sys;
675
676     double f, *pf;
677     int64_t i64, *pi64;
678
679     switch( i_query )
680     {
681         case DEMUX_GET_POSITION:
682             pf = (double*)va_arg( args, double * );
683             if( p_sys->i_duration > 0 )
684             {
685                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
686             }
687             else
688             {
689                 *pf = 0.0;
690             }
691             return VLC_SUCCESS;
692
693         case DEMUX_SET_POSITION:
694             f = (double)va_arg( args, double );
695             if( p_sys->i_timescale > 0 )
696             {
697                 i64 = (int64_t)( f * (double)1000000 *
698                                  (double)p_sys->i_duration /
699                                  (double)p_sys->i_timescale );
700                 return Seek( p_demux, i64 );
701             }
702             else return VLC_SUCCESS;
703
704         case DEMUX_GET_TIME:
705             pi64 = (int64_t*)va_arg( args, int64_t * );
706             if( p_sys->i_timescale > 0 )
707             {
708                 *pi64 = (mtime_t)1000000 *
709                         (mtime_t)p_sys->i_time /
710                         (mtime_t)p_sys->i_timescale;
711             }
712             else *pi64 = 0;
713             return VLC_SUCCESS;
714
715         case DEMUX_SET_TIME:
716             i64 = (int64_t)va_arg( args, int64_t );
717             return Seek( p_demux, i64 );
718
719         case DEMUX_GET_LENGTH:
720             pi64 = (int64_t*)va_arg( args, int64_t * );
721             if( p_sys->i_timescale > 0 )
722             {
723                 *pi64 = (mtime_t)1000000 *
724                         (mtime_t)p_sys->i_duration /
725                         (mtime_t)p_sys->i_timescale;
726             }
727             else *pi64 = 0;
728             return VLC_SUCCESS;
729
730         case DEMUX_GET_FPS:
731             msg_Warn( p_demux, "DEMUX_GET_FPS unimplemented !!" );
732             return VLC_EGENERIC;
733
734         case DEMUX_GET_META:
735         {
736             vlc_meta_t **pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
737             vlc_meta_t *meta;
738             MP4_Box_t  *p_udta   = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
739             MP4_Box_t  *p_0xa9xxx;
740             if( p_udta == NULL )
741             {
742                 return VLC_EGENERIC;
743             }
744             *pp_meta = meta = vlc_meta_New();
745             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
746                  p_0xa9xxx = p_0xa9xxx->p_next )
747             {
748                 switch( p_0xa9xxx->i_type )
749                 {
750                 case FOURCC_0xa9nam:
751                     vlc_meta_Add( meta, VLC_META_TITLE,
752                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
753                     break;
754                 case FOURCC_0xa9aut:
755                     vlc_meta_Add( meta, VLC_META_AUTHOR,
756                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
757                     break;
758                 case FOURCC_0xa9ART:
759                     vlc_meta_Add( meta, VLC_META_ARTIST,
760                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
761                     break;
762                 case FOURCC_0xa9cpy:
763                     vlc_meta_Add( meta, VLC_META_COPYRIGHT,
764                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
765                     break;
766                 case FOURCC_0xa9day:
767                     vlc_meta_Add( meta, VLC_META_DATE,
768                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
769                     break;
770                 case FOURCC_0xa9des:
771                     vlc_meta_Add( meta, VLC_META_DESCRIPTION,
772                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
773                     break;
774
775                 case FOURCC_0xa9swr:
776                 case FOURCC_0xa9inf:
777                 case FOURCC_0xa9dir:
778                 case FOURCC_0xa9cmt:
779                 case FOURCC_0xa9req:
780                 case FOURCC_0xa9fmt:
781                 case FOURCC_0xa9prd:
782                 case FOURCC_0xa9prf:
783                 case FOURCC_0xa9src:
784                     /* TODO one day, but they aren't really meaningfull */
785                     break;
786
787                 default:
788                     break;
789                 }
790             }
791             return VLC_SUCCESS;
792         }
793
794         case DEMUX_GET_TITLE_INFO:
795         case DEMUX_SET_NEXT_DEMUX_TIME:
796         case DEMUX_SET_GROUP:
797             return VLC_EGENERIC;
798
799         default:
800             msg_Warn( p_demux, "control query unimplemented !!!" );
801             return VLC_EGENERIC;
802     }
803 }
804
805 /*****************************************************************************
806  * Close: frees unused data
807  *****************************************************************************/
808 static void Close ( vlc_object_t * p_this )
809 {
810     unsigned int i_track;
811     demux_t *  p_demux = (demux_t *)p_this;
812     demux_sys_t *p_sys = p_demux->p_sys;
813
814     msg_Dbg( p_demux, "freeing all memory" );
815
816     MP4_BoxFree( p_demux->s, p_sys->p_root );
817     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
818     {
819         MP4_TrackDestroy( p_demux, &p_sys->track[i_track] );
820     }
821     FREE( p_sys->track );
822
823     free( p_sys );
824 }
825
826
827
828 /****************************************************************************
829  * Local functions, specific to vlc
830  ****************************************************************************/
831
832 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
833 static int TrackCreateChunksIndex( demux_t *p_demux,
834                                    mp4_track_t *p_demux_track )
835 {
836     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
837     MP4_Box_t *p_stsc;
838
839     unsigned int i_chunk;
840     unsigned int i_index, i_last;
841
842     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
843           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
844         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
845     {
846         return( VLC_EGENERIC );
847     }
848
849     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
850     if( !p_demux_track->i_chunk_count )
851     {
852         msg_Warn( p_demux, "no chunk defined" );
853         return( VLC_EGENERIC );
854     }
855     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
856                                    sizeof( mp4_chunk_t ) );
857
858     /* first we read chunk offset */
859     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
860     {
861         p_demux_track->chunk[i_chunk].i_offset =
862                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
863     }
864
865     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
866         to be used for the sample XXX begin to 1
867         We construct it begining at the end */
868     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
869     i_index = p_stsc->data.p_stsc->i_entry_count;
870     if( !i_index )
871     {
872         msg_Warn( p_demux, "cannot read chunk table or table empty" );
873         return( VLC_EGENERIC );
874     }
875
876     while( i_index )
877     {
878         i_index--;
879         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
880                 i_chunk < i_last; i_chunk++ )
881         {
882             p_demux_track->chunk[i_chunk].i_sample_description_index =
883                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
884             p_demux_track->chunk[i_chunk].i_sample_count =
885                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
886         }
887         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
888     }
889
890     p_demux_track->chunk[0].i_sample_first = 0;
891     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
892     {
893         p_demux_track->chunk[i_chunk].i_sample_first =
894             p_demux_track->chunk[i_chunk-1].i_sample_first +
895                 p_demux_track->chunk[i_chunk-1].i_sample_count;
896     }
897
898     msg_Dbg( p_demux,
899              "track[Id 0x%x] read %d chunk",
900              p_demux_track->i_track_ID,
901              p_demux_track->i_chunk_count );
902
903     return( VLC_SUCCESS );
904 }
905 static int TrackCreateSamplesIndex( demux_t *p_demux,
906                                     mp4_track_t *p_demux_track )
907 {
908     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
909                           ctts make same mapping but for composition time,
910                           not yet used and probably not usefull */
911     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
912                           that uses a compressed form FIXME make them in libmp4
913                           as a unique type */
914     /* TODO use also stss and stsh table for seeking */
915     /* FIXME use edit table */
916     int64_t i_sample;
917     int64_t i_chunk;
918
919     int64_t i_index;
920     int64_t i_index_sample_used;
921
922     int64_t i_last_dts;
923
924     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
925     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
926
927     if( ( !p_stts )||( !p_stsz ) )
928     {
929         msg_Warn( p_demux, "cannot read sample table" );
930         return( VLC_EGENERIC );
931     }
932
933     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
934
935
936     /* for sample size, there are 2 case */
937     if( p_stsz->data.p_stsz->i_sample_size )
938     {
939         /* 1: all sample have the same size, so no need to construct a table */
940         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
941         p_demux_track->p_sample_size = NULL;
942     }
943     else
944     {
945         /* 2: each sample can have a different size */
946         p_demux_track->i_sample_size = 0;
947         p_demux_track->p_sample_size =
948             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
949
950         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
951         {
952             p_demux_track->p_sample_size[i_sample] =
953                     p_stsz->data.p_stsz->i_entry_size[i_sample];
954         }
955     }
956     /* we have extract all information from stsz,
957         now use stts */
958
959     /* if we don't want to waste too much memory, we can't expand
960        the box !, so each chunk will contain an "extract" of this table
961        for fast research */
962
963     i_last_dts = 0;
964     i_index = 0; i_index_sample_used =0;
965
966     /* create and init last data for each chunk */
967     for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
968     {
969
970         int64_t i_entry, i_sample_count, i;
971         /* save last dts */
972         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
973     /* count how many entries needed for this chunk
974        for p_sample_delta_dts and p_sample_count_dts */
975
976         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
977
978         i_entry = 0;
979         while( i_sample_count > 0 )
980         {
981             i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
982             if( i_entry == 0 )
983             {
984                 i_sample_count += i_index_sample_used; /* don't count already used sample
985                                                    int this entry */
986             }
987             i_entry++;
988         }
989
990         /* allocate them */
991         p_demux_track->chunk[i_chunk].p_sample_count_dts =
992             calloc( i_entry, sizeof( uint32_t ) );
993         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
994             calloc( i_entry, sizeof( uint32_t ) );
995
996         /* now copy */
997         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
998         for( i = 0; i < i_entry; i++ )
999         {
1000             int64_t i_used;
1001             int64_t i_rest;
1002
1003             i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;
1004
1005             i_used = __MIN( i_rest, i_sample_count );
1006
1007             i_index_sample_used += i_used;
1008             i_sample_count -= i_used;
1009
1010             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
1011
1012             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
1013                         p_stts->data.p_stts->i_sample_delta[i_index];
1014
1015             i_last_dts += i_used *
1016                     p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
1017
1018             if( i_index_sample_used >=
1019                              p_stts->data.p_stts->i_sample_count[i_index] )
1020             {
1021
1022                 i_index++;
1023                 i_index_sample_used = 0;
1024             }
1025         }
1026
1027     }
1028
1029     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:"I64Fd"s",
1030              p_demux_track->i_track_ID,
1031              p_demux_track->i_sample_count,
1032              i_last_dts / p_demux_track->i_timescale );
1033
1034     return( VLC_SUCCESS );
1035 }
1036
1037 /*
1038  * TrackCreateES:
1039  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1040  */
1041 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1042                           unsigned int i_chunk, es_out_id_t **pp_es )
1043 {
1044     MP4_Box_t   *p_sample;
1045     MP4_Box_t   *p_esds;
1046
1047     *pp_es = NULL;
1048
1049     if( !p_track->chunk[i_chunk].i_sample_description_index )
1050     {
1051         msg_Warn( p_demux,
1052                   "invalid SampleEntry index (track[Id 0x%x])",
1053                   p_track->i_track_ID );
1054         return VLC_EGENERIC;
1055     }
1056
1057     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1058                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
1059
1060     if( !p_sample || ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1061     {
1062         msg_Warn( p_demux,
1063                   "cannot find SampleEntry (track[Id 0x%x])",
1064                   p_track->i_track_ID );
1065         return( VLC_EGENERIC );
1066     }
1067
1068     p_track->p_sample = p_sample;
1069
1070     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size == 1 )
1071     {
1072         MP4_Box_data_sample_soun_t *p_soun;
1073
1074         p_soun = p_sample->data.p_sample_soun;
1075
1076         if( p_soun->i_qt_version == 0 )
1077         {
1078             switch( p_sample->i_type )
1079             {
1080                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1081                     p_soun->i_qt_version = 1;
1082                     p_soun->i_sample_per_packet = 64;
1083                     p_soun->i_bytes_per_packet  = 34;
1084                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1085                     p_soun->i_bytes_per_sample  = 2;
1086                     break;
1087                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1088                     p_soun->i_qt_version = 1;
1089                     p_soun->i_sample_per_packet = 6;
1090                     p_soun->i_bytes_per_packet  = 2;
1091                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1092                     p_soun->i_bytes_per_sample  = 2;
1093                     break;
1094                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1095                     p_soun->i_qt_version = 1;
1096                     p_soun->i_sample_per_packet = 12;
1097                     p_soun->i_bytes_per_packet  = 2;
1098                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1099                     p_soun->i_bytes_per_sample  = 2;
1100                     break;
1101                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1102                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1103                     p_soun->i_samplesize = 8;
1104                     break;
1105                 default:
1106                     break;
1107             }
1108
1109         }
1110         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1111         {
1112             p_soun->i_qt_version = 0;
1113         }
1114     }
1115
1116
1117     /* It's a little ugly but .. there are special cases */
1118     switch( p_sample->i_type )
1119     {
1120         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1121         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1122             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1123             break;
1124         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1125             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1126             break;
1127         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1128             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1129             break;
1130
1131         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1132             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1133             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1134             /* FIXME UTF-8 doesn't work here ? */
1135             /* p_track->fmt.subs.psz_encoding = strdup( "UTF-8" ); */
1136             break;
1137
1138         default:
1139             p_track->fmt.i_codec = p_sample->i_type;
1140             break;
1141     }
1142
1143     /* now see if esds is present and if so create a data packet
1144         with decoder_specific_info  */
1145 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1146     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1147           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1148         ( p_esds->data.p_esds )&&
1149         ( p_decconfig ) )
1150     {
1151         /* First update information based on i_objectTypeIndication */
1152         switch( p_decconfig->i_objectTypeIndication )
1153         {
1154             case( 0x20 ): /* MPEG4 VIDEO */
1155                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1156                 break;
1157             case( 0x40):
1158                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1159                 break;
1160             case( 0x60):
1161             case( 0x61):
1162             case( 0x62):
1163             case( 0x63):
1164             case( 0x64):
1165             case( 0x65): /* MPEG2 video */
1166                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1167                 break;
1168             /* Theses are MPEG2-AAC */
1169             case( 0x66): /* main profile */
1170             case( 0x67): /* Low complexity profile */
1171             case( 0x68): /* Scaleable Sampling rate profile */
1172                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1173                 break;
1174             /* true MPEG 2 audio */
1175             case( 0x69):
1176                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1177                 break;
1178             case( 0x6a): /* MPEG1 video */
1179                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1180                 break;
1181             case( 0x6b): /* MPEG1 audio */
1182                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1183                 break;
1184             case( 0x6c ): /* jpeg */
1185                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1186                 break;
1187
1188             /* Private ID */
1189             case( 0xe0 ): /* NeroDigital: dvd subs */
1190                 if( p_track->fmt.i_cat == SPU_ES )
1191                 {
1192                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1193                     break;
1194                 }
1195             /* Fallback */
1196             default:
1197                 /* Unknown entry, but don't touch i_fourcc */
1198                 msg_Warn( p_demux,
1199                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1200                           p_decconfig->i_objectTypeIndication,
1201                           p_track->i_track_ID );
1202                 break;
1203         }
1204         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1205         if( p_track->fmt.i_extra > 0 )
1206         {
1207             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1208             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1209                     p_track->fmt.i_extra );
1210         }
1211     }
1212     else
1213     {
1214         switch( p_sample->i_type )
1215         {
1216             /* qt decoder, send the complete chunk */
1217             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1218             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1219             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1220             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1221             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1222                 p_track->fmt.i_extra =
1223                     p_sample->data.p_sample_vide->i_qt_image_description;
1224                 if( p_track->fmt.i_extra > 0 )
1225                 {
1226                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1227                     memcpy( p_track->fmt.p_extra,
1228                             p_sample->data.p_sample_vide->p_qt_image_description,
1229                             p_track->fmt.i_extra);
1230                 }
1231                 break;
1232             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1233             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1234             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1235             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1236                 p_track->fmt.i_extra =
1237                     p_sample->data.p_sample_soun->i_qt_description;
1238                 if( p_track->fmt.i_extra > 0 )
1239                 {
1240                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1241                     memcpy( p_track->fmt.p_extra,
1242                             p_sample->data.p_sample_soun->p_qt_description,
1243                             p_track->fmt.i_extra);
1244                 }
1245                 break;
1246
1247             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1248             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1249             {
1250                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1251
1252                 if( p_avcC )
1253                 {
1254                     /* Hack: use a packetizer to reecampsulate data in anexe B format */
1255                     msg_Dbg( p_demux, "avcC: size=%d", p_avcC->data.p_avcC->i_avcC );
1256                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1257                     p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1258                     memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC, p_track->fmt.i_extra );
1259                     p_track->fmt.b_packetized = VLC_FALSE;
1260                 }
1261                 else
1262                 {
1263                     msg_Err( p_demux, "missing avcC" );
1264                 }
1265                 break;
1266             }
1267
1268             default:
1269                 break;
1270         }
1271     }
1272
1273 #undef p_decconfig
1274
1275     /* some last initialisation */
1276     switch( p_track->fmt.i_cat )
1277     {
1278     case( VIDEO_ES ):
1279         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1280         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1281
1282         /* fall on display size */
1283         if( p_track->fmt.video.i_width <= 0 )
1284             p_track->fmt.video.i_width = p_track->i_width;
1285         if( p_track->fmt.video.i_height <= 0 )
1286             p_track->fmt.video.i_height = p_track->i_height;
1287
1288         /* Find out apect ratio from display size */
1289         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1290             /* Work-around buggy muxed files */
1291             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1292             p_track->fmt.video.i_aspect =
1293                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1294
1295         break;
1296
1297     case( AUDIO_ES ):
1298         p_track->fmt.audio.i_channels =
1299             p_sample->data.p_sample_soun->i_channelcount;
1300         p_track->fmt.audio.i_rate =
1301             p_sample->data.p_sample_soun->i_sampleratehi;
1302         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1303             p_sample->data.p_sample_soun->i_sampleratehi *
1304                 p_sample->data.p_sample_soun->i_samplesize;
1305         p_track->fmt.audio.i_bitspersample =
1306             p_sample->data.p_sample_soun->i_samplesize;
1307         break;
1308
1309     default:
1310         break;
1311     }
1312
1313     *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1314
1315     return VLC_SUCCESS;
1316 }
1317
1318 /* given a time it return sample/chunk
1319  * it also update elst field of the track
1320  */
1321 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1322                                    int64_t i_start, uint32_t *pi_chunk,
1323                                    uint32_t *pi_sample )
1324 {
1325     demux_sys_t *p_sys = p_demux->p_sys;
1326     MP4_Box_t   *p_stss;
1327     uint64_t     i_dts;
1328     unsigned int i_sample;
1329     unsigned int i_chunk;
1330     int          i_index;
1331
1332     /* FIXME see if it's needed to check p_track->i_chunk_count */
1333     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1334     {
1335         return( VLC_EGENERIC );
1336     }
1337
1338     /* handle elst (find the correct one) */
1339     MP4_TrackSetELST( p_demux, p_track, i_start );
1340     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1341     {
1342         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1343         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1344
1345         /* now calculate i_start for this elst */
1346         /* offset */
1347         i_start -= p_track->i_elst_time * I64C(1000000) / p_sys->i_timescale;
1348         if( i_start < 0 )
1349         {
1350             *pi_chunk = 0;
1351             *pi_sample= 0;
1352
1353             return VLC_SUCCESS;
1354         }
1355         /* to track time scale */
1356         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1357         /* add elst offset */
1358         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1359              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1360             elst->i_media_time[p_track->i_elst] > 0 )
1361         {
1362             i_start += elst->i_media_time[p_track->i_elst];
1363         }
1364
1365         msg_Dbg( p_demux, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd
1366                  "ms (track)", p_track->i_elst,
1367                  i_mvt * 1000 / p_sys->i_timescale,
1368                  i_start * 1000 / p_track->i_timescale );
1369     }
1370     else
1371     {
1372         /* convert absolute time to in timescale unit */
1373         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1374     }
1375
1376     /* we start from sample 0/chunk 0, hope it won't take too much time */
1377     /* *** find good chunk *** */
1378     for( i_chunk = 0; ; i_chunk++ )
1379     {
1380         if( i_chunk + 1 >= p_track->i_chunk_count )
1381         {
1382             /* at the end and can't check if i_start in this chunk,
1383                it will be check while searching i_sample */
1384             i_chunk = p_track->i_chunk_count - 1;
1385             break;
1386         }
1387
1388         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1389             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1390         {
1391             break;
1392         }
1393     }
1394
1395     /* *** find sample in the chunk *** */
1396     i_sample = p_track->chunk[i_chunk].i_sample_first;
1397     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1398     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1399     {
1400         if( i_dts +
1401             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1402             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1403         {
1404             i_dts    +=
1405                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1406                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1407
1408             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1409             i_index++;
1410         }
1411         else
1412         {
1413             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1414             {
1415                 break;
1416             }
1417             i_sample += ( i_start - i_dts ) /
1418                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1419             break;
1420         }
1421     }
1422
1423     if( i_sample >= p_track->i_sample_count )
1424     {
1425         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1426                   "(seeking too far) chunk=%d sample=%d",
1427                   p_track->i_track_ID, i_chunk, i_sample );
1428         return( VLC_EGENERIC );
1429     }
1430
1431
1432     /* *** Try to find nearest sync points *** */
1433     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1434     {
1435         unsigned int i_index;
1436         msg_Dbg( p_demux,
1437                     "track[Id 0x%x] using Sync Sample Box (stss)",
1438                     p_track->i_track_ID );
1439         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1440         {
1441             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1442             {
1443                 if( i_index > 0 )
1444                 {
1445                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1446                             i_sample,
1447                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1448                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1449                     /* new i_sample is less than old so i_chunk can only decreased */
1450                     while( i_chunk > 0 &&
1451                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1452                     {
1453                         i_chunk--;
1454                     }
1455                 }
1456                 else
1457                 {
1458                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1459                             i_sample,
1460                             p_stss->data.p_stss->i_sample_number[i_index] );
1461                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1462                     /* new i_sample is more than old so i_chunk can only increased */
1463                     while( i_chunk < p_track->i_chunk_count - 1 &&
1464                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1465                              p_track->chunk[i_chunk].i_sample_count )
1466                     {
1467                         i_chunk++;
1468                     }
1469                 }
1470                 break;
1471             }
1472         }
1473     }
1474     else
1475     {
1476         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
1477                  "Sample Box (stss)", p_track->i_track_ID );
1478     }
1479
1480     *pi_chunk  = i_chunk;
1481     *pi_sample = i_sample;
1482
1483     return VLC_SUCCESS;
1484 }
1485
1486 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
1487                                  unsigned int i_chunk, unsigned int i_sample )
1488 {
1489     vlc_bool_t b_reselect = VLC_FALSE;
1490
1491     /* now see if actual es is ok */
1492     if( p_track->i_chunk < 0 ||
1493         p_track->i_chunk >= p_track->i_chunk_count - 1 ||
1494         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1495             p_track->chunk[i_chunk].i_sample_description_index )
1496     {
1497         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
1498                   p_track->i_track_ID );
1499
1500         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1501                         p_track->p_es, &b_reselect );
1502
1503         es_out_Del( p_demux->out, p_track->p_es );
1504
1505         p_track->p_es = NULL;
1506
1507         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
1508         {
1509             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1510                      p_track->i_track_ID );
1511
1512             p_track->b_ok       = VLC_FALSE;
1513             p_track->b_selected = VLC_FALSE;
1514             return VLC_EGENERIC;
1515         }
1516     }
1517
1518     /* select again the new decoder */
1519     if( b_reselect )
1520     {
1521         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
1522     }
1523
1524     p_track->i_chunk    = i_chunk;
1525     p_track->i_sample   = i_sample;
1526
1527     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1528 }
1529
1530 /****************************************************************************
1531  * MP4_TrackCreate:
1532  ****************************************************************************
1533  * Parse track information and create all needed data to run a track
1534  * If it succeed b_ok is set to 1 else to 0
1535  ****************************************************************************/
1536 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
1537                              MP4_Box_t *p_box_trak )
1538 {
1539     demux_sys_t *p_sys = p_demux->p_sys;
1540
1541     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1542     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1543     MP4_Box_t *p_elst;
1544
1545     MP4_Box_t *p_mdhd;
1546     MP4_Box_t *p_hdlr;
1547
1548     MP4_Box_t *p_vmhd;
1549     MP4_Box_t *p_smhd;
1550
1551     MP4_Box_t *p_drms;
1552
1553     unsigned int i;
1554     char language[4];
1555
1556     /* hint track unsuported */
1557
1558     /* set default value (-> track unusable) */
1559     p_track->b_ok       = VLC_FALSE;
1560     p_track->b_enable   = VLC_FALSE;
1561     p_track->b_selected = VLC_FALSE;
1562
1563     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1564
1565     if( !p_tkhd )
1566     {
1567         return;
1568     }
1569
1570     /* do we launch this track by default ? */
1571     p_track->b_enable =
1572         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1573
1574     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1575     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1576     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1577
1578     if( p_tref )
1579     {
1580 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
1581     }
1582
1583     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1584     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1585
1586     if( ( !p_mdhd )||( !p_hdlr ) )
1587     {
1588         return;
1589     }
1590
1591     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1592
1593     for( i = 0; i < 3; i++ )
1594     {
1595         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1596     }
1597     language[3] = '\0';
1598
1599     switch( p_hdlr->data.p_hdlr->i_handler_type )
1600     {
1601         case( FOURCC_soun ):
1602             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1603             {
1604                 return;
1605             }
1606             p_track->fmt.i_cat = AUDIO_ES;
1607             break;
1608
1609         case( FOURCC_vide ):
1610             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1611             {
1612                 return;
1613             }
1614             p_track->fmt.i_cat = VIDEO_ES;
1615             break;
1616
1617         case( FOURCC_text ):
1618         case( FOURCC_subp ):
1619             p_track->fmt.i_cat = SPU_ES;
1620             break;
1621
1622         default:
1623             return;
1624     }
1625
1626     p_track->i_elst = 0;
1627     p_track->i_elst_time = 0;
1628     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1629     {
1630         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
1631         int i;
1632
1633         msg_Warn( p_demux, "elst box found" );
1634         for( i = 0; i < elst->i_entry_count; i++ )
1635         {
1636             msg_Dbg( p_demux, "   - [%d] duration="I64Fd"ms media time="I64Fd"ms) rate=%d.%d",
1637                      i,
1638                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
1639                      elst->i_media_time[i] >= 0 ?
1640                         elst->i_media_time[i] * 1000 / p_track->i_timescale : -1,
1641                      elst->i_media_rate_integer[i],
1642                      elst->i_media_rate_fraction[i] );
1643         }
1644     }
1645
1646
1647 /*  TODO
1648     add support for:
1649     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1650 */
1651     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1652         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1653     {
1654         return;
1655     }
1656
1657     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
1658     p_track->b_drms = p_drms != NULL;
1659     p_track->p_drms = p_track->b_drms ?
1660         p_drms->data.p_sample_soun->p_drms : NULL;
1661
1662     /* Set language */
1663     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1664     {
1665         p_track->fmt.psz_language = strdup( language );
1666     }
1667
1668     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1669     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1670     {
1671         MP4_Box_t *p_sample;
1672
1673         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1674         if( p_sample && p_sample->data.p_sample_soun)
1675         {
1676             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1677             if( p_soun->i_qt_version == 0 &&
1678                 p_track->i_timescale != p_soun->i_sampleratehi )
1679             {
1680                 msg_Warn( p_demux,
1681                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1682                           "qt_version == 0\n"
1683                           "Making both equal. (report any problem)",
1684                           p_track->i_timescale, p_soun->i_sampleratehi );
1685
1686                 if( p_soun->i_sampleratehi )
1687                     p_track->i_timescale = p_soun->i_sampleratehi;
1688                 else
1689                     p_soun->i_sampleratehi = p_track->i_timescale;
1690             }
1691         }
1692     }
1693
1694     /* Create chunk index table and sample index table */
1695     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
1696         TrackCreateSamplesIndex( p_demux, p_track ) )
1697     {
1698         return; /* cannot create chunks index */
1699     }
1700
1701     p_track->i_chunk  = 0;
1702     p_track->i_sample = 0;
1703
1704     /* now create es */
1705     if( TrackCreateES( p_demux,
1706                        p_track, p_track->i_chunk,
1707                        &p_track->p_es ) )
1708     {
1709         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1710                  p_track->i_track_ID );
1711         return;
1712     }
1713
1714 #if 0
1715     {
1716         int i;
1717         for( i = 0; i < p_track->i_chunk_count; i++ )
1718         {
1719             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
1720                      i, p_track->chunk[i].i_sample_count,
1721                      p_track->chunk[i].i_first_dts );
1722
1723         }
1724     }
1725 #endif
1726     p_track->b_ok = VLC_TRUE;
1727 }
1728
1729 /****************************************************************************
1730  * MP4_TrackDestroy:
1731  ****************************************************************************
1732  * Destroy a track created by MP4_TrackCreate.
1733  ****************************************************************************/
1734 static void MP4_TrackDestroy( demux_t *p_demux, mp4_track_t *p_track )
1735 {
1736     unsigned int i_chunk;
1737
1738     p_track->b_ok = VLC_FALSE;
1739     p_track->b_enable   = VLC_FALSE;
1740     p_track->b_selected = VLC_FALSE;
1741
1742     es_format_Clean( &p_track->fmt );
1743
1744     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1745     {
1746         if( p_track->chunk )
1747         {
1748            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1749            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1750         }
1751     }
1752     FREE( p_track->chunk );
1753
1754     if( !p_track->i_sample_size )
1755     {
1756         FREE( p_track->p_sample_size );
1757     }
1758 }
1759
1760 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
1761                             mtime_t i_start )
1762 {
1763     if( !p_track->b_ok )
1764     {
1765         return VLC_EGENERIC;
1766     }
1767
1768     if( p_track->b_selected )
1769     {
1770         msg_Warn( p_demux, "track[Id 0x%x] already selected",
1771                   p_track->i_track_ID );
1772         return VLC_SUCCESS;
1773     }
1774
1775     return MP4_TrackSeek( p_demux, p_track, i_start );
1776 }
1777
1778 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
1779 {
1780     if( !p_track->b_ok )
1781     {
1782         return;
1783     }
1784
1785     if( !p_track->b_selected )
1786     {
1787         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
1788                   p_track->i_track_ID );
1789         return;
1790     }
1791     if( p_track->p_es )
1792     {
1793         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
1794                         p_track->p_es, VLC_FALSE );
1795     }
1796
1797     p_track->b_selected = VLC_FALSE;
1798 }
1799
1800 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
1801                           mtime_t i_start )
1802 {
1803     uint32_t i_chunk;
1804     uint32_t i_sample;
1805
1806     if( !p_track->b_ok )
1807     {
1808         return( VLC_EGENERIC );
1809     }
1810
1811     p_track->b_selected = VLC_FALSE;
1812
1813     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
1814                                 &i_chunk, &i_sample ) )
1815     {
1816         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
1817                   p_track->i_track_ID );
1818         return( VLC_EGENERIC );
1819     }
1820
1821     p_track->b_selected = VLC_TRUE;
1822
1823     if( TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) ==
1824         VLC_SUCCESS )
1825     {
1826         p_track->b_selected = VLC_TRUE;
1827     }
1828     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
1829 }
1830
1831
1832 /*
1833  * 3 types: for audio
1834  * 
1835  */
1836 #define QT_V0_MAX_SAMPLES    1500
1837 static int MP4_TrackSampleSize( mp4_track_t *p_track )
1838 {
1839     int i_size;
1840     MP4_Box_data_sample_soun_t *p_soun;
1841
1842     if( p_track->i_sample_size == 0 )
1843     {
1844         /* most simple case */
1845         return( p_track->p_sample_size[p_track->i_sample] );
1846     }
1847     if( p_track->fmt.i_cat != AUDIO_ES )
1848     {
1849         return( p_track->i_sample_size );
1850     }
1851
1852     if( p_track->i_sample_size != 1 )
1853     {
1854         //msg_Warn( p_demux, "SampleSize != 1" );
1855         return( p_track->i_sample_size );
1856     }
1857
1858     p_soun = p_track->p_sample->data.p_sample_soun;
1859
1860     if( p_soun->i_qt_version == 1 )
1861     {
1862         i_size = p_track->chunk[p_track->i_chunk].i_sample_count / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
1863     }
1864     else
1865     {
1866         /* FIXME */
1867         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
1868                 ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first );
1869         if( i_samples > QT_V0_MAX_SAMPLES )
1870         {
1871             i_samples = QT_V0_MAX_SAMPLES;
1872         }
1873         i_size = i_samples * p_soun->i_channelcount * p_soun->i_samplesize / 8;
1874     }
1875
1876     //fprintf( stderr, "size=%d\n", i_size );
1877     return( i_size );
1878 }
1879
1880
1881 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
1882 {
1883     unsigned int i_sample;
1884     uint64_t i_pos;
1885
1886
1887     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
1888
1889     if( p_track->i_sample_size )
1890     {
1891         MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
1892
1893         if( p_soun->i_qt_version == 0 )
1894         {
1895             i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) *
1896                         p_soun->i_channelcount * p_soun->i_samplesize / 8;
1897         }
1898         else
1899         {
1900             /* we read chunk by chunk */
1901             i_pos += 0;
1902         }
1903     }
1904     else
1905     {
1906         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
1907                 i_sample < p_track->i_sample; i_sample++ )
1908         {
1909             i_pos += p_track->p_sample_size[i_sample];
1910         }
1911
1912     }
1913     return( i_pos );
1914 }
1915
1916 static int  MP4_TrackNextSample( demux_t     *p_demux,
1917                                  mp4_track_t   *p_track )
1918 {
1919
1920     if( p_track->fmt.i_cat == AUDIO_ES &&
1921         p_track->i_sample_size != 0 )
1922     {
1923         MP4_Box_data_sample_soun_t *p_soun;
1924
1925         p_soun = p_track->p_sample->data.p_sample_soun;
1926
1927         if( p_soun->i_qt_version == 1 )
1928         {
1929             /* chunk by chunk */
1930             p_track->i_sample =
1931                 p_track->chunk[p_track->i_chunk].i_sample_first +
1932                 p_track->chunk[p_track->i_chunk].i_sample_count;
1933         }
1934         else
1935         {
1936             /* FIXME */
1937             p_track->i_sample += QT_V0_MAX_SAMPLES;
1938             if( p_track->i_sample > p_track->chunk[p_track->i_chunk].i_sample_first + p_track->chunk[p_track->i_chunk].i_sample_count )
1939             {
1940                 p_track->i_sample =
1941                     p_track->chunk[p_track->i_chunk].i_sample_first +
1942                     p_track->chunk[p_track->i_chunk].i_sample_count;
1943             }
1944         }
1945     }
1946     else
1947     {
1948         p_track->i_sample++;
1949     }
1950
1951     if( p_track->i_sample >= p_track->i_sample_count )
1952     {
1953         /* we have reach end of the track so free decoder stuff */
1954         msg_Warn( p_demux, "track[0x%x] will be disabled", p_track->i_track_ID );
1955         MP4_TrackUnselect( p_demux, p_track );
1956         return VLC_EGENERIC;
1957     }
1958
1959     /* Have we changed chunk ? */
1960     if( p_track->i_sample >=
1961             p_track->chunk[p_track->i_chunk].i_sample_first +
1962             p_track->chunk[p_track->i_chunk].i_sample_count )
1963     {
1964         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
1965                                   p_track->i_sample ) )
1966         {
1967             msg_Warn( p_demux, "track[0x%x] will be disabled "
1968                       "(cannot restart decoder)", p_track->i_track_ID );
1969             MP4_TrackUnselect( p_demux, p_track );
1970             return VLC_EGENERIC;
1971         }
1972     }
1973
1974     /* Have we changed elst */
1975     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1976     {
1977         demux_sys_t *p_sys = p_demux->p_sys;
1978         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1979         int64_t i_mvt = MP4_TrackGetPTS( p_demux, p_track ) *
1980                         p_sys->i_timescale / (int64_t)1000000;
1981
1982         if( p_track->i_elst < elst->i_entry_count &&
1983             i_mvt >= p_track->i_elst_time +
1984                      elst->i_segment_duration[p_track->i_elst] )
1985         {
1986             MP4_TrackSetELST( p_demux, p_track,
1987                               MP4_TrackGetPTS( p_demux, p_track ) );
1988         }
1989     }
1990
1991     return VLC_SUCCESS;
1992 }
1993
1994 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
1995                               int64_t i_time )
1996 {
1997     demux_sys_t *p_sys = p_demux->p_sys;
1998     int         i_elst_last = tk->i_elst;
1999
2000     /* handle elst (find the correct one) */
2001     tk->i_elst      = 0;
2002     tk->i_elst_time = 0;
2003     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2004     {
2005         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2006         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2007
2008         for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2009         {
2010             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2011
2012             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2013             {
2014                 break;
2015             }
2016             tk->i_elst_time += i_dur;
2017         }
2018
2019         if( tk->i_elst >= elst->i_entry_count )
2020         {
2021             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2022             tk->i_elst = elst->i_entry_count - 1;
2023             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2024         }
2025
2026         if( elst->i_media_time[tk->i_elst] < 0 )
2027         {
2028             /* track offset */
2029             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2030         }
2031     }
2032     if( i_elst_last != tk->i_elst )
2033     {
2034         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2035     }
2036 }