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