]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
* Added more annotations boxes
[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: /* Full name */
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: /* Creation Date */
771                     vlc_meta_Add( meta, VLC_META_DATE,
772                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
773                     break;
774                 case FOURCC_0xa9des: /* Description */
775                     vlc_meta_Add( meta, VLC_META_DESCRIPTION,
776                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
777                     break;
778                 case FOURCC_0xa9gen: /* Genre */
779                     vlc_meta_Add( meta, VLC_META_GENRE,
780                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
781                     break;
782
783                 case FOURCC_0xa9swr:
784                 case FOURCC_0xa9inf: /* Information */
785                 case FOURCC_0xa9alb: /* Album */
786                 case FOURCC_0xa9dir: /* Director */
787                 case FOURCC_0xa9dis: /* Disclaimer */
788                 case FOURCC_0xa9enc: /* Encoded By */
789                 case FOURCC_0xa9trk: /* Track */
790                 case FOURCC_0xa9cmt: /* Commment */
791                 case FOURCC_0xa9url: /* URL */
792                 case FOURCC_0xa9req: /* Requirements */
793                 case FOURCC_0xa9fmt: /* Original Format */
794                 case FOURCC_0xa9dsa: /* Display Source As */
795                 case FOURCC_0xa9hst: /* Host Computer */
796                 case FOURCC_0xa9prd: /* Producer */
797                 case FOURCC_0xa9prf: /* Performers */
798                 case FOURCC_0xa9ope: /* Original Performer */
799                 case FOURCC_0xa9src: /* Providers Source Content */
800                 case FOURCC_0xa9wrt: /* Writer */
801                 case FOURCC_0xa9com: /* Composer */
802                 case FOURCC_WLOC:    /* Window Location */
803                     /* TODO one day, but they aren't really meaningfull */
804                     break;
805
806                 default:
807                     break;
808                 }
809             }
810             return VLC_SUCCESS;
811         }
812
813         case DEMUX_GET_TITLE_INFO:
814         case DEMUX_SET_NEXT_DEMUX_TIME:
815         case DEMUX_SET_GROUP:
816             return VLC_EGENERIC;
817
818         default:
819             msg_Warn( p_demux, "control query unimplemented !!!" );
820             return VLC_EGENERIC;
821     }
822 }
823
824 /*****************************************************************************
825  * Close: frees unused data
826  *****************************************************************************/
827 static void Close ( vlc_object_t * p_this )
828 {
829     unsigned int i_track;
830     demux_t *  p_demux = (demux_t *)p_this;
831     demux_sys_t *p_sys = p_demux->p_sys;
832
833     msg_Dbg( p_demux, "freeing all memory" );
834
835     MP4_BoxFree( p_demux->s, p_sys->p_root );
836     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
837     {
838         MP4_TrackDestroy( p_demux, &p_sys->track[i_track] );
839     }
840     FREE( p_sys->track );
841
842     free( p_sys );
843 }
844
845
846
847 /****************************************************************************
848  * Local functions, specific to vlc
849  ****************************************************************************/
850
851 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
852 static int TrackCreateChunksIndex( demux_t *p_demux,
853                                    mp4_track_t *p_demux_track )
854 {
855     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
856     MP4_Box_t *p_stsc;
857
858     unsigned int i_chunk;
859     unsigned int i_index, i_last;
860
861     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
862           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
863         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
864     {
865         return( VLC_EGENERIC );
866     }
867
868     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
869     if( !p_demux_track->i_chunk_count )
870     {
871         msg_Warn( p_demux, "no chunk defined" );
872         return( VLC_EGENERIC );
873     }
874     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
875                                    sizeof( mp4_chunk_t ) );
876
877     /* first we read chunk offset */
878     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
879     {
880         p_demux_track->chunk[i_chunk].i_offset =
881                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
882     }
883
884     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
885         to be used for the sample XXX begin to 1
886         We construct it begining at the end */
887     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
888     i_index = p_stsc->data.p_stsc->i_entry_count;
889     if( !i_index )
890     {
891         msg_Warn( p_demux, "cannot read chunk table or table empty" );
892         return( VLC_EGENERIC );
893     }
894
895     while( i_index )
896     {
897         i_index--;
898         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
899                 i_chunk < i_last; i_chunk++ )
900         {
901             p_demux_track->chunk[i_chunk].i_sample_description_index =
902                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
903             p_demux_track->chunk[i_chunk].i_sample_count =
904                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
905         }
906         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
907     }
908
909     p_demux_track->chunk[0].i_sample_first = 0;
910     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
911     {
912         p_demux_track->chunk[i_chunk].i_sample_first =
913             p_demux_track->chunk[i_chunk-1].i_sample_first +
914                 p_demux_track->chunk[i_chunk-1].i_sample_count;
915     }
916
917     msg_Dbg( p_demux,
918              "track[Id 0x%x] read %d chunk",
919              p_demux_track->i_track_ID,
920              p_demux_track->i_chunk_count );
921
922     return( VLC_SUCCESS );
923 }
924 static int TrackCreateSamplesIndex( demux_t *p_demux,
925                                     mp4_track_t *p_demux_track )
926 {
927     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
928                           ctts make same mapping but for composition time,
929                           not yet used and probably not usefull */
930     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
931                           that uses a compressed form FIXME make them in libmp4
932                           as a unique type */
933     /* TODO use also stss and stsh table for seeking */
934     /* FIXME use edit table */
935     int64_t i_sample;
936     int64_t i_chunk;
937
938     int64_t i_index;
939     int64_t i_index_sample_used;
940
941     int64_t i_last_dts;
942
943     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
944     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
945
946     if( ( !p_stts )||( !p_stsz ) )
947     {
948         msg_Warn( p_demux, "cannot read sample table" );
949         return( VLC_EGENERIC );
950     }
951
952     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
953
954
955     /* for sample size, there are 2 case */
956     if( p_stsz->data.p_stsz->i_sample_size )
957     {
958         /* 1: all sample have the same size, so no need to construct a table */
959         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
960         p_demux_track->p_sample_size = NULL;
961     }
962     else
963     {
964         /* 2: each sample can have a different size */
965         p_demux_track->i_sample_size = 0;
966         p_demux_track->p_sample_size =
967             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
968
969         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
970         {
971             p_demux_track->p_sample_size[i_sample] =
972                     p_stsz->data.p_stsz->i_entry_size[i_sample];
973         }
974     }
975     /* we have extract all information from stsz,
976         now use stts */
977
978     /* if we don't want to waste too much memory, we can't expand
979        the box !, so each chunk will contain an "extract" of this table
980        for fast research */
981
982     i_last_dts = 0;
983     i_index = 0; i_index_sample_used =0;
984
985     /* create and init last data for each chunk */
986     for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
987     {
988
989         int64_t i_entry, i_sample_count, i;
990         /* save last dts */
991         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
992     /* count how many entries needed for this chunk
993        for p_sample_delta_dts and p_sample_count_dts */
994
995         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
996
997         i_entry = 0;
998         while( i_sample_count > 0 )
999         {
1000             i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
1001             if( i_entry == 0 )
1002             {
1003                 i_sample_count += i_index_sample_used; /* don't count already used sample
1004                                                    int this entry */
1005             }
1006             i_entry++;
1007         }
1008
1009         /* allocate them */
1010         p_demux_track->chunk[i_chunk].p_sample_count_dts =
1011             calloc( i_entry, sizeof( uint32_t ) );
1012         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
1013             calloc( i_entry, sizeof( uint32_t ) );
1014
1015         /* now copy */
1016         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
1017         for( i = 0; i < i_entry; i++ )
1018         {
1019             int64_t i_used;
1020             int64_t i_rest;
1021
1022             i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;
1023
1024             i_used = __MIN( i_rest, i_sample_count );
1025
1026             i_index_sample_used += i_used;
1027             i_sample_count -= i_used;
1028
1029             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
1030
1031             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
1032                         p_stts->data.p_stts->i_sample_delta[i_index];
1033
1034             i_last_dts += i_used *
1035                     p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
1036
1037             if( i_index_sample_used >=
1038                              p_stts->data.p_stts->i_sample_count[i_index] )
1039             {
1040
1041                 i_index++;
1042                 i_index_sample_used = 0;
1043             }
1044         }
1045
1046     }
1047
1048     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:"I64Fd"s",
1049              p_demux_track->i_track_ID,
1050              p_demux_track->i_sample_count,
1051              i_last_dts / p_demux_track->i_timescale );
1052
1053     return( VLC_SUCCESS );
1054 }
1055
1056 /*
1057  * TrackCreateES:
1058  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1059  */
1060 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1061                           unsigned int i_chunk, es_out_id_t **pp_es )
1062 {
1063     MP4_Box_t   *p_sample;
1064     MP4_Box_t   *p_esds;
1065
1066     *pp_es = NULL;
1067
1068     if( !p_track->chunk[i_chunk].i_sample_description_index )
1069     {
1070         msg_Warn( p_demux,
1071                   "invalid SampleEntry index (track[Id 0x%x])",
1072                   p_track->i_track_ID );
1073         return VLC_EGENERIC;
1074     }
1075
1076     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1077                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
1078
1079     if( !p_sample || ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1080     {
1081         msg_Warn( p_demux,
1082                   "cannot find SampleEntry (track[Id 0x%x])",
1083                   p_track->i_track_ID );
1084         return( VLC_EGENERIC );
1085     }
1086
1087     p_track->p_sample = p_sample;
1088
1089     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size == 1 )
1090     {
1091         MP4_Box_data_sample_soun_t *p_soun;
1092
1093         p_soun = p_sample->data.p_sample_soun;
1094
1095         if( p_soun->i_qt_version == 0 )
1096         {
1097             switch( p_sample->i_type )
1098             {
1099                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1100                     p_soun->i_qt_version = 1;
1101                     p_soun->i_sample_per_packet = 64;
1102                     p_soun->i_bytes_per_packet  = 34;
1103                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1104                     p_soun->i_bytes_per_sample  = 2;
1105                     break;
1106                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1107                     p_soun->i_qt_version = 1;
1108                     p_soun->i_sample_per_packet = 6;
1109                     p_soun->i_bytes_per_packet  = 2;
1110                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1111                     p_soun->i_bytes_per_sample  = 2;
1112                     break;
1113                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1114                     p_soun->i_qt_version = 1;
1115                     p_soun->i_sample_per_packet = 12;
1116                     p_soun->i_bytes_per_packet  = 2;
1117                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1118                     p_soun->i_bytes_per_sample  = 2;
1119                     break;
1120                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1121                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1122                     p_soun->i_samplesize = 8;
1123                     break;
1124                 default:
1125                     break;
1126             }
1127
1128         }
1129         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1130         {
1131             p_soun->i_qt_version = 0;
1132         }
1133     }
1134
1135
1136     /* It's a little ugly but .. there are special cases */
1137     switch( p_sample->i_type )
1138     {
1139         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1140         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1141             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1142             break;
1143         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1144             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1145             break;
1146         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1147             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1148             break;
1149
1150         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1151             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1152             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1153             /* FIXME UTF-8 doesn't work here ? */
1154             /* p_track->fmt.subs.psz_encoding = strdup( "UTF-8" ); */
1155             break;
1156
1157         default:
1158             p_track->fmt.i_codec = p_sample->i_type;
1159             break;
1160     }
1161
1162     /* now see if esds is present and if so create a data packet
1163         with decoder_specific_info  */
1164 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1165     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1166           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1167         ( p_esds->data.p_esds )&&
1168         ( p_decconfig ) )
1169     {
1170         /* First update information based on i_objectTypeIndication */
1171         switch( p_decconfig->i_objectTypeIndication )
1172         {
1173             case( 0x20 ): /* MPEG4 VIDEO */
1174                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1175                 break;
1176             case( 0x40):
1177                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1178                 break;
1179             case( 0x60):
1180             case( 0x61):
1181             case( 0x62):
1182             case( 0x63):
1183             case( 0x64):
1184             case( 0x65): /* MPEG2 video */
1185                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1186                 break;
1187             /* Theses are MPEG2-AAC */
1188             case( 0x66): /* main profile */
1189             case( 0x67): /* Low complexity profile */
1190             case( 0x68): /* Scaleable Sampling rate profile */
1191                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1192                 break;
1193             /* true MPEG 2 audio */
1194             case( 0x69):
1195                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1196                 break;
1197             case( 0x6a): /* MPEG1 video */
1198                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1199                 break;
1200             case( 0x6b): /* MPEG1 audio */
1201                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1202                 break;
1203             case( 0x6c ): /* jpeg */
1204                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1205                 break;
1206
1207             /* Private ID */
1208             case( 0xe0 ): /* NeroDigital: dvd subs */
1209                 if( p_track->fmt.i_cat == SPU_ES )
1210                 {
1211                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1212                     break;
1213                 }
1214             /* Fallback */
1215             default:
1216                 /* Unknown entry, but don't touch i_fourcc */
1217                 msg_Warn( p_demux,
1218                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1219                           p_decconfig->i_objectTypeIndication,
1220                           p_track->i_track_ID );
1221                 break;
1222         }
1223         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
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, p_decconfig->p_decoder_specific_info,
1228                     p_track->fmt.i_extra );
1229         }
1230     }
1231     else
1232     {
1233         switch( p_sample->i_type )
1234         {
1235             /* qt decoder, send the complete chunk */
1236             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1237             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1238             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1239             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1240             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1241                 p_track->fmt.i_extra =
1242                     p_sample->data.p_sample_vide->i_qt_image_description;
1243                 if( p_track->fmt.i_extra > 0 )
1244                 {
1245                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1246                     memcpy( p_track->fmt.p_extra,
1247                             p_sample->data.p_sample_vide->p_qt_image_description,
1248                             p_track->fmt.i_extra);
1249                 }
1250                 break;
1251             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1252             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1253             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1254             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1255                 p_track->fmt.i_extra =
1256                     p_sample->data.p_sample_soun->i_qt_description;
1257                 if( p_track->fmt.i_extra > 0 )
1258                 {
1259                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1260                     memcpy( p_track->fmt.p_extra,
1261                             p_sample->data.p_sample_soun->p_qt_description,
1262                             p_track->fmt.i_extra);
1263                 }
1264                 break;
1265
1266             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1267             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1268             {
1269                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1270
1271                 if( p_avcC )
1272                 {
1273                     /* Hack: use a packetizer to reecampsulate data in anexe B format */
1274                     msg_Dbg( p_demux, "avcC: size=%d", p_avcC->data.p_avcC->i_avcC );
1275                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1276                     p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1277                     memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC, p_track->fmt.i_extra );
1278                     p_track->fmt.b_packetized = VLC_FALSE;
1279                 }
1280                 else
1281                 {
1282                     msg_Err( p_demux, "missing avcC" );
1283                 }
1284                 break;
1285             }
1286
1287             default:
1288                 break;
1289         }
1290     }
1291
1292 #undef p_decconfig
1293
1294     /* some last initialisation */
1295     switch( p_track->fmt.i_cat )
1296     {
1297     case( VIDEO_ES ):
1298         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1299         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1300
1301         /* fall on display size */
1302         if( p_track->fmt.video.i_width <= 0 )
1303             p_track->fmt.video.i_width = p_track->i_width;
1304         if( p_track->fmt.video.i_height <= 0 )
1305             p_track->fmt.video.i_height = p_track->i_height;
1306
1307         /* Find out apect ratio from display size */
1308         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1309             /* Work-around buggy muxed files */
1310             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1311             p_track->fmt.video.i_aspect =
1312                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1313
1314         break;
1315
1316     case( AUDIO_ES ):
1317         p_track->fmt.audio.i_channels =
1318             p_sample->data.p_sample_soun->i_channelcount;
1319         p_track->fmt.audio.i_rate =
1320             p_sample->data.p_sample_soun->i_sampleratehi;
1321         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1322             p_sample->data.p_sample_soun->i_sampleratehi *
1323                 p_sample->data.p_sample_soun->i_samplesize;
1324         p_track->fmt.audio.i_bitspersample =
1325             p_sample->data.p_sample_soun->i_samplesize;
1326         break;
1327
1328     default:
1329         break;
1330     }
1331
1332     *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1333
1334     return VLC_SUCCESS;
1335 }
1336
1337 /* given a time it return sample/chunk
1338  * it also update elst field of the track
1339  */
1340 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1341                                    int64_t i_start, uint32_t *pi_chunk,
1342                                    uint32_t *pi_sample )
1343 {
1344     demux_sys_t *p_sys = p_demux->p_sys;
1345     MP4_Box_t   *p_stss;
1346     uint64_t     i_dts;
1347     unsigned int i_sample;
1348     unsigned int i_chunk;
1349     int          i_index;
1350
1351     /* FIXME see if it's needed to check p_track->i_chunk_count */
1352     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1353     {
1354         return( VLC_EGENERIC );
1355     }
1356
1357     /* handle elst (find the correct one) */
1358     MP4_TrackSetELST( p_demux, p_track, i_start );
1359     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1360     {
1361         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1362         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1363
1364         /* now calculate i_start for this elst */
1365         /* offset */
1366         i_start -= p_track->i_elst_time * I64C(1000000) / p_sys->i_timescale;
1367         if( i_start < 0 )
1368         {
1369             *pi_chunk = 0;
1370             *pi_sample= 0;
1371
1372             return VLC_SUCCESS;
1373         }
1374         /* to track time scale */
1375         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1376         /* add elst offset */
1377         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1378              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1379             elst->i_media_time[p_track->i_elst] > 0 )
1380         {
1381             i_start += elst->i_media_time[p_track->i_elst];
1382         }
1383
1384         msg_Dbg( p_demux, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd
1385                  "ms (track)", p_track->i_elst,
1386                  i_mvt * 1000 / p_sys->i_timescale,
1387                  i_start * 1000 / p_track->i_timescale );
1388     }
1389     else
1390     {
1391         /* convert absolute time to in timescale unit */
1392         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1393     }
1394
1395     /* we start from sample 0/chunk 0, hope it won't take too much time */
1396     /* *** find good chunk *** */
1397     for( i_chunk = 0; ; i_chunk++ )
1398     {
1399         if( i_chunk + 1 >= p_track->i_chunk_count )
1400         {
1401             /* at the end and can't check if i_start in this chunk,
1402                it will be check while searching i_sample */
1403             i_chunk = p_track->i_chunk_count - 1;
1404             break;
1405         }
1406
1407         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1408             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1409         {
1410             break;
1411         }
1412     }
1413
1414     /* *** find sample in the chunk *** */
1415     i_sample = p_track->chunk[i_chunk].i_sample_first;
1416     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1417     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1418     {
1419         if( i_dts +
1420             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1421             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1422         {
1423             i_dts    +=
1424                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1425                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1426
1427             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1428             i_index++;
1429         }
1430         else
1431         {
1432             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1433             {
1434                 break;
1435             }
1436             i_sample += ( i_start - i_dts ) /
1437                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1438             break;
1439         }
1440     }
1441
1442     if( i_sample >= p_track->i_sample_count )
1443     {
1444         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1445                   "(seeking too far) chunk=%d sample=%d",
1446                   p_track->i_track_ID, i_chunk, i_sample );
1447         return( VLC_EGENERIC );
1448     }
1449
1450
1451     /* *** Try to find nearest sync points *** */
1452     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1453     {
1454         unsigned int i_index;
1455         msg_Dbg( p_demux,
1456                     "track[Id 0x%x] using Sync Sample Box (stss)",
1457                     p_track->i_track_ID );
1458         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1459         {
1460             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1461             {
1462                 if( i_index > 0 )
1463                 {
1464                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1465                             i_sample,
1466                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1467                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1468                     /* new i_sample is less than old so i_chunk can only decreased */
1469                     while( i_chunk > 0 &&
1470                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1471                     {
1472                         i_chunk--;
1473                     }
1474                 }
1475                 else
1476                 {
1477                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1478                             i_sample,
1479                             p_stss->data.p_stss->i_sample_number[i_index] );
1480                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1481                     /* new i_sample is more than old so i_chunk can only increased */
1482                     while( i_chunk < p_track->i_chunk_count - 1 &&
1483                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1484                              p_track->chunk[i_chunk].i_sample_count )
1485                     {
1486                         i_chunk++;
1487                     }
1488                 }
1489                 break;
1490             }
1491         }
1492     }
1493     else
1494     {
1495         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
1496                  "Sample Box (stss)", p_track->i_track_ID );
1497     }
1498
1499     *pi_chunk  = i_chunk;
1500     *pi_sample = i_sample;
1501
1502     return VLC_SUCCESS;
1503 }
1504
1505 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
1506                                  unsigned int i_chunk, unsigned int i_sample )
1507 {
1508     vlc_bool_t b_reselect = VLC_FALSE;
1509
1510     /* now see if actual es is ok */
1511     if( p_track->i_chunk < 0 ||
1512         p_track->i_chunk >= p_track->i_chunk_count - 1 ||
1513         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1514             p_track->chunk[i_chunk].i_sample_description_index )
1515     {
1516         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
1517                   p_track->i_track_ID );
1518
1519         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1520                         p_track->p_es, &b_reselect );
1521
1522         es_out_Del( p_demux->out, p_track->p_es );
1523
1524         p_track->p_es = NULL;
1525
1526         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
1527         {
1528             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1529                      p_track->i_track_ID );
1530
1531             p_track->b_ok       = VLC_FALSE;
1532             p_track->b_selected = VLC_FALSE;
1533             return VLC_EGENERIC;
1534         }
1535     }
1536
1537     /* select again the new decoder */
1538     if( b_reselect )
1539     {
1540         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
1541     }
1542
1543     p_track->i_chunk    = i_chunk;
1544     p_track->i_sample   = i_sample;
1545
1546     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1547 }
1548
1549 /****************************************************************************
1550  * MP4_TrackCreate:
1551  ****************************************************************************
1552  * Parse track information and create all needed data to run a track
1553  * If it succeed b_ok is set to 1 else to 0
1554  ****************************************************************************/
1555 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
1556                              MP4_Box_t *p_box_trak )
1557 {
1558     demux_sys_t *p_sys = p_demux->p_sys;
1559
1560     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1561     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1562     MP4_Box_t *p_elst;
1563
1564     MP4_Box_t *p_mdhd;
1565     MP4_Box_t *p_udta;
1566     MP4_Box_t *p_hdlr;
1567
1568     MP4_Box_t *p_vmhd;
1569     MP4_Box_t *p_smhd;
1570
1571     MP4_Box_t *p_drms;
1572
1573     unsigned int i;
1574     char language[4];
1575
1576     /* hint track unsuported */
1577
1578     /* set default value (-> track unusable) */
1579     p_track->b_ok       = VLC_FALSE;
1580     p_track->b_enable   = VLC_FALSE;
1581     p_track->b_selected = VLC_FALSE;
1582
1583     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1584
1585     if( !p_tkhd )
1586     {
1587         return;
1588     }
1589
1590     /* do we launch this track by default ? */
1591     p_track->b_enable =
1592         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1593
1594     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1595     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1596     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1597
1598     if( p_tref )
1599     {
1600 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
1601     }
1602
1603     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1604     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1605
1606     if( ( !p_mdhd )||( !p_hdlr ) )
1607     {
1608         return;
1609     }
1610
1611     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1612
1613     for( i = 0; i < 3; i++ )
1614     {
1615         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1616     }
1617     language[3] = '\0';
1618
1619     switch( p_hdlr->data.p_hdlr->i_handler_type )
1620     {
1621         case( FOURCC_soun ):
1622             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1623             {
1624                 return;
1625             }
1626             p_track->fmt.i_cat = AUDIO_ES;
1627             break;
1628
1629         case( FOURCC_vide ):
1630             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1631             {
1632                 return;
1633             }
1634             p_track->fmt.i_cat = VIDEO_ES;
1635             break;
1636
1637         case( FOURCC_text ):
1638         case( FOURCC_subp ):
1639             p_track->fmt.i_cat = SPU_ES;
1640             break;
1641
1642         default:
1643             return;
1644     }
1645
1646     p_track->i_elst = 0;
1647     p_track->i_elst_time = 0;
1648     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1649     {
1650         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
1651         int i;
1652
1653         msg_Warn( p_demux, "elst box found" );
1654         for( i = 0; i < elst->i_entry_count; i++ )
1655         {
1656             msg_Dbg( p_demux, "   - [%d] duration="I64Fd"ms media time="I64Fd"ms) rate=%d.%d",
1657                      i,
1658                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
1659                      elst->i_media_time[i] >= 0 ?
1660                         elst->i_media_time[i] * 1000 / p_track->i_timescale : -1,
1661                      elst->i_media_rate_integer[i],
1662                      elst->i_media_rate_fraction[i] );
1663         }
1664     }
1665
1666
1667 /*  TODO
1668     add support for:
1669     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1670 */
1671     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1672         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1673     {
1674         return;
1675     }
1676
1677     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
1678     p_track->b_drms = p_drms != NULL;
1679     p_track->p_drms = p_track->b_drms ?
1680         p_drms->data.p_sample_soun->p_drms : NULL;
1681
1682     /* Set language */
1683     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1684     {
1685         p_track->fmt.psz_language = strdup( language );
1686     }
1687
1688     p_udta = MP4_BoxGet( p_box_trak, "udta" );
1689     if( p_udta )
1690     {
1691         MP4_Box_t *p_0xa9xxx;
1692         for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1693                  p_0xa9xxx = p_0xa9xxx->p_next )
1694         {
1695             switch( p_0xa9xxx->i_type )
1696             {
1697                 case FOURCC_0xa9nam:
1698                     p_track->fmt.psz_description = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text );
1699                     break;
1700             }
1701         }
1702     }
1703
1704     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1705     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1706     {
1707         MP4_Box_t *p_sample;
1708
1709         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1710         if( p_sample && p_sample->data.p_sample_soun)
1711         {
1712             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1713             if( p_soun->i_qt_version == 0 &&
1714                 p_track->i_timescale != p_soun->i_sampleratehi )
1715             {
1716                 msg_Warn( p_demux,
1717                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1718                           "qt_version == 0\n"
1719                           "Making both equal. (report any problem)",
1720                           p_track->i_timescale, p_soun->i_sampleratehi );
1721
1722                 if( p_soun->i_sampleratehi )
1723                     p_track->i_timescale = p_soun->i_sampleratehi;
1724                 else
1725                     p_soun->i_sampleratehi = p_track->i_timescale;
1726             }
1727         }
1728     }
1729
1730     /* Create chunk index table and sample index table */
1731     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
1732         TrackCreateSamplesIndex( p_demux, p_track ) )
1733     {
1734         return; /* cannot create chunks index */
1735     }
1736
1737     p_track->i_chunk  = 0;
1738     p_track->i_sample = 0;
1739
1740     /* now create es */
1741     if( TrackCreateES( p_demux,
1742                        p_track, p_track->i_chunk,
1743                        &p_track->p_es ) )
1744     {
1745         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1746                  p_track->i_track_ID );
1747         return;
1748     }
1749
1750 #if 0
1751     {
1752         int i;
1753         for( i = 0; i < p_track->i_chunk_count; i++ )
1754         {
1755             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
1756                      i, p_track->chunk[i].i_sample_count,
1757                      p_track->chunk[i].i_first_dts );
1758
1759         }
1760     }
1761 #endif
1762     p_track->b_ok = VLC_TRUE;
1763 }
1764
1765 /****************************************************************************
1766  * MP4_TrackDestroy:
1767  ****************************************************************************
1768  * Destroy a track created by MP4_TrackCreate.
1769  ****************************************************************************/
1770 static void MP4_TrackDestroy( demux_t *p_demux, mp4_track_t *p_track )
1771 {
1772     unsigned int i_chunk;
1773
1774     p_track->b_ok = VLC_FALSE;
1775     p_track->b_enable   = VLC_FALSE;
1776     p_track->b_selected = VLC_FALSE;
1777
1778     es_format_Clean( &p_track->fmt );
1779
1780     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1781     {
1782         if( p_track->chunk )
1783         {
1784            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1785            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1786         }
1787     }
1788     FREE( p_track->chunk );
1789
1790     if( !p_track->i_sample_size )
1791     {
1792         FREE( p_track->p_sample_size );
1793     }
1794 }
1795
1796 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
1797                             mtime_t i_start )
1798 {
1799     if( !p_track->b_ok )
1800     {
1801         return VLC_EGENERIC;
1802     }
1803
1804     if( p_track->b_selected )
1805     {
1806         msg_Warn( p_demux, "track[Id 0x%x] already selected",
1807                   p_track->i_track_ID );
1808         return VLC_SUCCESS;
1809     }
1810
1811     return MP4_TrackSeek( p_demux, p_track, i_start );
1812 }
1813
1814 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
1815 {
1816     if( !p_track->b_ok )
1817     {
1818         return;
1819     }
1820
1821     if( !p_track->b_selected )
1822     {
1823         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
1824                   p_track->i_track_ID );
1825         return;
1826     }
1827     if( p_track->p_es )
1828     {
1829         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
1830                         p_track->p_es, VLC_FALSE );
1831     }
1832
1833     p_track->b_selected = VLC_FALSE;
1834 }
1835
1836 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
1837                           mtime_t i_start )
1838 {
1839     uint32_t i_chunk;
1840     uint32_t i_sample;
1841
1842     if( !p_track->b_ok )
1843     {
1844         return( VLC_EGENERIC );
1845     }
1846
1847     p_track->b_selected = VLC_FALSE;
1848
1849     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
1850                                 &i_chunk, &i_sample ) )
1851     {
1852         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
1853                   p_track->i_track_ID );
1854         return( VLC_EGENERIC );
1855     }
1856
1857     p_track->b_selected = VLC_TRUE;
1858
1859     if( TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) ==
1860         VLC_SUCCESS )
1861     {
1862         p_track->b_selected = VLC_TRUE;
1863     }
1864     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
1865 }
1866
1867
1868 /*
1869  * 3 types: for audio
1870  * 
1871  */
1872 #define QT_V0_MAX_SAMPLES    1500
1873 static int MP4_TrackSampleSize( mp4_track_t *p_track )
1874 {
1875     int i_size;
1876     MP4_Box_data_sample_soun_t *p_soun;
1877
1878     if( p_track->i_sample_size == 0 )
1879     {
1880         /* most simple case */
1881         return( p_track->p_sample_size[p_track->i_sample] );
1882     }
1883     if( p_track->fmt.i_cat != AUDIO_ES )
1884     {
1885         return( p_track->i_sample_size );
1886     }
1887
1888     if( p_track->i_sample_size != 1 )
1889     {
1890         //msg_Warn( p_demux, "SampleSize != 1" );
1891         return( p_track->i_sample_size );
1892     }
1893
1894     p_soun = p_track->p_sample->data.p_sample_soun;
1895
1896     if( p_soun->i_qt_version == 1 )
1897     {
1898         i_size = p_track->chunk[p_track->i_chunk].i_sample_count / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
1899     }
1900     else
1901     {
1902         /* FIXME */
1903         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
1904                 ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first );
1905         if( i_samples > QT_V0_MAX_SAMPLES )
1906         {
1907             i_samples = QT_V0_MAX_SAMPLES;
1908         }
1909         i_size = i_samples * p_soun->i_channelcount * p_soun->i_samplesize / 8;
1910     }
1911
1912     //fprintf( stderr, "size=%d\n", i_size );
1913     return( i_size );
1914 }
1915
1916
1917 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
1918 {
1919     unsigned int i_sample;
1920     uint64_t i_pos;
1921
1922
1923     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
1924
1925     if( p_track->i_sample_size )
1926     {
1927         MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
1928
1929         if( p_soun->i_qt_version == 0 )
1930         {
1931             i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) *
1932                         p_soun->i_channelcount * p_soun->i_samplesize / 8;
1933         }
1934         else
1935         {
1936             /* we read chunk by chunk */
1937             i_pos += 0;
1938         }
1939     }
1940     else
1941     {
1942         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
1943                 i_sample < p_track->i_sample; i_sample++ )
1944         {
1945             i_pos += p_track->p_sample_size[i_sample];
1946         }
1947
1948     }
1949     return( i_pos );
1950 }
1951
1952 static int  MP4_TrackNextSample( demux_t     *p_demux,
1953                                  mp4_track_t   *p_track )
1954 {
1955
1956     if( p_track->fmt.i_cat == AUDIO_ES &&
1957         p_track->i_sample_size != 0 )
1958     {
1959         MP4_Box_data_sample_soun_t *p_soun;
1960
1961         p_soun = p_track->p_sample->data.p_sample_soun;
1962
1963         if( p_soun->i_qt_version == 1 )
1964         {
1965             /* chunk by chunk */
1966             p_track->i_sample =
1967                 p_track->chunk[p_track->i_chunk].i_sample_first +
1968                 p_track->chunk[p_track->i_chunk].i_sample_count;
1969         }
1970         else
1971         {
1972             /* FIXME */
1973             p_track->i_sample += QT_V0_MAX_SAMPLES;
1974             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 )
1975             {
1976                 p_track->i_sample =
1977                     p_track->chunk[p_track->i_chunk].i_sample_first +
1978                     p_track->chunk[p_track->i_chunk].i_sample_count;
1979             }
1980         }
1981     }
1982     else
1983     {
1984         p_track->i_sample++;
1985     }
1986
1987     if( p_track->i_sample >= p_track->i_sample_count )
1988     {
1989         /* we have reach end of the track so free decoder stuff */
1990         msg_Warn( p_demux, "track[0x%x] will be disabled", p_track->i_track_ID );
1991         MP4_TrackUnselect( p_demux, p_track );
1992         return VLC_EGENERIC;
1993     }
1994
1995     /* Have we changed chunk ? */
1996     if( p_track->i_sample >=
1997             p_track->chunk[p_track->i_chunk].i_sample_first +
1998             p_track->chunk[p_track->i_chunk].i_sample_count )
1999     {
2000         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2001                                   p_track->i_sample ) )
2002         {
2003             msg_Warn( p_demux, "track[0x%x] will be disabled "
2004                       "(cannot restart decoder)", p_track->i_track_ID );
2005             MP4_TrackUnselect( p_demux, p_track );
2006             return VLC_EGENERIC;
2007         }
2008     }
2009
2010     /* Have we changed elst */
2011     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2012     {
2013         demux_sys_t *p_sys = p_demux->p_sys;
2014         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2015         int64_t i_mvt = MP4_TrackGetPTS( p_demux, p_track ) *
2016                         p_sys->i_timescale / (int64_t)1000000;
2017
2018         if( p_track->i_elst < elst->i_entry_count &&
2019             i_mvt >= p_track->i_elst_time +
2020                      elst->i_segment_duration[p_track->i_elst] )
2021         {
2022             MP4_TrackSetELST( p_demux, p_track,
2023                               MP4_TrackGetPTS( p_demux, p_track ) );
2024         }
2025     }
2026
2027     return VLC_SUCCESS;
2028 }
2029
2030 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2031                               int64_t i_time )
2032 {
2033     demux_sys_t *p_sys = p_demux->p_sys;
2034     int         i_elst_last = tk->i_elst;
2035
2036     /* handle elst (find the correct one) */
2037     tk->i_elst      = 0;
2038     tk->i_elst_time = 0;
2039     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2040     {
2041         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2042         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2043
2044         for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2045         {
2046             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2047
2048             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2049             {
2050                 break;
2051             }
2052             tk->i_elst_time += i_dur;
2053         }
2054
2055         if( tk->i_elst >= elst->i_entry_count )
2056         {
2057             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2058             tk->i_elst = elst->i_entry_count - 1;
2059             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2060         }
2061
2062         if( elst->i_media_time[tk->i_elst] < 0 )
2063         {
2064             /* track offset */
2065             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2066         }
2067     }
2068     if( i_elst_last != tk->i_elst )
2069     {
2070         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2071     }
2072 }