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