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