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