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