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