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