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