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