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