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