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