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