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