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