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