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