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