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