]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
atmo: remove invalid input state callback code
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * 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 #include <assert.h>
39
40 #include "libmp4.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   DemuxFrg( demux_t * );
64 static int   Seek    ( demux_t *, mtime_t );
65 static int   Control ( demux_t *, int, va_list );
66
67 struct demux_sys_t
68 {
69     MP4_Box_t    *p_root;      /* container for the whole file */
70
71     mtime_t      i_pcr;
72
73     uint64_t     i_time;         /* time position of the presentation
74                                   * in movie timescale */
75     uint64_t     i_timescale;    /* movie time scale */
76     uint64_t     i_duration;     /* movie duration */
77     unsigned int i_tracks;       /* number of tracks */
78     mp4_track_t  *track;         /* array of track */
79     float        f_fps;          /* number of frame per seconds */
80
81     bool         b_fragmented;   /* fMP4 */
82
83     /* */
84     MP4_Box_t    *p_tref_chap;
85
86     /* */
87     input_title_t *p_title;
88 };
89
90 /*****************************************************************************
91  * Declaration of local function
92  *****************************************************************************/
93 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_force_enable );
94 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
95 static void MP4_TrackDestroy(  mp4_track_t * );
96
97 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
98 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
99
100 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
101
102 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
103 static int      MP4_TrackSampleSize( mp4_track_t * );
104 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
105 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
106
107 static void     MP4_UpdateSeekpoint( demux_t * );
108 static const char *MP4_ConvertMacCode( uint16_t );
109
110 /* Return time in microsecond of a track */
111 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
112 {
113     demux_sys_t *p_sys = p_demux->p_sys;
114     mp4_chunk_t chunk;
115     if( p_sys->b_fragmented )
116         chunk = *p_track->cchunk;
117     else
118         chunk = p_track->chunk[p_track->i_chunk];
119
120     unsigned int i_index = 0;
121     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
122     int64_t i_dts = chunk.i_first_dts;
123
124     while( i_sample > 0 )
125     {
126         if( i_sample > chunk.p_sample_count_dts[i_index] )
127         {
128             i_dts += chunk.p_sample_count_dts[i_index] *
129                 chunk.p_sample_delta_dts[i_index];
130             i_sample -= chunk.p_sample_count_dts[i_index];
131             i_index++;
132         }
133         else
134         {
135             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
136             break;
137         }
138     }
139
140     /* now handle elst */
141     if( p_track->p_elst )
142     {
143         demux_sys_t         *p_sys = p_demux->p_sys;
144         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
145
146         /* convert to offset */
147         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
148               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
149             elst->i_media_time[p_track->i_elst] > 0 )
150         {
151             i_dts -= elst->i_media_time[p_track->i_elst];
152         }
153
154         /* add i_elst_time */
155         i_dts += p_track->i_elst_time * p_track->i_timescale /
156             p_sys->i_timescale;
157
158         if( i_dts < 0 ) i_dts = 0;
159     }
160
161     return INT64_C(1000000) * i_dts / p_track->i_timescale;
162 }
163
164 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
165 {
166     demux_sys_t *p_sys = p_demux->p_sys;
167     mp4_chunk_t *ck;
168     if( p_sys->b_fragmented )
169         ck = p_track->cchunk;
170     else
171         ck = &p_track->chunk[p_track->i_chunk];
172
173     unsigned int i_index = 0;
174     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
175
176     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
177         return -1;
178
179     for( i_index = 0;; i_index++ )
180     {
181         if( i_sample < ck->p_sample_count_pts[i_index] )
182             return ck->p_sample_offset_pts[i_index] * INT64_C(1000000) /
183                    (int64_t)p_track->i_timescale;
184
185         i_sample -= ck->p_sample_count_pts[i_index];
186     }
187 }
188
189 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
190 {
191     return INT64_C(1000000) * p_sys->i_time / p_sys->i_timescale;
192 }
193
194 static void LoadChapter( demux_t  *p_demux );
195
196 static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
197 {
198     demux_sys_t *p_sys = p_demux->p_sys;
199
200     if( b_smooth ) /* Smooth Streaming */
201     {
202         if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
203         {
204             goto LoadInitFragError;
205         }
206         else
207         {
208             MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
209             if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
210                 goto LoadInitFragError;
211             /* Get number of tracks */
212             p_sys->i_tracks = 0;
213             for( int i = 0; i < 3; i++ )
214             {
215                 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
216                 if( p_stra && p_stra->data.p_stra->i_track_ID )
217                     p_sys->i_tracks++;
218                 /* Get timescale and duration of the video track; */
219                 if( p_sys->i_timescale == 0 )
220                 {
221                     p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
222                     p_sys->i_duration = p_stra->data.p_stra->i_duration;
223                     if( p_sys->i_timescale == 0 )
224                     {
225                         msg_Err( p_demux, "bad timescale" );
226                         goto LoadInitFragError;
227                     }
228                 }
229             }
230         }
231     }
232     else
233     {
234         /* Load all boxes ( except raw data ) */
235         if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
236         {
237             goto LoadInitFragError;
238         }
239     }
240     return VLC_SUCCESS;
241
242 LoadInitFragError:
243     msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
244     return VLC_EGENERIC;
245 }
246
247 static int InitTracks( demux_t *p_demux )
248 {
249     demux_sys_t *p_sys = p_demux->p_sys;
250
251     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
252     if( p_sys->track == NULL )
253         return VLC_EGENERIC;
254
255     if( p_sys->b_fragmented )
256     {
257         mp4_track_t *p_track;
258         for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
259         {
260             p_track = &p_sys->track[i];
261             p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
262             if( unlikely( !p_track->cchunk ) )
263             {
264                 free( p_sys->track );
265                 return VLC_EGENERIC;
266             }
267         }
268     }
269     return VLC_SUCCESS;
270 }
271
272 static void CreateTracksFromSmooBox( demux_t *p_demux )
273 {
274     demux_sys_t *p_sys = p_demux->p_sys;
275
276     MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
277     mp4_track_t *p_track;
278     int j = 0;
279     for( int i = 0; i < 3; i++ )
280     {
281         MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
282         if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
283             continue;
284         else
285         {
286             p_track = &p_sys->track[j]; j++;
287             MP4_frg_TrackCreate( p_demux, p_track, p_stra );
288             p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
289         }
290     }
291 }
292
293 /*****************************************************************************
294  * Open: check file and initializes MP4 structures
295  *****************************************************************************/
296 static int Open( vlc_object_t * p_this )
297 {
298     demux_t  *p_demux = (demux_t *)p_this;
299     demux_sys_t     *p_sys;
300
301     const uint8_t   *p_peek;
302
303     MP4_Box_t       *p_ftyp;
304     MP4_Box_t       *p_rmra;
305     MP4_Box_t       *p_mvhd;
306     MP4_Box_t       *p_trak;
307
308     unsigned int    i;
309     bool      b_seekable;
310     bool      b_enabled_es;
311
312     /* A little test to see if it could be a mp4 */
313     if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
314
315     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
316     {
317         case ATOM_moov:
318         case ATOM_foov:
319         case ATOM_moof:
320         case ATOM_mdat:
321         case ATOM_udta:
322         case ATOM_free:
323         case ATOM_skip:
324         case ATOM_wide:
325         case ATOM_uuid:
326         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
327             break;
328         case ATOM_ftyp:
329             /* We don't yet support f4v, but avformat does. */
330             if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
331                 return VLC_EGENERIC;
332             break;
333          default:
334             return VLC_EGENERIC;
335     }
336
337     /* I need to seek */
338     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
339     if( !b_seekable )
340     {
341         msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
342         return VLC_EGENERIC;
343     }
344
345     /*Set exported functions */
346     p_demux->pf_demux = Demux;
347     p_demux->pf_control = Control;
348
349     /* create our structure that will contains all data */
350     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
351
352     /* Is it Smooth Streaming? */
353     bool b_smooth = false;
354     if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
355     if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
356     {
357         b_smooth = true;
358         p_sys->b_fragmented = true;
359     }
360
361     if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
362         goto error;
363
364     if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
365     {
366         p_sys->b_fragmented = true;
367     }
368     if( p_sys->b_fragmented )
369     {
370         p_demux->pf_demux = DemuxFrg;
371     }
372
373     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
374     if( b_smooth )
375     {
376         if( InitTracks( p_demux ) != VLC_SUCCESS )
377             goto error;
378         CreateTracksFromSmooBox( p_demux );
379         return VLC_SUCCESS;
380     }
381     else if( p_sys->b_fragmented && b_seekable )
382     {
383         /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
384          * box. So if STREAM_CAN_FASTSEEK is true, we're assuming we've got such
385          * a file, and we let avformat do the job. */
386         msg_Warn( p_demux, "MP4 plugin discarded "\
387                 "(fast-seekable and fragmented, let avformat demux it)" );
388         stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
389         goto error;
390     }
391     else if( !p_sys->b_fragmented && !b_seekable )
392     {
393         msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
394         stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
395         goto error;
396     }
397
398     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
399
400     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
401     {
402         switch( p_ftyp->data.p_ftyp->i_major_brand )
403         {
404             case( ATOM_isom ):
405                 msg_Dbg( p_demux,
406                          "ISO Media file (isom) version %d.",
407                          p_ftyp->data.p_ftyp->i_minor_version );
408                 break;
409             case( ATOM_3gp4 ):
410             case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
411             case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
412             case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
413                 msg_Dbg( p_demux, "3GPP Media file Release: %c",
414 #ifdef WORDS_BIGENDIAN
415                         p_ftyp->data.p_ftyp->i_major_brand
416 #else
417                         p_ftyp->data.p_ftyp->i_major_brand >> 24
418 #endif
419                         );
420                 break;
421             case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
422                 msg_Dbg( p_demux, "Apple QuickTime file" );
423                 break;
424             case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
425                 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
426                 break;
427             default:
428                 msg_Dbg( p_demux,
429                          "unrecognized major file specification (%4.4s).",
430                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
431                 break;
432         }
433     }
434     else
435     {
436         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
437     }
438
439     /* the file need to have one moov box */
440     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
441     {
442         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
443
444         if( !p_foov )
445         {
446             msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
447             goto error;
448         }
449         /* we have a free box as a moov, rename it */
450         p_foov->i_type = ATOM_moov;
451     }
452
453     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
454     {
455         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
456         int        i;
457
458         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
459
460         input_thread_t *p_input = demux_GetParentInput( p_demux );
461         input_item_t *p_current = input_GetItem( p_input );
462
463         input_item_node_t *p_subitems = input_item_node_Create( p_current );
464
465         for( i = 0; i < i_count; i++ )
466         {
467             MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
468             char      *psz_ref;
469             uint32_t  i_ref_type;
470
471             if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
472             {
473                 continue;
474             }
475             i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
476
477             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
478                      psz_ref, (char*)&i_ref_type );
479
480             if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
481             {
482                 if( strstr( psz_ref, "qt5gateQT" ) )
483                 {
484                     msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
485                     continue;
486                 }
487                 if( !strncmp( psz_ref, "http://", 7 ) ||
488                     !strncmp( psz_ref, "rtsp://", 7 ) )
489                 {
490                     ;
491                 }
492                 else
493                 {
494                     char *psz_absolute;
495                     char *psz_path = strdup( p_demux->psz_location );
496                     char *end = strrchr( psz_path, '/' );
497                     if( end ) end[1] = '\0';
498                     else *psz_path = '\0';
499
500                     if( asprintf( &psz_absolute, "%s://%s%s",
501                                   p_demux->psz_access, psz_path, psz_ref ) < 0 )
502                     {
503                         free( psz_ref );
504                         free( psz_path );
505                         vlc_object_release( p_input) ;
506                         return VLC_ENOMEM;
507                     }
508
509                     free( psz_ref );
510                     psz_ref = psz_absolute;
511                     free( psz_path );
512                 }
513                 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
514                 input_item_t *p_item = input_item_New( psz_ref, NULL );
515                 input_item_CopyOptions( p_current, p_item );
516                 input_item_node_AppendItem( p_subitems, p_item );
517                 vlc_gc_decref( p_item );
518             }
519             else
520             {
521                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
522                          (char*)&p_rdrf->data.p_rdrf->i_ref_type );
523             }
524             free( psz_ref );
525         }
526         input_item_node_PostAndDelete( p_subitems );
527         vlc_object_release( p_input );
528     }
529
530     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
531     {
532         if( !p_rmra )
533         {
534             msg_Err( p_demux, "cannot find /moov/mvhd" );
535             goto error;
536         }
537         else
538         {
539             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
540             p_demux->pf_demux = DemuxRef;
541             return VLC_SUCCESS;
542         }
543     }
544     else
545     {
546         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
547         if( p_sys->i_timescale == 0 )
548         {
549             msg_Err( p_this, "bad timescale" );
550             goto error;
551         }
552         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
553     }
554
555     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
556     {
557         msg_Err( p_demux, "cannot find any /moov/trak" );
558         goto error;
559     }
560     msg_Dbg( p_demux, "found %d track%c",
561                         p_sys->i_tracks,
562                         p_sys->i_tracks ? 's':' ' );
563
564     if( InitTracks( p_demux ) != VLC_SUCCESS )
565         goto error;
566
567     /* Search the first chap reference (like quicktime) and
568      * check that at least 1 stream is enabled */
569     p_sys->p_tref_chap = NULL;
570     b_enabled_es = false;
571     for( i = 0; i < p_sys->i_tracks; i++ )
572     {
573         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
574
575
576         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
577         if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
578             b_enabled_es = true;
579
580         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
581         if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
582             p_sys->p_tref_chap = p_chap;
583     }
584
585     /* now process each track and extract all useful information */
586     for( i = 0; i < p_sys->i_tracks; i++ )
587     {
588         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
589         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
590
591         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
592         {
593             const char *psz_cat;
594             switch( p_sys->track[i].fmt.i_cat )
595             {
596                 case( VIDEO_ES ):
597                     psz_cat = "video";
598                     break;
599                 case( AUDIO_ES ):
600                     psz_cat = "audio";
601                     break;
602                 case( SPU_ES ):
603                     psz_cat = "subtitle";
604                     break;
605
606                 default:
607                     psz_cat = "unknown";
608                     break;
609             }
610
611             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
612                      p_sys->track[i].i_track_ID, psz_cat,
613                      p_sys->track[i].b_enable ? "enable":"disable",
614                      p_sys->track[i].fmt.psz_language ?
615                      p_sys->track[i].fmt.psz_language : "undef" );
616         }
617         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
618         {
619             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
620                      p_sys->track[i].i_track_ID,
621                      p_sys->track[i].fmt.psz_language ?
622                      p_sys->track[i].fmt.psz_language : "undef" );
623         }
624         else
625         {
626             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
627                      p_sys->track[i].i_track_ID );
628         }
629     }
630
631     /* */
632     LoadChapter( p_demux );
633
634     return VLC_SUCCESS;
635
636 error:
637     if( p_sys->p_root )
638     {
639         MP4_BoxFree( p_demux->s, p_sys->p_root );
640     }
641     free( p_sys );
642     return VLC_EGENERIC;
643 }
644
645 /*****************************************************************************
646  * Demux: read packet and send them to decoders
647  *****************************************************************************
648  * TODO check for newly selected track (ie audio upt to now )
649  *****************************************************************************/
650 static int Demux( demux_t *p_demux )
651 {
652     demux_sys_t *p_sys = p_demux->p_sys;
653     unsigned int i_track;
654
655
656     unsigned int i_track_selected;
657
658     /* check for newly selected/unselected track */
659     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
660          i_track++ )
661     {
662         mp4_track_t *tk = &p_sys->track[i_track];
663         bool b;
664
665         if( !tk->b_ok || tk->b_chapter ||
666             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
667         {
668             continue;
669         }
670
671         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
672
673         if( tk->b_selected && !b )
674         {
675             MP4_TrackUnselect( p_demux, tk );
676         }
677         else if( !tk->b_selected && b)
678         {
679             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
680         }
681
682         if( tk->b_selected )
683         {
684             i_track_selected++;
685         }
686     }
687
688     if( i_track_selected <= 0 )
689     {
690         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
691         if( p_sys->i_timescale > 0 )
692         {
693             int64_t i_length = (mtime_t)1000000 *
694                                (mtime_t)p_sys->i_duration /
695                                (mtime_t)p_sys->i_timescale;
696             if( MP4_GetMoviePTS( p_sys ) >= i_length )
697                 return 0;
698             return 1;
699         }
700
701         msg_Warn( p_demux, "no track selected, exiting..." );
702         return 0;
703     }
704
705     /* */
706     MP4_UpdateSeekpoint( p_demux );
707
708     /* first wait for the good time to read a packet */
709     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
710
711     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
712
713     /* we will read 100ms for each stream so ...*/
714     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
715
716     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
717     {
718         mp4_track_t *tk = &p_sys->track[i_track];
719
720         if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
721             continue;
722
723         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
724         {
725 #if 0
726             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
727                      MP4_TrackGetDTS( p_demux, tk ),
728                      MP4_GetMoviePTS( p_sys ) );
729 #endif
730
731             if( MP4_TrackSampleSize( tk ) > 0 )
732             {
733                 block_t *p_block;
734                 int64_t i_delta;
735
736                 /* go,go go ! */
737                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
738                 {
739                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
740                               tk->i_track_ID );
741                     MP4_TrackUnselect( p_demux, tk );
742                     break;
743                 }
744
745                 /* now read pes */
746                 if( !(p_block =
747                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
748                 {
749                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
750                               tk->i_track_ID );
751                     MP4_TrackUnselect( p_demux, tk );
752                     break;
753                 }
754
755                 else if( tk->fmt.i_cat == SPU_ES )
756                 {
757                     if( tk->fmt.i_codec == VLC_CODEC_SUBT &&
758                         p_block->i_buffer >= 2 )
759                     {
760                         size_t i_size = GetWBE( p_block->p_buffer );
761
762                         if( i_size + 2 <= p_block->i_buffer )
763                         {
764                             char *p;
765                             /* remove the length field, and append a '\0' */
766                             memmove( &p_block->p_buffer[0],
767                                      &p_block->p_buffer[2], i_size );
768                             p_block->p_buffer[i_size] = '\0';
769                             p_block->i_buffer = i_size + 1;
770
771                             /* convert \r -> \n */
772                             while( ( p = strchr((char *) p_block->p_buffer, '\r' ) ) )
773                             {
774                                 *p = '\n';
775                             }
776                         }
777                         else
778                         {
779                             /* Invalid */
780                             p_block->i_buffer = 0;
781                         }
782                     }
783                 }
784                 /* dts */
785                 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
786                 /* pts */
787                 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
788                 if( i_delta != -1 )
789                     p_block->i_pts = p_block->i_dts + i_delta;
790                 else if( tk->fmt.i_cat != VIDEO_ES )
791                     p_block->i_pts = p_block->i_dts;
792                 else
793                     p_block->i_pts = VLC_TS_INVALID;
794
795                 es_out_Send( p_demux->out, tk->p_es, p_block );
796             }
797
798             /* Next sample */
799             if( MP4_TrackNextSample( p_demux, tk ) )
800                 break;
801         }
802     }
803
804     return 1;
805 }
806
807 static void MP4_UpdateSeekpoint( demux_t *p_demux )
808 {
809     demux_sys_t *p_sys = p_demux->p_sys;
810     int64_t i_time;
811     int i;
812     if( !p_sys->p_title )
813         return;
814     i_time = MP4_GetMoviePTS( p_sys );
815     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
816     {
817         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
818             break;
819     }
820     i--;
821
822     if( i != p_demux->info.i_seekpoint && i >= 0 )
823     {
824         p_demux->info.i_seekpoint = i;
825         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
826     }
827 }
828 /*****************************************************************************
829  * Seek: Go to i_date
830 ******************************************************************************/
831 static int Seek( demux_t *p_demux, mtime_t i_date )
832 {
833     demux_sys_t *p_sys = p_demux->p_sys;
834     unsigned int i_track;
835
836     /* First update global time */
837     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
838     p_sys->i_pcr  = i_date;
839
840     /* Now for each stream try to go to this time */
841     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
842     {
843         mp4_track_t *tk = &p_sys->track[i_track];
844         MP4_TrackSeek( p_demux, tk, i_date );
845     }
846     MP4_UpdateSeekpoint( p_demux );
847
848     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
849
850     return VLC_SUCCESS;
851 }
852
853 static int MP4_frg_Seek( demux_t *p_demux, double f )
854 {
855     demux_sys_t *p_sys = p_demux->p_sys;
856
857     int64_t i64 = stream_Size( p_demux->s );
858     if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
859     {
860         return VLC_EGENERIC;
861     }
862     else
863     {
864         /* update global time */
865         p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
866         p_sys->i_pcr  = MP4_GetMoviePTS( p_sys );
867
868         for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
869         {
870             mp4_track_t *tk = &p_sys->track[i_track];
871
872             /* We don't want the current chunk to be flushed */
873             tk->cchunk->i_sample = tk->cchunk->i_sample_count;
874
875             /* reset/update some values */
876             tk->i_sample = tk->i_sample_first = 0;
877             tk->i_first_dts = p_sys->i_time;
878
879             /* We want to discard the current chunk and get the next one at once */
880             tk->b_has_non_empty_cchunk = false;
881         }
882         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
883         return VLC_SUCCESS;
884     }
885 }
886
887 /*****************************************************************************
888  * Control:
889  *****************************************************************************/
890 static int Control( demux_t *p_demux, int i_query, va_list args )
891 {
892     demux_sys_t *p_sys = p_demux->p_sys;
893
894     double f, *pf;
895     int64_t i64, *pi64;
896
897     switch( i_query )
898     {
899         case DEMUX_GET_POSITION:
900             pf = (double*)va_arg( args, double * );
901             if( p_sys->i_duration > 0 )
902             {
903                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
904             }
905             else
906             {
907                 *pf = 0.0;
908             }
909             return VLC_SUCCESS;
910
911         case DEMUX_SET_POSITION:
912             f = (double)va_arg( args, double );
913             if( p_sys->b_fragmented )
914             {
915                 return MP4_frg_Seek( p_demux, f );
916             }
917             else if( p_sys->i_timescale > 0 )
918             {
919                 i64 = (int64_t)( f * (double)1000000 *
920                                  (double)p_sys->i_duration /
921                                  (double)p_sys->i_timescale );
922                 return Seek( p_demux, i64 );
923             }
924             else return VLC_SUCCESS;
925
926         case DEMUX_GET_TIME:
927             pi64 = (int64_t*)va_arg( args, int64_t * );
928             if( p_sys->i_timescale > 0 )
929             {
930                 *pi64 = (mtime_t)1000000 *
931                         (mtime_t)p_sys->i_time /
932                         (mtime_t)p_sys->i_timescale;
933             }
934             else *pi64 = 0;
935             return VLC_SUCCESS;
936
937         case DEMUX_SET_TIME:
938             i64 = (int64_t)va_arg( args, int64_t );
939             return Seek( p_demux, i64 );
940
941         case DEMUX_GET_LENGTH:
942             pi64 = (int64_t*)va_arg( args, int64_t * );
943             if( p_sys->i_timescale > 0 )
944             {
945                 *pi64 = (mtime_t)1000000 *
946                         (mtime_t)p_sys->i_duration /
947                         (mtime_t)p_sys->i_timescale;
948             }
949             else *pi64 = 0;
950             return VLC_SUCCESS;
951
952         case DEMUX_GET_FPS:
953             pf = (double*)va_arg( args, double* );
954             *pf = p_sys->f_fps;
955             return VLC_SUCCESS;
956
957         case DEMUX_GET_META:
958         {
959             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
960             MP4_Box_t  *p_0xa9xxx;
961
962             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
963             if( p_udta == NULL )
964             {
965                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
966                 if( p_udta == NULL )
967                 {
968                     return VLC_EGENERIC;
969                 }
970             }
971
972             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
973                  p_0xa9xxx = p_0xa9xxx->p_next )
974             {
975
976                 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
977                     continue;
978
979                 /* FIXME FIXME: should convert from whatever the character
980                  * encoding of MP4 meta data is to UTF-8. */
981 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
982     if( psz_utf ) { EnsureUTF8( psz_utf );  \
983                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
984
985                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
986                 switch( p_0xa9xxx->i_type )
987                 {
988                 case ATOM_0xa9nam: /* Full name */
989                     SET( vlc_meta_SetTitle );
990                     break;
991                 case ATOM_0xa9aut:
992                     SET( vlc_meta_SetArtist );
993                     break;
994                 case ATOM_0xa9ART:
995                     SET( vlc_meta_SetArtist );
996                     break;
997                 case ATOM_0xa9cpy:
998                     SET( vlc_meta_SetCopyright );
999                     break;
1000                 case ATOM_0xa9day: /* Creation Date */
1001                     SET( vlc_meta_SetDate );
1002                     break;
1003                 case ATOM_0xa9des: /* Description */
1004                     SET( vlc_meta_SetDescription );
1005                     break;
1006                 case ATOM_0xa9gen: /* Genre */
1007                     SET( vlc_meta_SetGenre );
1008                     break;
1009
1010                 case ATOM_gnre:
1011                     if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1012                         vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1013                     break;
1014
1015                 case ATOM_0xa9alb: /* Album */
1016                     SET( vlc_meta_SetAlbum );
1017                     break;
1018
1019                 case ATOM_0xa9trk: /* Track */
1020                     SET( vlc_meta_SetTrackNum );
1021                     break;
1022                 case ATOM_trkn:
1023                 {
1024                     char psz_trck[11];
1025                     snprintf( psz_trck, sizeof( psz_trck ), "%i",
1026                               p_0xa9xxx->data.p_trkn->i_track_number );
1027                     vlc_meta_SetTrackNum( p_meta, psz_trck );
1028                     if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1029                     {
1030                         snprintf( psz_trck, sizeof( psz_trck ), "%i",
1031                                   p_0xa9xxx->data.p_trkn->i_track_total );
1032                         vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1033                     }
1034                     break;
1035                 }
1036                 case ATOM_0xa9cmt: /* Commment */
1037                     SET( vlc_meta_SetDescription );
1038                     break;
1039
1040                 case ATOM_0xa9url: /* URL */
1041                     SET( vlc_meta_SetURL );
1042                     break;
1043
1044                 case ATOM_0xa9too: /* Encoder Tool */
1045                 case ATOM_0xa9enc: /* Encoded By */
1046                     SET( vlc_meta_SetEncodedBy );
1047                     break;
1048
1049                 case ATOM_0xa9pub:
1050                     SET( vlc_meta_SetPublisher );
1051                     break;
1052
1053                 default:
1054                     break;
1055                 }
1056 #undef SET
1057                 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1058                 {
1059                     { ATOM_0xa9wrt, N_("Writer") },
1060                     { ATOM_0xa9com, N_("Composer") },
1061                     { ATOM_0xa9prd, N_("Producer") },
1062                     { ATOM_0xa9inf, N_("Information") },
1063                     { ATOM_0xa9dir, N_("Director") },
1064                     { ATOM_0xa9dis, N_("Disclaimer") },
1065                     { ATOM_0xa9req, N_("Requirements") },
1066                     { ATOM_0xa9fmt, N_("Original Format") },
1067                     { ATOM_0xa9dsa, N_("Display Source As") },
1068                     { ATOM_0xa9hst, N_("Host Computer") },
1069                     { ATOM_0xa9prf, N_("Performers") },
1070                     { ATOM_0xa9ope, N_("Original Performer") },
1071                     { ATOM_0xa9src, N_("Providers Source Content") },
1072                     { ATOM_0xa9wrn, N_("Warning") },
1073                     { ATOM_0xa9swr, N_("Software") },
1074                     { ATOM_0xa9lyr, N_("Lyrics") },
1075                     { ATOM_0xa9mak, N_("Record Company") },
1076                     { ATOM_0xa9mod, N_("Model") },
1077                     { ATOM_0xa9PRD, N_("Product") },
1078                     { ATOM_0xa9grp, N_("Grouping") },
1079                     { ATOM_0xa9gen, N_("Genre") },
1080                     { ATOM_0xa9st3, N_("Sub-Title") },
1081                     { ATOM_0xa9arg, N_("Arranger") },
1082                     { ATOM_0xa9ard, N_("Art Director") },
1083                     { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1084                     { ATOM_0xa9con, N_("Conductor") },
1085                     { ATOM_0xa9des, N_("Song Description") },
1086                     { ATOM_0xa9lnt, N_("Liner Notes") },
1087                     { ATOM_0xa9phg, N_("Phonogram Rights") },
1088                     { ATOM_0xa9pub, N_("Publisher") },
1089                     { ATOM_0xa9sne, N_("Sound Engineer") },
1090                     { ATOM_0xa9sol, N_("Soloist") },
1091                     { ATOM_0xa9thx, N_("Thanks") },
1092                     { ATOM_0xa9xpd, N_("Executive Producer") },
1093                     { 0, "" },
1094                 };
1095                 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1096                 {
1097                     if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1098                     {
1099                         char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1100                         if( psz_utf )
1101                         {
1102                              EnsureUTF8( psz_utf );
1103                              vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1104                              free( psz_utf );
1105                         }
1106                         break;
1107                     }
1108                 }
1109             }
1110             return VLC_SUCCESS;
1111         }
1112
1113         case DEMUX_GET_TITLE_INFO:
1114         {
1115             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1116             int *pi_int    = (int*)va_arg( args, int* );
1117             int *pi_title_offset = (int*)va_arg( args, int* );
1118             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1119
1120             if( !p_sys->p_title )
1121                 return VLC_EGENERIC;
1122
1123             *pi_int = 1;
1124             *ppp_title = malloc( sizeof( input_title_t*) );
1125             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1126             *pi_title_offset = 0;
1127             *pi_seekpoint_offset = 0;
1128             return VLC_SUCCESS;
1129         }
1130         case DEMUX_SET_TITLE:
1131         {
1132             const int i_title = (int)va_arg( args, int );
1133             if( !p_sys->p_title || i_title != 0 )
1134                 return VLC_EGENERIC;
1135             return VLC_SUCCESS;
1136         }
1137         case DEMUX_SET_SEEKPOINT:
1138         {
1139             const int i_seekpoint = (int)va_arg( args, int );
1140             if( !p_sys->p_title )
1141                 return VLC_EGENERIC;
1142             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1143         }
1144
1145         case DEMUX_SET_NEXT_DEMUX_TIME:
1146         case DEMUX_SET_GROUP:
1147         case DEMUX_HAS_UNSUPPORTED_META:
1148         case DEMUX_GET_ATTACHMENTS:
1149         case DEMUX_GET_PTS_DELAY:
1150         case DEMUX_CAN_RECORD:
1151             return VLC_EGENERIC;
1152
1153         default:
1154             msg_Warn( p_demux, "control query %u unimplemented", i_query );
1155             return VLC_EGENERIC;
1156     }
1157 }
1158
1159 /*****************************************************************************
1160  * Close: frees unused data
1161  *****************************************************************************/
1162 static void Close ( vlc_object_t * p_this )
1163 {
1164     demux_t *  p_demux = (demux_t *)p_this;
1165     demux_sys_t *p_sys = p_demux->p_sys;
1166     unsigned int i_track;
1167
1168     msg_Dbg( p_demux, "freeing all memory" );
1169
1170     MP4_BoxFree( p_demux->s, p_sys->p_root );
1171     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1172     {
1173         MP4_TrackDestroy(  &p_sys->track[i_track] );
1174     }
1175     FREENULL( p_sys->track );
1176
1177     if( p_sys->p_title )
1178         vlc_input_title_Delete( p_sys->p_title );
1179
1180     free( p_sys );
1181 }
1182
1183
1184
1185 /****************************************************************************
1186  * Local functions, specific to vlc
1187  ****************************************************************************/
1188 /* Chapters */
1189 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
1190 {
1191     demux_sys_t *p_sys = p_demux->p_sys;
1192     int i;
1193
1194     p_sys->p_title = vlc_input_title_New();
1195     for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1196     {
1197         seekpoint_t *s = vlc_seekpoint_New();
1198
1199         s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1200         EnsureUTF8( s->psz_name );
1201         s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1202         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1203     }
1204 }
1205 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1206 {
1207     demux_sys_t *p_sys = p_demux->p_sys;
1208
1209     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1210     {
1211         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1212         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1213         const unsigned int i_size = MP4_TrackSampleSize( tk );
1214
1215         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1216         {
1217             char p_buffer[256];
1218             const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1219             const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1220
1221             if( i_len > 0 )
1222             {
1223                 seekpoint_t *s = vlc_seekpoint_New();
1224
1225                 s->psz_name = strndup( &p_buffer[2], i_len );
1226                 EnsureUTF8( s->psz_name );
1227
1228                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1229
1230                 if( !p_sys->p_title )
1231                     p_sys->p_title = vlc_input_title_New();
1232                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1233             }
1234         }
1235         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1236                               tk->chunk[tk->i_chunk].i_sample_count )
1237             tk->i_chunk++;
1238     }
1239 }
1240 static void LoadChapter( demux_t  *p_demux )
1241 {
1242     demux_sys_t *p_sys = p_demux->p_sys;
1243     MP4_Box_t *p_chpl;
1244
1245     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1246     {
1247         LoadChapterGpac( p_demux, p_chpl );
1248     }
1249     else if( p_sys->p_tref_chap )
1250     {
1251         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1252         unsigned int i, j;
1253
1254         /* Load the first subtitle track like quicktime */
1255         for( i = 0; i < p_chap->i_entry_count; i++ )
1256         {
1257             for( j = 0; j < p_sys->i_tracks; j++ )
1258             {
1259                 mp4_track_t *tk = &p_sys->track[j];
1260                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1261                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1262                     break;
1263             }
1264             if( j < p_sys->i_tracks )
1265             {
1266                 LoadChapterApple( p_demux, &p_sys->track[j] );
1267                 break;
1268             }
1269         }
1270     }
1271
1272     /* Add duration if titles are enabled */
1273     if( p_sys->p_title )
1274     {
1275         p_sys->p_title->i_length = (uint64_t)1000000 *
1276                        (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1277     }
1278 }
1279
1280 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1281 static int TrackCreateChunksIndex( demux_t *p_demux,
1282                                    mp4_track_t *p_demux_track )
1283 {
1284     demux_sys_t *p_sys = p_demux->p_sys;
1285     if( p_sys->b_fragmented )
1286         return VLC_SUCCESS;
1287
1288     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1289     MP4_Box_t *p_stsc;
1290
1291     unsigned int i_chunk;
1292     unsigned int i_index, i_last;
1293
1294     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1295           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1296         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1297     {
1298         return( VLC_EGENERIC );
1299     }
1300
1301     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1302     if( !p_demux_track->i_chunk_count )
1303     {
1304         msg_Warn( p_demux, "no chunk defined" );
1305         return( VLC_EGENERIC );
1306     }
1307     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1308                                    sizeof( mp4_chunk_t ) );
1309     if( p_demux_track->chunk == NULL )
1310     {
1311         return VLC_ENOMEM;
1312     }
1313
1314     /* first we read chunk offset */
1315     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1316     {
1317         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1318
1319         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1320
1321         ck->i_first_dts = 0;
1322         ck->p_sample_count_dts = NULL;
1323         ck->p_sample_delta_dts = NULL;
1324         ck->p_sample_count_pts = NULL;
1325         ck->p_sample_offset_pts = NULL;
1326     }
1327
1328     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1329         to be used for the sample XXX begin to 1
1330         We construct it begining at the end */
1331     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1332     i_index = p_stsc->data.p_stsc->i_entry_count;
1333     if( !i_index )
1334     {
1335         msg_Warn( p_demux, "cannot read chunk table or table empty" );
1336         return( VLC_EGENERIC );
1337     }
1338
1339     while( i_index-- )
1340     {
1341         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1342              i_chunk < i_last; i_chunk++ )
1343         {
1344             if( i_chunk >= p_demux_track->i_chunk_count )
1345             {
1346                 msg_Warn( p_demux, "corrupted chunk table" );
1347                 return VLC_EGENERIC;
1348             }
1349
1350             p_demux_track->chunk[i_chunk].i_sample_description_index =
1351                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
1352             p_demux_track->chunk[i_chunk].i_sample_count =
1353                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1354         }
1355         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1356     }
1357
1358     p_demux_track->chunk[0].i_sample_first = 0;
1359     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1360     {
1361         p_demux_track->chunk[i_chunk].i_sample_first =
1362             p_demux_track->chunk[i_chunk-1].i_sample_first +
1363                 p_demux_track->chunk[i_chunk-1].i_sample_count;
1364     }
1365
1366     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1367              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1368
1369     return VLC_SUCCESS;
1370 }
1371
1372 static int TrackCreateSamplesIndex( demux_t *p_demux,
1373                                     mp4_track_t *p_demux_track )
1374 {
1375     demux_sys_t *p_sys = p_demux->p_sys;
1376     if( p_sys->b_fragmented )
1377         return VLC_SUCCESS;
1378
1379     MP4_Box_t *p_box;
1380     MP4_Box_data_stsz_t *stsz;
1381     MP4_Box_data_stts_t *stts;
1382     /* TODO use also stss and stsh table for seeking */
1383     /* FIXME use edit table */
1384     int64_t i_sample;
1385     int64_t i_chunk;
1386
1387     int64_t i_index;
1388     int64_t i_index_sample_used;
1389
1390     int64_t i_next_dts;
1391
1392     /* Find stsz
1393      *  Gives the sample size for each samples. There is also a stz2 table
1394      *  (compressed form) that we need to implement TODO */
1395     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1396     if( !p_box )
1397     {
1398         /* FIXME and stz2 */
1399         msg_Warn( p_demux, "cannot find STSZ box" );
1400         return VLC_EGENERIC;
1401     }
1402     stsz = p_box->data.p_stsz;
1403
1404     /* Find stts
1405      *  Gives mapping between sample and decoding time
1406      */
1407     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1408     if( !p_box )
1409     {
1410         msg_Warn( p_demux, "cannot find STTS box" );
1411         return VLC_EGENERIC;
1412     }
1413     stts = p_box->data.p_stts;
1414
1415     /* Use stsz table to create a sample number -> sample size table */
1416     p_demux_track->i_sample_count = stsz->i_sample_count;
1417     if( stsz->i_sample_size )
1418     {
1419         /* 1: all sample have the same size, so no need to construct a table */
1420         p_demux_track->i_sample_size = stsz->i_sample_size;
1421         p_demux_track->p_sample_size = NULL;
1422     }
1423     else
1424     {
1425         /* 2: each sample can have a different size */
1426         p_demux_track->i_sample_size = 0;
1427         p_demux_track->p_sample_size =
1428             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1429         if( p_demux_track->p_sample_size == NULL )
1430             return VLC_ENOMEM;
1431
1432         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1433         {
1434             p_demux_track->p_sample_size[i_sample] =
1435                     stsz->i_entry_size[i_sample];
1436         }
1437     }
1438
1439     /* Use stts table to create a sample number -> dts table.
1440      * XXX: if we don't want to waste too much memory, we can't expand
1441      *  the box! so each chunk will contain an "extract" of this table
1442      *  for fast research (problem with raw stream where a sample is sometime
1443      *  just channels*bits_per_sample/8 */
1444
1445     i_next_dts = 0;
1446     i_index = 0; i_index_sample_used = 0;
1447     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1448     {
1449         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1450         int64_t i_entry, i_sample_count, i;
1451
1452         /* save first dts */
1453         ck->i_first_dts = i_next_dts;
1454         ck->i_last_dts  = i_next_dts;
1455
1456         /* count how many entries are needed for this chunk
1457          * for p_sample_delta_dts and p_sample_count_dts */
1458         i_sample_count = ck->i_sample_count;
1459
1460         i_entry = 0;
1461         while( i_sample_count > 0 )
1462         {
1463             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1464             /* don't count already used sample in this entry */
1465             if( i_entry == 0 )
1466                 i_sample_count += i_index_sample_used;
1467
1468             i_entry++;
1469         }
1470
1471         /* allocate them */
1472         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1473         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1474
1475         if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1476             return VLC_ENOMEM;
1477
1478         /* now copy */
1479         i_sample_count = ck->i_sample_count;
1480         for( i = 0; i < i_entry; i++ )
1481         {
1482             int64_t i_used;
1483             int64_t i_rest;
1484
1485             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1486
1487             i_used = __MIN( i_rest, i_sample_count );
1488
1489             i_index_sample_used += i_used;
1490             i_sample_count -= i_used;
1491             i_next_dts += i_used * stts->i_sample_delta[i_index];
1492
1493             ck->p_sample_count_dts[i] = i_used;
1494             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1495             if( i_used > 0 )
1496                 ck->i_last_dts = i_next_dts - ck->p_sample_delta_dts[i];
1497
1498             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1499             {
1500                 i_index++;
1501                 i_index_sample_used = 0;
1502             }
1503         }
1504     }
1505
1506     /* Find ctts
1507      *  Gives the delta between decoding time (dts) and composition table (pts)
1508      */
1509     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1510     if( p_box )
1511     {
1512         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1513
1514         msg_Warn( p_demux, "CTTS table" );
1515
1516         /* Create pts-dts table per chunk */
1517         i_index = 0; i_index_sample_used = 0;
1518         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1519         {
1520             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1521             int64_t i_entry, i_sample_count, i;
1522
1523             /* count how many entries are needed for this chunk
1524              * for p_sample_delta_dts and p_sample_count_dts */
1525             i_sample_count = ck->i_sample_count;
1526
1527             i_entry = 0;
1528             while( i_sample_count > 0 )
1529             {
1530                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1531
1532                 /* don't count already used sample in this entry */
1533                 if( i_entry == 0 )
1534                     i_sample_count += i_index_sample_used;
1535
1536                 i_entry++;
1537             }
1538
1539             /* allocate them */
1540             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1541             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1542             if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1543                 return VLC_ENOMEM;
1544
1545             /* now copy */
1546             i_sample_count = ck->i_sample_count;
1547             for( i = 0; i < i_entry; i++ )
1548             {
1549                 int64_t i_used;
1550                 int64_t i_rest;
1551
1552                 i_rest = ctts->i_sample_count[i_index] -
1553                     i_index_sample_used;
1554
1555                 i_used = __MIN( i_rest, i_sample_count );
1556
1557                 i_index_sample_used += i_used;
1558                 i_sample_count -= i_used;
1559
1560                 ck->p_sample_count_pts[i] = i_used;
1561                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1562
1563                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1564                 {
1565                     i_index++;
1566                     i_index_sample_used = 0;
1567                 }
1568             }
1569         }
1570     }
1571
1572     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:%"PRId64"s",
1573              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1574              i_next_dts / p_demux_track->i_timescale );
1575
1576     return VLC_SUCCESS;
1577 }
1578
1579 /**
1580  * It computes the sample rate for a video track using the given sample
1581  * description index
1582  */
1583 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1584                                   const mp4_track_t *p_track,
1585                                   unsigned i_sd_index,
1586                                   unsigned i_chunk )
1587 {
1588     *pi_num = 0;
1589     *pi_den = 0;
1590
1591     if( p_track->i_chunk_count <= 0 )
1592         return;
1593
1594     /* */
1595     const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1596     while( p_chunk > &p_track->chunk[0] &&
1597            p_chunk[-1].i_sample_description_index == i_sd_index )
1598     {
1599         p_chunk--;
1600     }
1601
1602     uint64_t i_sample = 0;
1603     uint64_t i_first_dts = p_chunk->i_first_dts;
1604     uint64_t i_last_dts;
1605     do
1606     {
1607         i_sample += p_chunk->i_sample_count;
1608         i_last_dts = p_chunk->i_last_dts;
1609         p_chunk++;
1610     }
1611     while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1612            p_chunk->i_sample_description_index == i_sd_index );
1613
1614     if( i_sample > 1 && i_first_dts < i_last_dts )
1615         vlc_ureduce( pi_num, pi_den,
1616                      ( i_sample - 1) *  p_track->i_timescale,
1617                      i_last_dts - i_first_dts,
1618                      UINT16_MAX);
1619 }
1620
1621 /*
1622  * TrackCreateES:
1623  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1624  */
1625 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1626                           unsigned int i_chunk, es_out_id_t **pp_es )
1627 {
1628     demux_sys_t *p_sys = p_demux->p_sys;
1629     unsigned int i_sample_description_index;
1630
1631     if( p_sys->b_fragmented )
1632         i_sample_description_index = 1; /* XXX */
1633     else
1634         i_sample_description_index =
1635                 p_track->chunk[i_chunk].i_sample_description_index;
1636
1637     MP4_Box_t   *p_sample;
1638     MP4_Box_t   *p_esds;
1639     MP4_Box_t   *p_frma;
1640     MP4_Box_t   *p_enda;
1641     MP4_Box_t   *p_pasp;
1642
1643     if( pp_es )
1644         *pp_es = NULL;
1645
1646     if( !i_sample_description_index )
1647     {
1648         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1649                   p_track->i_track_ID );
1650         return VLC_EGENERIC;
1651     }
1652
1653     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1654                             i_sample_description_index - 1 );
1655
1656     if( !p_sample ||
1657         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1658     {
1659         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1660                   p_track->i_track_ID );
1661         return VLC_EGENERIC;
1662     }
1663
1664     p_track->p_sample = p_sample;
1665
1666     if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1667     {
1668         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1669
1670         p_sample->i_type = p_frma->data.p_frma->i_type;
1671     }
1672
1673     p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1674     if( !p_enda )
1675         p_enda = MP4_BoxGet( p_sample, "enda" );
1676
1677     p_pasp = MP4_BoxGet( p_sample, "pasp" );
1678
1679     /* */
1680     switch( p_track->fmt.i_cat )
1681     {
1682     case VIDEO_ES:
1683         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1684         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1685         p_track->fmt.video.i_bits_per_pixel =
1686             p_sample->data.p_sample_vide->i_depth;
1687
1688         /* fall on display size */
1689         if( p_track->fmt.video.i_width <= 0 )
1690             p_track->fmt.video.i_width = p_track->i_width;
1691         if( p_track->fmt.video.i_height <= 0 )
1692             p_track->fmt.video.i_height = p_track->i_height;
1693
1694         /* Find out apect ratio from display size */
1695         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1696             /* Work-around buggy muxed files */
1697             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1698         {
1699             p_track->fmt.video.i_sar_num = p_track->i_width  * p_track->fmt.video.i_height;
1700             p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1701         }
1702         if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1703                       p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1704         {
1705             p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1706             p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1707         }
1708
1709         /* Support for cropping (eg. in H263 files) */
1710         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1711         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1712
1713         /* Frame rate */
1714         TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1715                               &p_track->fmt.video.i_frame_rate_base,
1716                               p_track, i_sample_description_index, i_chunk );
1717         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1718                                 (float)p_track->fmt.video.i_frame_rate_base;
1719
1720         /* Rotation */
1721         switch( (int)p_track->f_rotation ) {
1722             case 90:
1723                 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1724                 break;
1725             case 180:
1726                 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1727                 break;
1728             case 270:
1729                 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1730                 break;
1731         }
1732
1733         break;
1734
1735     case AUDIO_ES:
1736         p_track->fmt.audio.i_channels =
1737             p_sample->data.p_sample_soun->i_channelcount;
1738         p_track->fmt.audio.i_rate =
1739             p_sample->data.p_sample_soun->i_sampleratehi;
1740         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1741             p_sample->data.p_sample_soun->i_sampleratehi *
1742                 p_sample->data.p_sample_soun->i_samplesize;
1743         p_track->fmt.audio.i_bitspersample =
1744             p_sample->data.p_sample_soun->i_samplesize;
1745
1746         if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1747         {
1748             MP4_Box_data_sample_soun_t *p_soun;
1749             p_soun = p_sample->data.p_sample_soun;
1750
1751             if( p_soun->i_qt_version == 0 )
1752             {
1753                 switch( p_sample->i_type )
1754                 {
1755                     case VLC_CODEC_ADPCM_IMA_QT:
1756                         p_soun->i_qt_version = 1;
1757                         p_soun->i_sample_per_packet = 64;
1758                         p_soun->i_bytes_per_packet  = 34;
1759                         p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1760                         p_soun->i_bytes_per_sample  = 2;
1761                         break;
1762                     case VLC_CODEC_MACE3:
1763                         p_soun->i_qt_version = 1;
1764                         p_soun->i_sample_per_packet = 6;
1765                         p_soun->i_bytes_per_packet  = 2;
1766                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1767                         p_soun->i_bytes_per_sample  = 2;
1768                         break;
1769                     case VLC_CODEC_MACE6:
1770                         p_soun->i_qt_version = 1;
1771                         p_soun->i_sample_per_packet = 12;
1772                         p_soun->i_bytes_per_packet  = 2;
1773                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1774                         p_soun->i_bytes_per_sample  = 2;
1775                         break;
1776                     case VLC_CODEC_ALAW:
1777                     case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1778                         p_soun->i_samplesize = 8;
1779                         p_track->i_sample_size = p_soun->i_channelcount;
1780                         break;
1781                     case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1782                     case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1783                     case VLC_FOURCC( 't', 'w', 'o', 's' ):
1784                     case VLC_FOURCC( 's', 'o', 'w', 't' ):
1785                         /* What would be the fun if you could trust the .mov */
1786                         p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1787                         break;
1788                     default:
1789                         break;
1790                 }
1791
1792             }
1793             else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1794             {
1795                 p_soun->i_qt_version = 0;
1796             }
1797         }
1798         else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1799         {
1800             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1801
1802             switch( p_sample->i_type )
1803             {
1804                 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1805                 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1806                     {
1807                         if( p_track->i_sample_size > 1 )
1808                             p_soun->i_qt_version = 0;
1809                         break;
1810                     }
1811                 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1812                 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1813                 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
1814                     p_soun->i_qt_version = 0;
1815                     break;
1816                 default:
1817                     break;
1818             }
1819         }
1820
1821         if( p_track->i_sample_size != 0 &&
1822                 p_sample->data.p_sample_soun->i_qt_version == 1 &&
1823                 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
1824         {
1825             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
1826             p_sample->data.p_sample_soun->i_qt_version = 0;
1827         }
1828         break;
1829
1830     default:
1831         break;
1832     }
1833
1834
1835     /* It's a little ugly but .. there are special cases */
1836     switch( p_sample->i_type )
1837     {
1838         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1839         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1840         {
1841             p_track->fmt.i_codec = VLC_CODEC_MPGA;
1842             break;
1843         }
1844         case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1845         {
1846             MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
1847
1848             p_track->fmt.i_codec = VLC_CODEC_A52;
1849             if( p_dac3_box )
1850             {
1851                 static const int pi_bitrate[] = {
1852                      32,  40,  48,  56,
1853                      64,  80,  96, 112,
1854                     128, 160, 192, 224,
1855                     256, 320, 384, 448,
1856                     512, 576, 640,
1857                 };
1858                 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
1859                 p_track->fmt.audio.i_channels = 0;
1860                 p_track->fmt.i_bitrate = 0;
1861                 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
1862                     p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
1863                 p_track->fmt.audio.i_bitspersample = 0;
1864             }
1865             break;
1866         }
1867         case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1868         {
1869             p_track->fmt.i_codec = VLC_CODEC_EAC3;
1870             break;
1871         }
1872
1873         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1874         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
1875         {
1876             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1877
1878             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
1879                 p_track->fmt.i_codec = VLC_CODEC_U8;
1880             else
1881                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1882
1883             /* Buggy files workaround */
1884             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
1885                 p_sample->data.p_sample_soun->i_sampleratehi) )
1886             {
1887                 MP4_Box_data_sample_soun_t *p_soun =
1888                     p_sample->data.p_sample_soun;
1889
1890                 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
1891                           "(%u), making both equal (report any problem).",
1892                           p_track->i_timescale, p_soun->i_sampleratehi );
1893
1894                 if( p_soun->i_sampleratehi != 0 )
1895                     p_track->i_timescale = p_soun->i_sampleratehi;
1896                 else
1897                     p_soun->i_sampleratehi = p_track->i_timescale;
1898             }
1899             break;
1900         }
1901
1902         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1903             p_track->fmt.i_codec = VLC_CODEC_H263;
1904             break;
1905
1906         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1907         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
1908             p_track->fmt.i_codec = VLC_CODEC_SUBT;
1909             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1910             /* FIXME UTF-8 doesn't work here ? */
1911             if( p_track->b_mac_encoding )
1912                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
1913             else
1914                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
1915             break;
1916
1917         case VLC_FOURCC('y','v','1','2'):
1918             p_track->fmt.i_codec = VLC_CODEC_YV12;
1919             break;
1920         case VLC_FOURCC('y','u','v','2'):
1921             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
1922             break;
1923
1924         case VLC_FOURCC('i','n','2','4'):
1925             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1926                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
1927             break;
1928         case VLC_FOURCC('i','n','3','2'):
1929             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1930                                     VLC_CODEC_S32L : VLC_CODEC_S32B;
1931             break;
1932         case VLC_FOURCC('f','l','3','2'):
1933             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1934                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
1935             break;
1936         case VLC_FOURCC('f','l','6','4'):
1937             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1938                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
1939             break;
1940         case VLC_CODEC_DVD_LPCM:
1941         {
1942             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1943             if( p_soun->i_qt_version == 2 &&
1944                 p_soun->i_qt_description > 20 + 28 )
1945             {
1946                 /* Flags:
1947                  *  0x01: IsFloat
1948                  *  0x02: IsBigEndian
1949                  *  0x04: IsSigned
1950                  */
1951                 static const struct {
1952                     unsigned     i_flags;
1953                     unsigned     i_mask;
1954                     unsigned     i_bits;
1955                     vlc_fourcc_t i_codec;
1956                 } p_formats[] = {
1957                     { 0x01,           0x03, 32, VLC_CODEC_F32L },
1958                     { 0x01,           0x03, 64, VLC_CODEC_F64L },
1959                     { 0x01|0x02,      0x03, 32, VLC_CODEC_F32B },
1960                     { 0x01|0x02,      0x03, 64, VLC_CODEC_F64B },
1961
1962                     { 0x00,           0x05,  8, VLC_CODEC_U8 },
1963                     { 0x00|     0x04, 0x05,  8, VLC_CODEC_S8 },
1964
1965                     { 0x00,           0x07, 16, VLC_CODEC_U16L },
1966                     { 0x00|0x02,      0x07, 16, VLC_CODEC_U16B },
1967                     { 0x00     |0x04, 0x07, 16, VLC_CODEC_S16L },
1968                     { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
1969
1970                     { 0x00,           0x07, 24, VLC_CODEC_U24L },
1971                     { 0x00|0x02,      0x07, 24, VLC_CODEC_U24B },
1972                     { 0x00     |0x04, 0x07, 24, VLC_CODEC_S24L },
1973                     { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
1974
1975                     { 0x00,           0x07, 32, VLC_CODEC_U32L },
1976                     { 0x00|0x02,      0x07, 32, VLC_CODEC_U32B },
1977                     { 0x00     |0x04, 0x07, 32, VLC_CODEC_S32L },
1978                     { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
1979
1980                     {0, 0, 0, 0}
1981                 };
1982                 uint32_t i_bits  = GetDWBE(&p_soun->p_qt_description[20 + 20]);
1983                 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
1984
1985                 for( int i = 0; p_formats[i].i_codec; i++ )
1986                 {
1987                     if( p_formats[i].i_bits == i_bits &&
1988                         (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
1989                     {
1990                         p_track->fmt.i_codec = p_formats[i].i_codec;
1991                         p_track->fmt.audio.i_bitspersample = i_bits;
1992                         p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
1993                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
1994
1995                         p_soun->i_qt_version = 0;
1996                         break;
1997                     }
1998                 }
1999             }
2000             break;
2001         }
2002         default:
2003             p_track->fmt.i_codec = p_sample->i_type;
2004             break;
2005     }
2006
2007     /* now see if esds is present and if so create a data packet
2008         with decoder_specific_info  */
2009 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2010     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2011           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2012         ( p_esds->data.p_esds )&&
2013         ( p_decconfig ) )
2014     {
2015         /* First update information based on i_objectTypeIndication */
2016         switch( p_decconfig->i_objectTypeIndication )
2017         {
2018             case( 0x20 ): /* MPEG4 VIDEO */
2019                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2020                 break;
2021             case( 0x21 ): /* H.264 */
2022                 p_track->fmt.i_codec = VLC_CODEC_H264;
2023                 break;
2024             case( 0x40):
2025                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2026                 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2027                      p_decconfig->p_decoder_specific_info[0]       == 0xF8 &&
2028                     (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2029                 {
2030                     p_track->fmt.i_codec = VLC_CODEC_ALS;
2031                 }
2032                 break;
2033             case( 0x60):
2034             case( 0x61):
2035             case( 0x62):
2036             case( 0x63):
2037             case( 0x64):
2038             case( 0x65): /* MPEG2 video */
2039                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2040                 break;
2041             /* Theses are MPEG2-AAC */
2042             case( 0x66): /* main profile */
2043             case( 0x67): /* Low complexity profile */
2044             case( 0x68): /* Scaleable Sampling rate profile */
2045                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2046                 break;
2047             /* True MPEG 2 audio */
2048             case( 0x69):
2049                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2050                 break;
2051             case( 0x6a): /* MPEG1 video */
2052                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2053                 break;
2054             case( 0x6b): /* MPEG1 audio */
2055                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2056                 break;
2057             case( 0x6c ): /* jpeg */
2058                 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2059                 break;
2060             case( 0x6d ): /* png */
2061                 p_track->fmt.i_codec = VLC_CODEC_PNG;
2062                 break;
2063             case( 0x6e ): /* jpeg2000 */
2064                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2065                 break;
2066             case( 0xa3 ): /* vc1 */
2067                 p_track->fmt.i_codec = VLC_CODEC_VC1;
2068                 break;
2069             case( 0xa4 ):
2070                 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2071                 break;
2072             case( 0xa5 ):
2073                 p_track->fmt.i_codec = VLC_CODEC_A52;
2074                 break;
2075             case( 0xa6 ):
2076                 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2077                 break;
2078             case( 0xa9 ): /* dts */
2079             case( 0xaa ): /* DTS-HD HRA */
2080             case( 0xab ): /* DTS-HD Master Audio */
2081                 p_track->fmt.i_codec = VLC_CODEC_DTS;
2082                 break;
2083             case( 0xDD ):
2084                 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2085                 break;
2086
2087             /* Private ID */
2088             case( 0xe0 ): /* NeroDigital: dvd subs */
2089                 if( p_track->fmt.i_cat == SPU_ES )
2090                 {
2091                     p_track->fmt.i_codec = VLC_CODEC_SPU;
2092                     if( p_track->i_width > 0 )
2093                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2094                     if( p_track->i_height > 0 )
2095                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2096                     break;
2097                 }
2098             case( 0xe1 ): /* QCelp for 3gp */
2099                 if( p_track->fmt.i_cat == AUDIO_ES )
2100                 {
2101                     p_track->fmt.i_codec = VLC_CODEC_QCELP;
2102                 }
2103                 break;
2104
2105             /* Fallback */
2106             default:
2107                 /* Unknown entry, but don't touch i_fourcc */
2108                 msg_Warn( p_demux,
2109                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2110                           p_decconfig->i_objectTypeIndication,
2111                           p_track->i_track_ID );
2112                 break;
2113         }
2114         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2115         if( p_track->fmt.i_extra > 0 )
2116         {
2117             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2118             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2119                     p_track->fmt.i_extra );
2120         }
2121     }
2122     else
2123     {
2124         switch( p_sample->i_type )
2125         {
2126             /* qt decoder, send the complete chunk */
2127             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2128             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2129             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2130             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2131             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2132             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2133             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2134             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2135             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2136             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2137             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2138             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2139                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2140                 break;
2141             /* qt decoder, send the complete chunk */
2142             case VLC_CODEC_SVQ1:
2143             case VLC_CODEC_SVQ3:
2144             case VLC_FOURCC( 'V', 'P', '3', '1' ):
2145             case VLC_FOURCC( '3', 'I', 'V', '1' ):
2146             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2147                 p_track->fmt.i_extra =
2148                     p_sample->data.p_sample_vide->i_qt_image_description;
2149                 if( p_track->fmt.i_extra > 0 )
2150                 {
2151                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2152                     memcpy( p_track->fmt.p_extra,
2153                             p_sample->data.p_sample_vide->p_qt_image_description,
2154                             p_track->fmt.i_extra);
2155                 }
2156                 break;
2157
2158             case VLC_CODEC_AMR_NB:
2159                 p_track->fmt.audio.i_rate = 8000;
2160                 break;
2161             case VLC_CODEC_AMR_WB:
2162                 p_track->fmt.audio.i_rate = 16000;
2163                 break;
2164             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2165             case VLC_CODEC_QDM2:
2166             case VLC_CODEC_ALAC:
2167                 p_track->fmt.i_extra =
2168                     p_sample->data.p_sample_soun->i_qt_description;
2169                 if( p_track->fmt.i_extra > 0 )
2170                 {
2171                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2172                     memcpy( p_track->fmt.p_extra,
2173                             p_sample->data.p_sample_soun->p_qt_description,
2174                             p_track->fmt.i_extra);
2175                 }
2176                 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2177                 {
2178                     p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2179                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2180                 }
2181                 break;
2182
2183             case VLC_FOURCC( 'v', 'c', '-', '1' ):
2184             {
2185                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2186                 if( p_dvc1 )
2187                 {
2188                     p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2189                     if( p_track->fmt.i_extra > 0 )
2190                     {
2191                         p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2192                         memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2193                                 p_track->fmt.i_extra );
2194                     }
2195                 }
2196                 else
2197                 {
2198                     msg_Err( p_demux, "missing dvc1" );
2199                 }
2200                 break;
2201             }
2202
2203             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2204             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2205             {
2206                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2207
2208                 if( p_avcC )
2209                 {
2210                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2211                     if( p_track->fmt.i_extra > 0 )
2212                     {
2213                         p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2214                         memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2215                                 p_track->fmt.i_extra );
2216                     }
2217                 }
2218                 else
2219                 {
2220                     msg_Err( p_demux, "missing avcC" );
2221                 }
2222                 break;
2223             }
2224             case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2225             {
2226                 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2227
2228                 if( p_hvcC )
2229                 {
2230                     p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2231                     if( p_track->fmt.i_extra > 0 )
2232                     {
2233                         p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2234                         memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2235                                 p_track->fmt.i_extra );
2236                     }
2237                     p_track->fmt.i_codec = VLC_CODEC_HEVC;
2238                 }
2239                 else
2240                 {
2241                     msg_Err( p_demux, "missing hvcC" );
2242                 }
2243                 break;
2244             }
2245
2246
2247             case VLC_CODEC_ADPCM_MS:
2248             case VLC_CODEC_ADPCM_IMA_WAV:
2249             case VLC_CODEC_QCELP:
2250                 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2251                 break;
2252
2253             default:
2254                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2255                 break;
2256         }
2257     }
2258
2259 #undef p_decconfig
2260
2261     if( pp_es )
2262         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2263
2264     return VLC_SUCCESS;
2265 }
2266
2267 /* given a time it return sample/chunk
2268  * it also update elst field of the track
2269  */
2270 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2271                                    int64_t i_start, uint32_t *pi_chunk,
2272                                    uint32_t *pi_sample )
2273 {
2274     demux_sys_t *p_sys = p_demux->p_sys;
2275     MP4_Box_t   *p_box_stss;
2276     uint64_t     i_dts;
2277     unsigned int i_sample;
2278     unsigned int i_chunk;
2279     int          i_index;
2280
2281     /* FIXME see if it's needed to check p_track->i_chunk_count */
2282     if( p_track->i_chunk_count == 0 )
2283         return( VLC_EGENERIC );
2284
2285     /* handle elst (find the correct one) */
2286     MP4_TrackSetELST( p_demux, p_track, i_start );
2287     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2288     {
2289         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2290         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
2291
2292         /* now calculate i_start for this elst */
2293         /* offset */
2294         i_start -= p_track->i_elst_time * INT64_C(1000000) / p_sys->i_timescale;
2295         if( i_start < 0 )
2296         {
2297             *pi_chunk = 0;
2298             *pi_sample= 0;
2299
2300             return VLC_SUCCESS;
2301         }
2302         /* to track time scale */
2303         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
2304         /* add elst offset */
2305         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2306              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2307             elst->i_media_time[p_track->i_elst] > 0 )
2308         {
2309             i_start += elst->i_media_time[p_track->i_elst];
2310         }
2311
2312         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2313                  "ms (track)", p_track->i_elst,
2314                  i_mvt * 1000 / p_sys->i_timescale,
2315                  i_start * 1000 / p_track->i_timescale );
2316     }
2317     else
2318     {
2319         /* convert absolute time to in timescale unit */
2320         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
2321     }
2322
2323     /* we start from sample 0/chunk 0, hope it won't take too much time */
2324     /* *** find good chunk *** */
2325     for( i_chunk = 0; ; i_chunk++ )
2326     {
2327         if( i_chunk + 1 >= p_track->i_chunk_count )
2328         {
2329             /* at the end and can't check if i_start in this chunk,
2330                it will be check while searching i_sample */
2331             i_chunk = p_track->i_chunk_count - 1;
2332             break;
2333         }
2334
2335         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2336             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
2337         {
2338             break;
2339         }
2340     }
2341
2342     /* *** find sample in the chunk *** */
2343     i_sample = p_track->chunk[i_chunk].i_sample_first;
2344     i_dts    = p_track->chunk[i_chunk].i_first_dts;
2345     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2346     {
2347         if( i_dts +
2348             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2349             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2350         {
2351             i_dts    +=
2352                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2353                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2354
2355             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2356             i_index++;
2357         }
2358         else
2359         {
2360             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2361             {
2362                 break;
2363             }
2364             i_sample += ( i_start - i_dts ) /
2365                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2366             break;
2367         }
2368     }
2369
2370     if( i_sample >= p_track->i_sample_count )
2371     {
2372         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2373                   "(seeking too far) chunk=%d sample=%d",
2374                   p_track->i_track_ID, i_chunk, i_sample );
2375         return( VLC_EGENERIC );
2376     }
2377
2378
2379     /* *** Try to find nearest sync points *** */
2380     if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2381     {
2382         MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2383         msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2384                  p_track->i_track_ID );
2385         for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2386         {
2387             if( i_index >= p_stss->i_entry_count - 1 ||
2388                 i_sample < p_stss->i_sample_number[i_index+1] )
2389             {
2390                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2391                 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2392                          i_sample, i_sync_sample );
2393
2394                 if( i_sync_sample <= i_sample )
2395                 {
2396                     while( i_chunk > 0 &&
2397                            i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2398                         i_chunk--;
2399                 }
2400                 else
2401                 {
2402                     while( i_chunk < p_track->i_chunk_count - 1 &&
2403                            i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2404                                             p_track->chunk[i_chunk].i_sample_count )
2405                         i_chunk++;
2406                 }
2407                 i_sample = i_sync_sample;
2408                 break;
2409             }
2410         }
2411     }
2412     else
2413     {
2414         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2415                  "Sample Box (stss)", p_track->i_track_ID );
2416     }
2417
2418     *pi_chunk  = i_chunk;
2419     *pi_sample = i_sample;
2420
2421     return VLC_SUCCESS;
2422 }
2423
2424 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2425                                  unsigned int i_chunk, unsigned int i_sample )
2426 {
2427     bool b_reselect = false;
2428
2429     /* now see if actual es is ok */
2430     if( p_track->i_chunk >= p_track->i_chunk_count ||
2431         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2432             p_track->chunk[i_chunk].i_sample_description_index )
2433     {
2434         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2435                   p_track->i_track_ID );
2436
2437         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2438                         p_track->p_es, &b_reselect );
2439
2440         es_out_Del( p_demux->out, p_track->p_es );
2441
2442         p_track->p_es = NULL;
2443
2444         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2445         {
2446             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2447                      p_track->i_track_ID );
2448
2449             p_track->b_ok       = false;
2450             p_track->b_selected = false;
2451             return VLC_EGENERIC;
2452         }
2453     }
2454
2455     /* select again the new decoder */
2456     if( b_reselect )
2457     {
2458         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2459     }
2460
2461     p_track->i_chunk    = i_chunk;
2462     p_track->i_sample   = i_sample;
2463
2464     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2465 }
2466
2467 /****************************************************************************
2468  * MP4_TrackCreate:
2469  ****************************************************************************
2470  * Parse track information and create all needed data to run a track
2471  * If it succeed b_ok is set to 1 else to 0
2472  ****************************************************************************/
2473 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2474                              MP4_Box_t *p_box_trak,
2475                              bool b_force_enable )
2476 {
2477     demux_sys_t *p_sys = p_demux->p_sys;
2478
2479     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2480     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2481     MP4_Box_t *p_elst;
2482
2483     MP4_Box_t *p_mdhd;
2484     MP4_Box_t *p_udta;
2485     MP4_Box_t *p_hdlr;
2486
2487     MP4_Box_t *p_vmhd;
2488     MP4_Box_t *p_smhd;
2489
2490     char language[4] = { '\0' };
2491
2492     /* hint track unsupported */
2493
2494     /* set default value (-> track unusable) */
2495     p_track->b_ok       = false;
2496     p_track->b_enable   = false;
2497     p_track->b_selected = false;
2498     p_track->b_chapter  = false;
2499     p_track->b_mac_encoding = false;
2500
2501     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2502
2503     if( !p_tkhd )
2504     {
2505         return;
2506     }
2507
2508     /* do we launch this track by default ? */
2509     p_track->b_enable =
2510         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2511     if( !p_track->b_enable )
2512         p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2513
2514     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2515
2516     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
2517     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
2518     p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2519
2520     if( p_tref )
2521     {
2522 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2523     }
2524
2525     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2526     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2527
2528     if( ( !p_mdhd )||( !p_hdlr ) )
2529     {
2530         return;
2531     }
2532
2533     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2534     if( p_track->i_timescale == 0 )
2535         return;
2536
2537     if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2538     {
2539         strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2540         p_track->b_mac_encoding = true;
2541     }
2542     else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2543         p_track->b_mac_encoding = true;
2544     else
2545     {
2546         for( unsigned i = 0; i < 3; i++ )
2547             language[i] = p_mdhd->data.p_mdhd->i_language[i];
2548         language[3] = '\0';
2549     }
2550
2551     switch( p_hdlr->data.p_hdlr->i_handler_type )
2552     {
2553         case( ATOM_soun ):
2554             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2555             {
2556                 return;
2557             }
2558             p_track->fmt.i_cat = AUDIO_ES;
2559             break;
2560
2561         case( ATOM_vide ):
2562             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2563             {
2564                 return;
2565             }
2566             p_track->fmt.i_cat = VIDEO_ES;
2567             break;
2568
2569         case( ATOM_text ):
2570         case( ATOM_subp ):
2571         case( ATOM_tx3g ):
2572         case( ATOM_sbtl ):
2573             p_track->fmt.i_cat = SPU_ES;
2574             break;
2575
2576         default:
2577             return;
2578     }
2579
2580     p_track->i_elst = 0;
2581     p_track->i_elst_time = 0;
2582     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2583     {
2584         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2585         unsigned int i;
2586
2587         msg_Warn( p_demux, "elst box found" );
2588         for( i = 0; i < elst->i_entry_count; i++ )
2589         {
2590             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
2591                      "ms) rate=%d.%d", i,
2592                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2593                      elst->i_media_time[i] >= 0 ?
2594                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2595                      INT64_C(-1),
2596                      elst->i_media_rate_integer[i],
2597                      elst->i_media_rate_fraction[i] );
2598         }
2599     }
2600
2601
2602 /*  TODO
2603     add support for:
2604     p_dinf = MP4_BoxGet( p_minf, "dinf" );
2605 */
2606     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2607         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2608     {
2609         return;
2610     }
2611
2612     /* Set language */
2613     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2614     {
2615         p_track->fmt.psz_language = strdup( language );
2616     }
2617
2618     p_udta = MP4_BoxGet( p_box_trak, "udta" );
2619     if( p_udta )
2620     {
2621         MP4_Box_t *p_box_iter;
2622         for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2623                  p_box_iter = p_box_iter->p_next )
2624         {
2625             switch( p_box_iter->i_type )
2626             {
2627                 case ATOM_0xa9nam:
2628                     p_track->fmt.psz_description =
2629                         strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2630                     break;
2631                 case ATOM_name:
2632                     p_track->fmt.psz_description =
2633                         strdup( p_box_iter->data.p_name->psz_text );
2634                     break;
2635             }
2636         }
2637     }
2638
2639     /* Create chunk index table and sample index table */
2640     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
2641         TrackCreateSamplesIndex( p_demux, p_track ) )
2642     {
2643         return; /* cannot create chunks index */
2644     }
2645
2646     p_track->i_chunk  = 0;
2647     p_track->i_sample = 0;
2648
2649     /* Mark chapter only track */
2650     if( p_sys->p_tref_chap )
2651     {
2652         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2653         unsigned int i;
2654
2655         for( i = 0; i < p_chap->i_entry_count; i++ )
2656         {
2657             if( p_track->i_track_ID == p_chap->i_track_ID[i] )
2658             {
2659                 p_track->b_chapter = true;
2660                 p_track->b_enable = false;
2661                 break;
2662             }
2663         }
2664     }
2665
2666     /* now create es */
2667     if( b_force_enable &&
2668         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2669     {
2670         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2671                   p_track->i_track_ID );
2672         p_track->b_enable = true;
2673         p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2674     }
2675
2676     p_track->p_es = NULL;
2677     if( TrackCreateES( p_demux,
2678                        p_track, p_track->i_chunk,
2679                        p_track->b_chapter ? NULL : &p_track->p_es ) )
2680     {
2681         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2682                  p_track->i_track_ID );
2683         return;
2684     }
2685     p_track->b_ok = true;
2686 #if 0
2687     {
2688         int i;
2689         for( i = 0; i < p_track->i_chunk_count; i++ )
2690         {
2691             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2692                      i, p_track->chunk[i].i_sample_count,
2693                      p_track->chunk[i].i_first_dts );
2694
2695         }
2696     }
2697 #endif
2698 }
2699
2700 static void FreeAndResetChunk( mp4_chunk_t *ck )
2701 {
2702     free( ck->p_sample_count_dts );
2703     free( ck->p_sample_delta_dts );
2704     free( ck->p_sample_count_pts );
2705     free( ck->p_sample_offset_pts );
2706     free( ck->p_sample_size );
2707     for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2708         free( ck->p_sample_data[i] );
2709     free( ck->p_sample_data );
2710     memset( ck, 0, sizeof( mp4_chunk_t ) );
2711 }
2712
2713 /****************************************************************************
2714  * MP4_TrackDestroy:
2715  ****************************************************************************
2716  * Destroy a track created by MP4_TrackCreate.
2717  ****************************************************************************/
2718 static void MP4_TrackDestroy( mp4_track_t *p_track )
2719 {
2720     unsigned int i_chunk;
2721
2722     p_track->b_ok = false;
2723     p_track->b_enable   = false;
2724     p_track->b_selected = false;
2725
2726     es_format_Clean( &p_track->fmt );
2727
2728     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2729     {
2730         if( p_track->chunk )
2731         {
2732            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2733            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2734
2735            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2736            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2737         }
2738     }
2739     FREENULL( p_track->chunk );
2740     if( p_track->cchunk ) {
2741         FreeAndResetChunk( p_track->cchunk );
2742         FREENULL( p_track->cchunk );
2743     }
2744
2745     if( !p_track->i_sample_size )
2746     {
2747         FREENULL( p_track->p_sample_size );
2748     }
2749 }
2750
2751 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2752                             mtime_t i_start )
2753 {
2754     if( !p_track->b_ok || p_track->b_chapter )
2755     {
2756         return VLC_EGENERIC;
2757     }
2758
2759     if( p_track->b_selected )
2760     {
2761         msg_Warn( p_demux, "track[Id 0x%x] already selected",
2762                   p_track->i_track_ID );
2763         return VLC_SUCCESS;
2764     }
2765
2766     return MP4_TrackSeek( p_demux, p_track, i_start );
2767 }
2768
2769 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2770 {
2771     if( !p_track->b_ok || p_track->b_chapter )
2772     {
2773         return;
2774     }
2775
2776     if( !p_track->b_selected )
2777     {
2778         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2779                   p_track->i_track_ID );
2780         return;
2781     }
2782     if( p_track->p_es )
2783     {
2784         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2785                         p_track->p_es, false );
2786     }
2787
2788     p_track->b_selected = false;
2789 }
2790
2791 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2792                           mtime_t i_start )
2793 {
2794     uint32_t i_chunk;
2795     uint32_t i_sample;
2796
2797     if( !p_track->b_ok || p_track->b_chapter )
2798         return VLC_EGENERIC;
2799
2800     p_track->b_selected = false;
2801
2802     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2803                                 &i_chunk, &i_sample ) )
2804     {
2805         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2806                   p_track->i_track_ID );
2807         return VLC_EGENERIC;
2808     }
2809
2810     p_track->b_selected = true;
2811
2812     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
2813         p_track->b_selected = true;
2814
2815     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2816 }
2817
2818
2819 /*
2820  * 3 types: for audio
2821  *
2822  */
2823 #define QT_V0_MAX_SAMPLES 1024
2824 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2825 {
2826     int i_size;
2827     MP4_Box_data_sample_soun_t *p_soun;
2828
2829     if( p_track->i_sample_size == 0 )
2830     {
2831         /* most simple case */
2832         return p_track->p_sample_size[p_track->i_sample];
2833     }
2834     if( p_track->fmt.i_cat != AUDIO_ES )
2835     {
2836         return p_track->i_sample_size;
2837     }
2838
2839     p_soun = p_track->p_sample->data.p_sample_soun;
2840
2841     if( p_soun->i_qt_version == 1 )
2842     {
2843         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
2844         if( p_track->fmt.audio.i_blockalign > 1 )
2845             i_samples = p_soun->i_sample_per_packet;
2846
2847         i_size = i_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2848     }
2849     else if( p_track->i_sample_size > 256 )
2850     {
2851         /* We do that so we don't read too much data
2852          * (in this case we are likely dealing with compressed data) */
2853         i_size = p_track->i_sample_size;
2854     }
2855     else
2856     {
2857         /* Read a bunch of samples at once */
2858         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2859             ( p_track->i_sample -
2860               p_track->chunk[p_track->i_chunk].i_sample_first );
2861
2862         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2863         i_size = i_samples * p_track->i_sample_size;
2864     }
2865
2866     //fprintf( stderr, "size=%d\n", i_size );
2867     return i_size;
2868 }
2869
2870 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2871 {
2872     unsigned int i_sample;
2873     uint64_t i_pos;
2874
2875     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2876
2877     if( p_track->i_sample_size )
2878     {
2879         MP4_Box_data_sample_soun_t *p_soun =
2880             p_track->p_sample->data.p_sample_soun;
2881
2882         if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
2883         {
2884             i_pos += ( p_track->i_sample -
2885                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2886                      p_track->i_sample_size;
2887         }
2888         else
2889         {
2890             /* we read chunk by chunk unless a blockalign is requested */
2891             if( p_track->fmt.audio.i_blockalign > 1 )
2892                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
2893                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2894         }
2895     }
2896     else
2897     {
2898         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2899              i_sample < p_track->i_sample; i_sample++ )
2900         {
2901             i_pos += p_track->p_sample_size[i_sample];
2902         }
2903     }
2904
2905     return i_pos;
2906 }
2907
2908 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2909 {
2910     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2911     {
2912         MP4_Box_data_sample_soun_t *p_soun;
2913
2914         p_soun = p_track->p_sample->data.p_sample_soun;
2915
2916         if( p_soun->i_qt_version == 1 )
2917         {
2918             /* we read chunk by chunk unless a blockalign is requested */
2919             if( p_track->fmt.audio.i_blockalign > 1 )
2920                 p_track->i_sample += p_soun->i_sample_per_packet;
2921             else
2922                 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
2923         }
2924         else if( p_track->i_sample_size > 256 )
2925         {
2926             /* We do that so we don't read too much data
2927              * (in this case we are likely dealing with compressed data) */
2928             p_track->i_sample += 1;
2929         }
2930         else
2931         {
2932             /* FIXME */
2933             p_track->i_sample += QT_V0_MAX_SAMPLES;
2934             if( p_track->i_sample >
2935                 p_track->chunk[p_track->i_chunk].i_sample_first +
2936                 p_track->chunk[p_track->i_chunk].i_sample_count )
2937             {
2938                 p_track->i_sample =
2939                     p_track->chunk[p_track->i_chunk].i_sample_first +
2940                     p_track->chunk[p_track->i_chunk].i_sample_count;
2941             }
2942         }
2943     }
2944     else
2945     {
2946         p_track->i_sample++;
2947     }
2948
2949     if( p_track->i_sample >= p_track->i_sample_count )
2950         return VLC_EGENERIC;
2951
2952     /* Have we changed chunk ? */
2953     if( p_track->i_sample >=
2954             p_track->chunk[p_track->i_chunk].i_sample_first +
2955             p_track->chunk[p_track->i_chunk].i_sample_count )
2956     {
2957         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2958                                   p_track->i_sample ) )
2959         {
2960             msg_Warn( p_demux, "track[0x%x] will be disabled "
2961                       "(cannot restart decoder)", p_track->i_track_ID );
2962             MP4_TrackUnselect( p_demux, p_track );
2963             return VLC_EGENERIC;
2964         }
2965     }
2966
2967     /* Have we changed elst */
2968     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2969     {
2970         demux_sys_t *p_sys = p_demux->p_sys;
2971         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2972         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2973                         p_sys->i_timescale / (int64_t)1000000;
2974
2975         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
2976             i_mvt >= p_track->i_elst_time +
2977                      elst->i_segment_duration[p_track->i_elst] )
2978         {
2979             MP4_TrackSetELST( p_demux, p_track,
2980                               MP4_TrackGetDTS( p_demux, p_track ) );
2981         }
2982     }
2983
2984     return VLC_SUCCESS;
2985 }
2986
2987 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2988                               int64_t i_time )
2989 {
2990     demux_sys_t *p_sys = p_demux->p_sys;
2991     int         i_elst_last = tk->i_elst;
2992
2993     /* handle elst (find the correct one) */
2994     tk->i_elst      = 0;
2995     tk->i_elst_time = 0;
2996     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2997     {
2998         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2999         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
3000
3001         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3002         {
3003             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3004
3005             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3006             {
3007                 break;
3008             }
3009             tk->i_elst_time += i_dur;
3010         }
3011
3012         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3013         {
3014             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3015             tk->i_elst = elst->i_entry_count - 1;
3016             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3017         }
3018
3019         if( elst->i_media_time[tk->i_elst] < 0 )
3020         {
3021             /* track offset */
3022             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3023         }
3024     }
3025     if( i_elst_last != tk->i_elst )
3026     {
3027         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3028     }
3029 }
3030
3031 /* */
3032 static const char *MP4_ConvertMacCode( uint16_t i_code )
3033 {
3034     static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3035         { "en",   0 }, { "fr",   1 }, { "de",   2 }, { "it",   3 }, { "nl",   4 },
3036         { "sv",   5 }, { "es",   6 }, { "da",   7 }, { "pt",   8 }, { "no",   9 },
3037         { "he",  10 }, { "ja",  11 }, { "ar",  12 }, { "fi",  13 }, { "el",  14 },
3038         { "is",  15 }, { "mt",  16 }, { "tr",  17 }, { "hr",  18 }, { "zh",  19 },
3039         { "ur",  20 }, { "hi",  21 }, { "th",  22 }, { "ko",  23 }, { "lt",  24 },
3040         { "pl",  25 }, { "hu",  26 }, { "et",  27 }, { "lv",  28 }, //{ "??",  29 },
3041         { "fo",  30 }, { "fa",  31 }, { "ru",  32 }, { "zh",  33 }, { "nl",  34 },
3042         { "ga",  35 }, { "sq",  36 }, { "ro",  37 }, { "cs",  38 }, { "sk",  39 },
3043         { "sl",  40 }, { "yi",  41 }, { "sr",  42 }, { "mk",  43 }, { "bg",  44 },
3044         { "uk",  45 }, { "be",  46 }, { "uz",  47 }, { "az",  48 }, { "kk",  48 },
3045         { "az",  50 }, { "hy",  51 }, { "ka",  52 }, { "mo",  53 }, { "ky",  54 },
3046         { "tg",  55 }, { "tk",  56 }, { "mn",  57 }, { "mn",  58 }, { "ps",  59 },
3047         { "ku",  60 }, { "ks",  61 }, { "sd",  62 }, { "bo",  63 }, { "ne",  64 },
3048         { "sa",  65 }, { "mr",  66 }, { "bn",  67 }, { "as",  68 }, { "gu",  69 },
3049         { "pa",  70 }, { "or",  71 }, { "ml",  72 }, { "kn",  73 }, { "ta",  74 },
3050         { "te",  75 }, { "si",  76 }, { "my",  77 }, { "km",  78 }, { "lo",  79 },
3051         { "vi",  80 }, { "id",  81 }, { "tl",  82 }, { "ms",  83 }, { "ms",  84 },
3052         { "am",  85 }, { "ti",  86 }, { "om",  87 }, { "so",  88 }, { "sw",  89 },
3053         { "rw",  90 }, { "rn",  91 }, { "ny",  92 }, { "mg",  93 }, { "eo",  94 },
3054
3055                                                      { "cy", 128 }, { "eu", 129 },
3056         { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3057         { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3058         { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3059         { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3060         /* */
3061         { "", 0 }
3062     };
3063     int i;
3064     for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3065     {
3066         if( p_cvt[i].i_code == i_code )
3067             return p_cvt[i].psz_iso639_1;
3068     }
3069     return "";
3070 }
3071
3072 /******************************************************************************
3073  *     Here are the functions used for fragmented MP4
3074  *****************************************************************************/
3075
3076 /**
3077  * It computes the sample rate for a video track using current video chunk
3078  */
3079 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3080                                   const mp4_track_t *p_track )
3081 {
3082     if( p_track->cchunk->i_last_dts == 0 )
3083         return;
3084
3085     *pi_num = 0;
3086     *pi_den = 0;
3087
3088     /* */
3089     const mp4_chunk_t *p_chunk = p_track->cchunk;
3090
3091     uint32_t i_sample = p_chunk->i_sample_count;
3092     uint64_t i_first_dts = p_chunk->i_first_dts;
3093     uint64_t i_last_dts =  p_chunk->i_last_dts;
3094
3095     if( i_sample > 1 && i_first_dts < i_last_dts )
3096         vlc_ureduce( pi_num, pi_den,
3097                      ( i_sample - 1) *  p_track->i_timescale,
3098                      i_last_dts - i_first_dts,
3099                      UINT16_MAX);
3100 }
3101
3102 /**
3103  * Build raw avcC box (without the 8 bytes header)
3104  * \return The size of the box.
3105  */
3106 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3107                                                        const unsigned cpd_len )
3108 {
3109     uint8_t *avcC;
3110     unsigned sps_len = 0, pps_len = 0;
3111     const uint32_t mark = 0x00000001;
3112
3113     assert( CodecPrivateData[0] == 0 );
3114     assert( CodecPrivateData[1] == 0 );
3115     assert( CodecPrivateData[2] == 0 );
3116     assert( CodecPrivateData[3] == 1 );
3117
3118     uint32_t length = cpd_len + 3;
3119     avcC = calloc( length, 1 );
3120     if( unlikely( avcC == NULL ) )
3121         return 0;
3122
3123     uint8_t *sps = avcC + 8;
3124
3125     uint32_t candidate = ~mark;
3126     CodecPrivateData += 4;
3127     for( unsigned i = 0; i < cpd_len - 4; i++ )
3128     {
3129         sps[i] = CodecPrivateData[i];
3130         candidate = (candidate << 8) | CodecPrivateData[i];
3131         if( candidate == mark )
3132         {
3133             sps_len = i - 3;
3134             break;
3135         }
3136     }
3137     if( sps_len == 0 )
3138     {
3139         free( avcC );
3140         return 0;
3141     }
3142     uint8_t *pps = sps + sps_len + 3;
3143     pps_len = cpd_len - sps_len - 4 * 2;
3144     memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3145
3146     /* XXX */
3147     uint8_t AVCProfileIndication = 0x64;
3148     uint8_t profile_compatibility = 0x40;
3149     uint8_t AVCLevelIndication = 0x1f;
3150     uint8_t lengthSizeMinusOne = 0x03;
3151
3152     avcC[0] = 1;
3153     avcC[1] = AVCProfileIndication;
3154     avcC[2] = profile_compatibility;
3155     avcC[3] = AVCLevelIndication;
3156     avcC[4] = 0xfc + lengthSizeMinusOne;
3157     avcC[5] = 0xe0 + 1;
3158     avcC[6] = (sps_len & 0xff00)>>8;
3159     avcC[7] = sps_len & 0xff;
3160
3161     avcC[8+sps_len] = 1;
3162     avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3163     avcC[10+sps_len] = pps_len & 0xff;
3164
3165     *p_extra = avcC;
3166     return length;
3167 }
3168
3169 /**
3170  * Build a mp4_track_t from a StraBox
3171  */
3172
3173 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3174 {
3175     fmt->i_extra = p_data->cpd_len;
3176     fmt->p_extra = malloc( p_data->cpd_len );
3177     if( unlikely( !fmt->p_extra ) )
3178         return VLC_ENOMEM;
3179     memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3180     return VLC_SUCCESS;
3181   }
3182
3183 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3184 {
3185     demux_sys_t *p_sys = p_demux->p_sys;
3186     int ret;
3187     MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3188     if( !p_data )
3189         return VLC_EGENERIC;
3190
3191     p_track->b_ok       = true;
3192     p_track->b_selected = false;
3193     p_track->i_sample_count = UINT32_MAX;
3194
3195     p_track->i_timescale = p_sys->i_timescale;
3196     p_track->i_width = p_data->MaxWidth;
3197     p_track->i_height = p_data->MaxHeight;
3198     p_track->i_track_ID = p_data->i_track_ID;
3199
3200     es_format_t *fmt = &p_track->fmt;
3201     if( fmt == NULL )
3202         return VLC_EGENERIC;
3203
3204     es_format_Init( fmt, p_data->i_es_cat, 0 );
3205
3206     /* Set language FIXME */
3207     fmt->psz_language = strdup( "en" );
3208
3209     fmt->i_original_fourcc = p_data->FourCC;
3210     fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3211
3212     uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3213     /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3214      * for MS weird use of FourCC*/
3215     switch( fmt->i_cat )
3216     {
3217         case VIDEO_ES:
3218             if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3219                 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3220                 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3221             {
3222                 fmt->i_extra = build_raw_avcC( p_extra,
3223                         p_data->CodecPrivateData, p_data->cpd_len );
3224             }
3225             else
3226             {
3227                 ret = MP4_SetCodecExtraData( fmt, p_data );
3228                 if( ret != VLC_SUCCESS )
3229                     return ret;
3230             }
3231
3232             fmt->video.i_width = p_data->MaxWidth;
3233             fmt->video.i_height = p_data->MaxHeight;
3234             fmt->video.i_bits_per_pixel = 0x18;
3235             fmt->video.i_visible_width = p_data->MaxWidth;
3236             fmt->video.i_visible_height = p_data->MaxHeight;
3237
3238             /* Frame rate */
3239             ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3240                                   &fmt->video.i_frame_rate_base, p_track );
3241
3242             if( fmt->video.i_frame_rate_base != 0 )
3243             {
3244                 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3245                                         (float)fmt->video.i_frame_rate_base;
3246             }
3247             else
3248                 p_demux->p_sys->f_fps = 24;
3249
3250             break;
3251
3252         case AUDIO_ES:
3253             fmt->audio.i_channels = p_data->Channels;
3254             fmt->audio.i_rate = p_data->SamplingRate;
3255             fmt->audio.i_bitspersample = p_data->BitsPerSample;
3256             fmt->audio.i_blockalign = p_data->nBlockAlign;
3257
3258             fmt->i_bitrate = p_data->Bitrate;
3259
3260             ret = MP4_SetCodecExtraData( fmt, p_data );
3261             if( ret != VLC_SUCCESS )
3262                 return ret;
3263
3264             break;
3265
3266         default:
3267             break;
3268     }
3269
3270     return VLC_SUCCESS;
3271 }
3272
3273 /**
3274  * Return the track identified by tid
3275  */
3276 static mp4_track_t *MP4_frg_GetTrack( demux_t *p_demux, const uint32_t tid )
3277 {
3278     demux_sys_t *p_sys = p_demux->p_sys;
3279
3280     mp4_track_t *ret = NULL;
3281     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3282     {
3283         ret = &p_sys->track[i];
3284         if( !ret )
3285             return NULL;
3286         if( ret->i_track_ID == tid )
3287             return ret;
3288     }
3289     msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3290     return NULL;
3291 }
3292
3293 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3294 {
3295     msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3296     mp4_chunk_t *ck = tk->cchunk;
3297     while( ck->i_sample < ck->i_sample_count )
3298     {
3299         block_t *p_block;
3300         int64_t i_delta;
3301
3302         if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3303             return;
3304
3305         uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3306         assert( sample_size > 0 );
3307         p_block = block_Alloc( sample_size );
3308         if( unlikely( !p_block ) )
3309             return;
3310
3311         uint8_t *src = ck->p_sample_data[ck->i_sample];
3312         memcpy( p_block->p_buffer, src, sample_size );
3313         ck->i_sample++;
3314
3315         /* dts */
3316         p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3317         /* pts */
3318         i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3319         if( i_delta != -1 )
3320             p_block->i_pts = p_block->i_dts + i_delta;
3321         else if( tk->fmt.i_cat != VIDEO_ES )
3322             p_block->i_pts = p_block->i_dts;
3323         else
3324             p_block->i_pts = VLC_TS_INVALID;
3325
3326         es_out_Send( p_demux->out, tk->p_es, p_block );
3327
3328         tk->i_sample++;
3329     }
3330 }
3331
3332 /**
3333  * Re-init decoder.
3334  * \Note If we call that function too soon,
3335  * before the track has been selected by MP4_TrackSelect
3336  * (during the first execution of Demux), then the track gets disabled
3337  */
3338 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3339 {
3340     demux_sys_t *p_sys = p_demux->p_sys;
3341
3342     uint32_t i_sample = 0;
3343     bool b_smooth = false;
3344     MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3345
3346     if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3347         b_smooth = true;
3348
3349     if( b_smooth )
3350     {
3351         p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3352         if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3353             return VLC_EGENERIC;
3354     }
3355     else /* DASH */
3356     {
3357         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3358         if( !p_trak )
3359             return VLC_EGENERIC;
3360     }
3361
3362     i_sample = p_track->i_sample;
3363     es_out_Del( p_demux->out, p_track->p_es );
3364     es_format_Clean( &p_track->fmt );
3365
3366     if( b_smooth )
3367         MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3368     else /* DASH */
3369         MP4_TrackCreate( p_demux, p_track, p_trak, true );
3370
3371     p_track->i_sample = i_sample;
3372
3373     /* Temporary hack until we support track selection */
3374     p_track->b_selected = true;
3375     p_track->b_ok = true;
3376     p_track->b_enable = true;
3377
3378     p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3379     p_track->b_codec_need_restart = false;
3380
3381     return VLC_SUCCESS;
3382 }
3383
3384 /**
3385  * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3386  * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3387  * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3388  * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3389  */
3390 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3391 {
3392     MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3393     MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3394     if( p_moof == NULL)
3395     {
3396         msg_Warn( p_demux, "no moof box found!" );
3397         return VLC_EGENERIC;
3398     }
3399
3400     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3401     if( p_traf == NULL)
3402     {
3403         msg_Warn( p_demux, "no traf box found!" );
3404         return VLC_EGENERIC;
3405     }
3406
3407     MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3408     if( p_tfhd == NULL)
3409     {
3410         msg_Warn( p_demux, "no tfhd box found!" );
3411         return VLC_EGENERIC;
3412     }
3413
3414     uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3415     *i_tk_id = i_track_ID;
3416     assert( i_track_ID > 0 );
3417     msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3418
3419     mp4_track_t *p_track = MP4_frg_GetTrack( p_demux, i_track_ID );
3420     if( !p_track )
3421         return VLC_EGENERIC;
3422
3423     mp4_chunk_t *ret = p_track->cchunk;
3424
3425     if( p_tfhd->data.p_tfhd->b_empty )
3426         msg_Warn( p_demux, "No samples in this chunk!" );
3427
3428     /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3429      * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3430      * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3431      * and so on. Finally, suppose that we get the chunks the other way around,
3432      * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3433      * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3434      * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3435      * flush it, i.e. send to the decoder the samples not yet sent.
3436      * Note that all the samples to be flushed should worth less than 100 ms,
3437      * (though I did not do the formal proof) and thus this flushing mechanism
3438      * should not cause A/V sync issues, or delays or whatever.
3439      */
3440     if( ret->i_sample < ret->i_sample_count )
3441         FlushChunk( p_demux, p_track );
3442
3443     if( ret->i_sample_count )
3444         FreeAndResetChunk( ret );
3445
3446     uint32_t default_duration = 0;
3447     if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3448         default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3449
3450     uint32_t default_size = 0;
3451     if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3452         default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3453
3454     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3455     if( p_trun == NULL)
3456     {
3457         msg_Warn( p_demux, "no trun box found!" );
3458         return VLC_EGENERIC;
3459     }
3460     MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3461
3462     ret->i_sample_count = p_trun_data->i_sample_count;
3463     assert( ret->i_sample_count > 0 );
3464     ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3465     ret->i_sample_first = p_track->i_sample_first;
3466     p_track->i_sample_first += ret->i_sample_count;
3467
3468     ret->i_first_dts = p_track->i_first_dts;
3469
3470     /* XXX I already saw DASH content with no default_duration and no
3471      * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3472      * This chunk of code might be buggy with segments having
3473      * more than one subsegment. */
3474     if( !default_duration )
3475     {
3476         if( p_sidx )
3477         {
3478             MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3479             assert( p_sidx_data->i_reference_count == 1 );
3480
3481             if( p_sidx_data->i_timescale == 0 )
3482                 return VLC_EGENERIC;
3483
3484             unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3485                                         p_sidx_data->i_timescale;
3486             default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3487
3488         }
3489     }
3490
3491     msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3492
3493     ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3494     ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3495
3496     if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3497         return VLC_ENOMEM;
3498
3499     ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3500     if( !ret->p_sample_count_pts )
3501         return VLC_ENOMEM;
3502
3503     if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3504     {
3505         ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3506         if( !ret->p_sample_offset_pts )
3507             return VLC_ENOMEM;
3508     }
3509
3510     ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3511     if( !ret->p_sample_size )
3512         return VLC_ENOMEM;
3513
3514     ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3515     if( !ret->p_sample_data )
3516         return VLC_ENOMEM;
3517
3518     uint32_t dur = 0, len;
3519     uint32_t chunk_duration = 0, chunk_size = 0;
3520
3521     /* Skip header of mdat */
3522     stream_Read( p_demux->s, NULL, 8 );
3523
3524     for( uint32_t i = 0; i < ret->i_sample_count; i++)
3525     {
3526         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3527             dur = p_trun_data->p_samples[i].i_duration;
3528         else
3529             dur = default_duration;
3530         ret->p_sample_delta_dts[i] = dur;
3531         chunk_duration += dur;
3532
3533         ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3534
3535         if( ret->p_sample_offset_pts )
3536         {
3537             ret->p_sample_offset_pts[i] =
3538                         p_trun_data->p_samples[i].i_composition_time_offset;
3539         }
3540
3541         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3542             len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3543         else
3544             len = ret->p_sample_size[i] = default_size;
3545
3546         ret->p_sample_data[i] = malloc( len );
3547         if( ret->p_sample_data[i] == NULL )
3548             return VLC_ENOMEM;
3549         int read = stream_Read( p_demux->s, ret->p_sample_data[i], len );
3550         if( read < (int)len )
3551             return VLC_EGENERIC;
3552         chunk_size += len;
3553     }
3554     ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3555     p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3556
3557     if( p_track->b_codec_need_restart &&
3558             p_track->fmt.i_cat == VIDEO_ES )
3559         ReInitDecoder( p_demux, p_track );
3560
3561     p_track->b_has_non_empty_cchunk = true;
3562     return VLC_SUCCESS;
3563 }
3564
3565 /**
3566  * Get the next chunk of the track identified by i_tk_id.
3567  * \Note We don't want to seek all the time, so if the first chunk given by the
3568  * input method doesn't belong to the right track, we don't throw it away,
3569  * and so, in general, this function fetch more than one chunk.
3570  * Not to mention that a new init segment might be put everywhere
3571  * between two chunks by the input method.
3572  */
3573 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3574 {
3575     demux_sys_t *p_sys = p_demux->p_sys;
3576     mp4_track_t *p_track;
3577
3578     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3579     {
3580         MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3581         if( !p_chunk )
3582             return VLC_EGENERIC;
3583
3584         if( !p_chunk->p_first )
3585             goto MP4_frg_GetChunks_Error;
3586         uint32_t i_type = p_chunk->p_first->i_type;
3587         uint32_t tid = 0;
3588         if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3589         {
3590             MP4_BoxFree( p_demux->s, p_sys->p_root );
3591             p_sys->p_root = p_chunk;
3592
3593             if( i_type == ATOM_ftyp ) /* DASH */
3594             {
3595                 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3596                 if( !p_tkhd )
3597                 {
3598                     msg_Warn( p_demux, "No tkhd found!" );
3599                     goto MP4_frg_GetChunks_Error;
3600                 }
3601                 tid = p_tkhd->data.p_tkhd->i_track_ID;
3602             }
3603             else                      /* Smooth Streaming */
3604             {
3605                 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3606                 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3607                 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3608                 {
3609                     msg_Warn( p_demux, "No StraBox found!" );
3610                     goto MP4_frg_GetChunks_Error;
3611                 }
3612                 tid = p_stra->data.p_stra->i_track_ID;
3613             }
3614
3615             p_track = MP4_frg_GetTrack( p_demux, tid );
3616             if( !p_track )
3617                 goto MP4_frg_GetChunks_Error;
3618             p_track->b_codec_need_restart = true;
3619
3620             return MP4_frg_GetChunks( p_demux, i_tk_id );
3621         }
3622
3623         if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3624             goto MP4_frg_GetChunks_Error;
3625
3626         MP4_BoxFree( p_demux->s, p_chunk );
3627
3628         if( tid == i_tk_id )
3629             break;
3630         else
3631             continue;
3632
3633 MP4_frg_GetChunks_Error:
3634         MP4_BoxFree( p_demux->s, p_chunk );
3635         return VLC_EGENERIC;
3636     }
3637
3638     return VLC_SUCCESS;
3639 }
3640
3641 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3642 {
3643     if( !p_track->b_ok || p_track->b_chapter )
3644     {
3645         return VLC_EGENERIC;
3646     }
3647
3648     if( p_track->b_selected )
3649     {
3650         msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3651         return VLC_SUCCESS;
3652     }
3653
3654     msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3655     p_track->b_selected = true;
3656     return VLC_SUCCESS;
3657 }
3658
3659 /**
3660  * DemuxFrg: read packet and send them to decoders
3661  * \return 1 on success, 0 on error.
3662  * TODO check for newly selected track
3663  */
3664 int DemuxFrg( demux_t *p_demux )
3665 {
3666     demux_sys_t *p_sys = p_demux->p_sys;
3667     unsigned i_track;
3668     unsigned i_track_selected;
3669
3670     /* check for newly selected/unselected track */
3671     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3672     {
3673         mp4_track_t *tk = &p_sys->track[i_track];
3674         bool b;
3675
3676         if( !tk->b_ok || tk->b_chapter )
3677             continue;
3678
3679         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3680         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3681
3682         if( tk->b_selected && !b )
3683         {
3684             MP4_TrackUnselect( p_demux, tk );
3685         }
3686         else if( !tk->b_selected && b)
3687         {
3688             MP4_frg_TrackSelect( p_demux, tk );
3689         }
3690
3691         if( tk->b_selected )
3692             i_track_selected++;
3693     }
3694
3695     if( i_track_selected <= 0 )
3696     {
3697         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3698         if( p_sys->i_timescale > 0 )
3699         {
3700             int64_t i_length = (mtime_t)1000000 *
3701                                (mtime_t)p_sys->i_duration /
3702                                (mtime_t)p_sys->i_timescale;
3703             if( MP4_GetMoviePTS( p_sys ) >= i_length )
3704                 return 0;
3705             return 1;
3706         }
3707
3708         msg_Warn( p_demux, "no track selected, exiting..." );
3709         return 0;
3710     }
3711
3712     /* first wait for the good time to read a packet */
3713     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3714
3715     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3716
3717     /* we will read 100ms for each stream so ...*/
3718     p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3719
3720     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3721     {
3722         mp4_track_t *tk = &p_sys->track[i_track];
3723
3724         if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3725         {
3726             msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3727             continue;
3728         }
3729
3730         if( !tk->b_has_non_empty_cchunk )
3731         {
3732             if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
3733             {
3734                 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
3735                 return 0;
3736             }
3737         }
3738
3739         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
3740         {
3741             block_t *p_block;
3742             int64_t i_delta;
3743
3744             mp4_chunk_t *ck = tk->cchunk;
3745             if( ck->i_sample >= ck->i_sample_count )
3746             {
3747                 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
3748                                     ck->i_sample, ck->i_sample_count );
3749                 return 0;
3750             }
3751
3752             uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3753             p_block = block_Alloc( sample_size );
3754             uint8_t *src = ck->p_sample_data[ck->i_sample];
3755             memcpy( p_block->p_buffer, src, sample_size );
3756
3757             ck->i_sample++;
3758             if( ck->i_sample == ck->i_sample_count )
3759                 tk->b_has_non_empty_cchunk = false;
3760
3761             /* dts */
3762             p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3763             /* pts */
3764             i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3765             if( i_delta != -1 )
3766                 p_block->i_pts = p_block->i_dts + i_delta;
3767             else if( tk->fmt.i_cat != VIDEO_ES )
3768                 p_block->i_pts = p_block->i_dts;
3769             else
3770                 p_block->i_pts = VLC_TS_INVALID;
3771
3772             es_out_Send( p_demux->out, tk->p_es, p_block );
3773
3774             tk->i_sample++;
3775
3776             if( !tk->b_has_non_empty_cchunk )
3777                 break;
3778         }
3779     }
3780     return 1;
3781 }