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