]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
demux: mp4: use new lang tables
[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 "mp4.h"
32
33 #include <vlc_plugin.h>
34
35 #include <vlc_demux.h>
36 #include <vlc_charset.h>                           /* EnsureUTF8 */
37 #include <vlc_meta.h>                              /* vlc_meta_t, vlc_meta_ */
38 #include <vlc_input.h>
39 #include <vlc_aout.h>
40 #include <assert.h>
41
42 #include "id3genres.h"                             /* for ATOM_gnre */
43
44 /*****************************************************************************
45  * Module descriptor
46  *****************************************************************************/
47 static int  Open ( vlc_object_t * );
48 static void Close( vlc_object_t * );
49
50 vlc_module_begin ()
51     set_category( CAT_INPUT )
52     set_subcategory( SUBCAT_INPUT_DEMUX )
53     set_description( N_("MP4 stream demuxer") )
54     set_shortname( N_("MP4") )
55     set_capability( "demux", 240 )
56     set_callbacks( Open, Close )
57 vlc_module_end ()
58
59 /*****************************************************************************
60  * Local prototypes
61  *****************************************************************************/
62 static int   Demux   ( demux_t * );
63 static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
64 static int   DemuxFrg( demux_t * );
65 static int   DemuxAsLeaf( demux_t * );
66 static int   Seek    ( demux_t *, mtime_t );
67 static int   Control ( demux_t *, int, va_list );
68
69 struct demux_sys_t
70 {
71     MP4_Box_t    *p_root;      /* container for the whole file */
72
73     mtime_t      i_pcr;
74
75     uint64_t     i_overall_duration; /* Full duration, including all fragments */
76     uint64_t     i_time;         /* time position of the presentation
77                                   * in movie timescale */
78     uint32_t     i_timescale;    /* movie time scale */
79     uint64_t     i_duration;     /* movie duration */
80     unsigned int i_tracks;       /* number of tracks */
81     mp4_track_t  *track;         /* array of track */
82     float        f_fps;          /* number of frame per seconds */
83
84     bool         b_fragmented;   /* fMP4 */
85     bool         b_seekable;
86     bool         b_fastseekable;
87     bool         b_seekmode;
88     bool         b_smooth;       /* Is it Smooth Streaming? */
89
90     bool            b_index_probed;
91     bool            b_fragments_probed;
92     mp4_fragment_t  moovfragment; /* moov */
93     mp4_fragment_t *p_fragments;  /* known fragments (moof following moov) */
94
95     struct
96     {
97         mp4_fragment_t *p_fragment;
98         uint32_t        i_current_box_type;
99         uint32_t        i_mdatbytesleft;
100     } context;
101
102     /* */
103     MP4_Box_t    *p_tref_chap;
104
105     /* */
106     input_title_t *p_title;
107 };
108
109 #define BOXDATA(type) type->data.type
110
111 /*****************************************************************************
112  * Declaration of local function
113  *****************************************************************************/
114 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_force_enable );
115 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
116 static void MP4_TrackDestroy(  mp4_track_t * );
117
118 static block_t * MP4_Block_Read( demux_t *, const mp4_track_t *, int );
119 static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
120
121 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
122 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
123
124 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
125
126 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
127 static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
128 static int      MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
129 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
130
131 static void     MP4_UpdateSeekpoint( demux_t * );
132
133 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
134
135 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox );
136 static int  ProbeFragments( demux_t *p_demux, bool b_force );
137 static int  ProbeIndex( demux_t *p_demux );
138 static mp4_fragment_t *GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact );
139 static mp4_fragment_t *GetFragmentByTime( demux_t *p_demux, const mtime_t i_time );
140
141 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
142                                       uint64_t *pi_pos, mtime_t *pi_mooftime );
143 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t * );
144 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
145                                       mp4_track_t **pp_tk, unsigned int *pi_chunk );
146 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof );
147
148 /* Helpers */
149
150 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
151 {
152     uint32_t i_return = 0;
153     if ( i_toread > INT32_MAX )
154     {
155         i_return = stream_Read( s, p_read, INT32_MAX );
156         if ( i_return < INT32_MAX )
157             return i_return;
158         else
159             i_toread -= INT32_MAX;
160     }
161     i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
162     return i_return;
163 }
164
165 static bool MP4_stream_Tell( stream_t *s, uint64_t *pi_pos )
166 {
167     int64_t i_pos = stream_Tell( s );
168     if ( i_pos < 0 )
169         return false;
170     else
171     {
172         *pi_pos = (uint64_t) i_pos;
173         return true;
174     }
175 }
176
177 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
178 {
179     MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
180     while( p_trex )
181     {
182         if ( p_trex->i_type == ATOM_trex &&
183              BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
184                 break;
185         else
186             p_trex = p_trex->p_next;
187     }
188     return p_trex;
189 }
190
191 static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
192 {
193     MP4_Box_t *p_trak = MP4_BoxGet( p_moov, "trak" );
194     MP4_Box_t *p_tkhd;
195     while( p_trak )
196     {
197         if( p_trak->i_type == ATOM_trak &&
198             (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
199             BOXDATA(p_tkhd)->i_track_ID == i_id )
200                 break;
201         else
202             p_trak = p_trak->p_next;
203     }
204     return p_trak;
205 }
206
207 /* Return time in microsecond of a track */
208 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
209 {
210     demux_sys_t *p_sys = p_demux->p_sys;
211     mp4_chunk_t chunk;
212     if( p_sys->b_fragmented )
213         chunk = *p_track->cchunk;
214     else
215         chunk = p_track->chunk[p_track->i_chunk];
216
217     unsigned int i_index = 0;
218     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
219     int64_t i_dts = chunk.i_first_dts;
220
221     while( i_sample > 0 )
222     {
223         if( i_sample > chunk.p_sample_count_dts[i_index] )
224         {
225             i_dts += chunk.p_sample_count_dts[i_index] *
226                 chunk.p_sample_delta_dts[i_index];
227             i_sample -= chunk.p_sample_count_dts[i_index];
228             i_index++;
229         }
230         else
231         {
232             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
233             break;
234         }
235     }
236
237     /* now handle elst */
238     if( p_track->p_elst )
239     {
240         demux_sys_t         *p_sys = p_demux->p_sys;
241         MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
242
243         /* convert to offset */
244         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
245               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
246             elst->i_media_time[p_track->i_elst] > 0 )
247         {
248             i_dts -= elst->i_media_time[p_track->i_elst];
249         }
250
251         /* add i_elst_time */
252         i_dts += p_track->i_elst_time * p_track->i_timescale /
253             p_sys->i_timescale;
254
255         if( i_dts < 0 ) i_dts = 0;
256     }
257
258     return CLOCK_FREQ * i_dts / p_track->i_timescale;
259 }
260
261 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
262 {
263     demux_sys_t *p_sys = p_demux->p_sys;
264     mp4_chunk_t *ck;
265     if( p_sys->b_fragmented )
266         ck = p_track->cchunk;
267     else
268         ck = &p_track->chunk[p_track->i_chunk];
269
270     unsigned int i_index = 0;
271     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
272
273     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
274         return -1;
275
276     for( i_index = 0;; i_index++ )
277     {
278         if( i_sample < ck->p_sample_count_pts[i_index] )
279             return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
280                    (int64_t)p_track->i_timescale;
281
282         i_sample -= ck->p_sample_count_pts[i_index];
283     }
284 }
285
286 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
287 {
288     return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
289 }
290
291 static void LoadChapter( demux_t  *p_demux );
292
293 static int LoadInitFrag( demux_t *p_demux )
294 {
295     demux_sys_t *p_sys = p_demux->p_sys;
296
297     if( p_sys->b_smooth ) /* Smooth Streaming */
298     {
299         if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
300         {
301             goto LoadInitFragError;
302         }
303         else
304         {
305             MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
306             if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
307                 goto LoadInitFragError;
308             /* Get number of tracks */
309             p_sys->i_tracks = 0;
310             for( int i = 0; i < 3; i++ )
311             {
312                 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
313                 if( p_stra && BOXDATA(p_stra) && BOXDATA(p_stra)->i_track_ID )
314                     p_sys->i_tracks++;
315                 /* Get timescale and duration of the video track; */
316                 if( p_sys->i_timescale == 0 )
317                 {
318                     if ( p_stra && BOXDATA(p_stra) )
319                     {
320                         p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
321                         p_sys->i_duration = BOXDATA(p_stra)->i_duration;
322                         p_sys->i_overall_duration = BOXDATA(p_stra)->i_duration;
323                     }
324                     if( p_sys->i_timescale == 0 )
325                     {
326                         msg_Err( p_demux, "bad timescale" );
327                         goto LoadInitFragError;
328                     }
329                 }
330             }
331         }
332     }
333     else
334     {
335         /* Load all boxes ( except raw data ) */
336         if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
337         {
338             goto LoadInitFragError;
339         }
340     }
341     return VLC_SUCCESS;
342
343 LoadInitFragError:
344     msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
345     return VLC_EGENERIC;
346 }
347
348 static int InitTracks( demux_t *p_demux )
349 {
350     demux_sys_t *p_sys = p_demux->p_sys;
351
352     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
353     if( p_sys->track == NULL )
354         return VLC_EGENERIC;
355
356     if( p_sys->b_fragmented )
357     {
358         mp4_track_t *p_track;
359         for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
360         {
361             p_track = &p_sys->track[i];
362             p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
363             if( unlikely( !p_track->cchunk ) )
364             {
365                 free( p_sys->track );
366                 return VLC_EGENERIC;
367             }
368         }
369     }
370     return VLC_SUCCESS;
371 }
372
373 static void CreateTracksFromSmooBox( demux_t *p_demux )
374 {
375     demux_sys_t *p_sys = p_demux->p_sys;
376
377     MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
378     mp4_track_t *p_track;
379     int j = 0;
380     for( int i = 0; i < 3; i++ )
381     {
382         MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
383         if( !p_stra || !BOXDATA(p_stra) || BOXDATA(p_stra)->i_track_ID == 0 )
384             continue;
385         else
386         {
387             p_track = &p_sys->track[j]; j++;
388             MP4_frg_TrackCreate( p_demux, p_track, p_stra );
389             p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
390         }
391     }
392 }
393
394 static block_t * MP4_EIA608_Convert( block_t * p_block )
395 {
396     /* Rebuild codec data from encap */
397     size_t i_copied = 0;
398     size_t i_remaining = p_block->i_buffer;
399     uint32_t i_bytes = 0;
400     block_t *p_newblock;
401
402     if ( i_remaining < 10 ||
403          !(i_bytes = GetDWBE(p_block->p_buffer)) ||
404          (i_bytes + 8 > i_remaining) ||
405          memcmp("cdat", &p_block->p_buffer[4], 4) ||
406          !(p_newblock = block_Alloc( i_remaining * 3 - 8 )) )
407     {
408         p_block->i_buffer = 0;
409         return p_block;
410     }
411
412     uint8_t *p_write = p_newblock->p_buffer;
413     uint8_t *p_read = &p_block->p_buffer[8];
414     i_bytes -= 8;
415     i_remaining -= 8;
416
417     do
418     {
419         p_write[i_copied++] = 0; /* cc1 == field 0 */
420         p_write[i_copied++] = p_read[0];
421         p_write[i_copied++] = p_read[1];
422         p_read += 2;
423         i_bytes -= 2;
424         i_remaining -= 2;
425     } while( i_bytes >= 2 );
426
427     if ( i_remaining >= 10 &&
428          (i_bytes = GetDWBE(p_read)) &&
429          (i_bytes + 8 <= i_remaining) &&
430          !memcmp("cdt2", &p_read[4], 4) )
431     {
432         p_read += 8;
433         i_bytes -= 8;
434         i_remaining -= 8;
435         do
436         {
437             p_write[i_copied++] = 0; /* cc1 == field 0 */
438             p_write[i_copied++] = p_read[0];
439             p_write[i_copied++] = p_read[1];
440             p_read += 2;
441             i_bytes -= 2;
442         } while( i_bytes >= 2 );
443     }
444
445     block_Release( p_block );
446     p_newblock->i_buffer = i_copied;
447     return p_newblock;
448 }
449
450 static block_t * MP4_Block_Read( demux_t *p_demux, const mp4_track_t *p_track, int i_size )
451 {
452     block_t *p_block = stream_Block( p_demux->s, i_size );
453     if ( !p_block )
454         return NULL;
455
456     /* might have some encap */
457     if( p_track->fmt.i_cat == SPU_ES )
458     {
459         switch( p_track->fmt.i_codec )
460         {
461             case VLC_CODEC_TX3G:
462             case VLC_CODEC_SPU:
463             /* accept as-is */
464             break;
465             case VLC_CODEC_EIA608_1:
466                 p_block = MP4_EIA608_Convert( p_block );
467             break;
468         default:
469             p_block->i_buffer = 0;
470             break;
471         }
472     }
473
474     return p_block;
475 }
476
477 static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
478 {
479     if ( p_track->b_chans_reorder && aout_BitsPerSample( p_track->fmt.i_codec ) )
480     {
481         aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
482                              p_track->fmt.audio.i_channels,
483                              p_track->rgi_chans_reordering,
484                              p_track->fmt.i_codec );
485     }
486     es_out_Send( p_demux->out, p_track->p_es, p_block );
487 }
488
489 /*****************************************************************************
490  * Open: check file and initializes MP4 structures
491  *****************************************************************************/
492 static int Open( vlc_object_t * p_this )
493 {
494     demux_t  *p_demux = (demux_t *)p_this;
495     demux_sys_t     *p_sys;
496
497     const uint8_t   *p_peek;
498
499     MP4_Box_t       *p_ftyp;
500     MP4_Box_t       *p_rmra;
501     MP4_Box_t       *p_mvhd;
502     MP4_Box_t       *p_trak;
503
504     unsigned int    i;
505     bool      b_enabled_es;
506
507     /* A little test to see if it could be a mp4 */
508     if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
509
510     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
511     {
512         case ATOM_moov:
513         case ATOM_foov:
514         case ATOM_moof:
515         case ATOM_mdat:
516         case ATOM_udta:
517         case ATOM_free:
518         case ATOM_skip:
519         case ATOM_wide:
520         case ATOM_uuid:
521         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
522             break;
523         case ATOM_ftyp:
524             /* We don't yet support f4v, but avformat does. */
525             if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
526                 return VLC_EGENERIC;
527             break;
528          default:
529             return VLC_EGENERIC;
530     }
531
532     /* create our structure that will contains all data */
533     p_sys = calloc( 1, sizeof( demux_sys_t ) );
534     if ( !p_sys )
535         return VLC_EGENERIC;
536
537     /* I need to seek */
538     stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
539     if( !p_sys->b_seekable )
540     {
541         msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
542         free( p_sys );
543         return VLC_EGENERIC;
544     }
545     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
546     p_sys->b_seekmode = p_sys->b_fastseekable;
547
548     /*Set exported functions */
549     p_demux->pf_demux = Demux;
550     p_demux->pf_control = Control;
551
552     p_demux->p_sys = p_sys;
553
554     if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
555     if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
556     {
557         p_sys->b_smooth = true;
558         p_sys->b_fragmented = true;
559     }
560
561     if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
562         goto error;
563
564     if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
565     {
566         if ( p_sys->b_seekable )
567         {
568             /* Probe remaining to check if there's really fragments
569                or if that file is just ready to append fragments */
570             ProbeFragments( p_demux, false );
571             p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
572         }
573         else
574             p_sys->b_fragmented = true;
575
576         if ( p_sys->b_fragmented && !p_sys->i_overall_duration )
577             ProbeFragments( p_demux, true );
578     }
579
580     if ( !p_sys->moovfragment.p_moox )
581         AddFragment( p_demux, MP4_BoxGet( p_sys->p_root, "/moov" ) );
582
583     /* we always need a moov entry, but smooth has a workaround */
584     if ( !p_sys->moovfragment.p_moox && !p_sys->b_smooth )
585         goto error;
586
587     if ( p_sys->b_smooth )
588     {
589         p_demux->pf_demux = DemuxFrg;
590     }
591     else if( p_sys->b_fragmented )
592     {
593         p_demux->pf_demux = DemuxAsLeaf;
594     }
595
596     if( p_sys->b_smooth )
597     {
598         if( InitTracks( p_demux ) != VLC_SUCCESS )
599             goto error;
600         CreateTracksFromSmooBox( p_demux );
601         return VLC_SUCCESS;
602     }
603
604     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
605
606     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
607     {
608         switch( BOXDATA(p_ftyp)->i_major_brand )
609         {
610             case( ATOM_isom ):
611                 msg_Dbg( p_demux,
612                          "ISO Media file (isom) version %d.",
613                          BOXDATA(p_ftyp)->i_minor_version );
614                 break;
615             case( ATOM_3gp4 ):
616             case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
617             case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
618             case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
619                 msg_Dbg( p_demux, "3GPP Media file Release: %c",
620 #ifdef WORDS_BIGENDIAN
621                         BOXDATA(p_ftyp)->i_major_brand
622 #else
623                         BOXDATA(p_ftyp)->i_major_brand >> 24
624 #endif
625                         );
626                 break;
627             case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
628                 msg_Dbg( p_demux, "Apple QuickTime file" );
629                 break;
630             case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
631                 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
632                 break;
633             default:
634                 msg_Dbg( p_demux,
635                          "unrecognized major file specification (%4.4s).",
636                           (char*)&BOXDATA(p_ftyp)->i_major_brand );
637                 break;
638         }
639     }
640     else
641     {
642         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
643     }
644
645     /* the file need to have one moov box */
646     p_sys->moovfragment.p_moox = MP4_BoxGet( p_sys->p_root, "/moov", 0 );
647     if( !p_sys->moovfragment.p_moox )
648     {
649         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
650
651         if( !p_foov )
652         {
653             msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
654             goto error;
655         }
656         /* we have a free box as a moov, rename it */
657         p_foov->i_type = ATOM_moov;
658         p_sys->moovfragment.p_moox = p_foov;
659     }
660
661     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
662     {
663         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
664         int        i;
665
666         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
667
668         input_thread_t *p_input = demux_GetParentInput( p_demux );
669         input_item_t *p_current = input_GetItem( p_input );
670
671         input_item_node_t *p_subitems = input_item_node_Create( p_current );
672
673         for( i = 0; i < i_count; i++ )
674         {
675             MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
676             char      *psz_ref;
677             uint32_t  i_ref_type;
678
679             if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
680             {
681                 continue;
682             }
683             i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
684
685             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
686                      psz_ref, (char*)&i_ref_type );
687
688             if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
689             {
690                 if( strstr( psz_ref, "qt5gateQT" ) )
691                 {
692                     msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
693                     continue;
694                 }
695                 if( !strncmp( psz_ref, "http://", 7 ) ||
696                     !strncmp( psz_ref, "rtsp://", 7 ) )
697                 {
698                     ;
699                 }
700                 else
701                 {
702                     char *psz_absolute;
703                     char *psz_path = strdup( p_demux->psz_location );
704                     char *end = strrchr( psz_path, '/' );
705                     if( end ) end[1] = '\0';
706                     else *psz_path = '\0';
707
708                     if( asprintf( &psz_absolute, "%s://%s%s",
709                                   p_demux->psz_access, psz_path, psz_ref ) < 0 )
710                     {
711                         free( psz_ref );
712                         free( psz_path );
713                         input_item_node_Delete( p_subitems );
714                         vlc_object_release( p_input) ;
715                         return VLC_ENOMEM;
716                     }
717
718                     free( psz_ref );
719                     psz_ref = psz_absolute;
720                     free( psz_path );
721                 }
722                 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
723                 input_item_t *p_item = input_item_New( psz_ref, NULL );
724                 input_item_CopyOptions( p_current, p_item );
725                 input_item_node_AppendItem( p_subitems, p_item );
726                 vlc_gc_decref( p_item );
727             }
728             else
729             {
730                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
731                          (char*)&BOXDATA(p_rdrf)->i_ref_type );
732             }
733             free( psz_ref );
734         }
735         input_item_node_PostAndDelete( p_subitems );
736         vlc_object_release( p_input );
737     }
738
739     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
740     {
741         if( !p_rmra )
742         {
743             msg_Err( p_demux, "cannot find /moov/mvhd" );
744             goto error;
745         }
746         else
747         {
748             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
749             p_demux->pf_demux = DemuxRef;
750             return VLC_SUCCESS;
751         }
752     }
753     else
754     {
755         p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
756         if( p_sys->i_timescale == 0 )
757         {
758             msg_Err( p_this, "bad timescale" );
759             goto error;
760         }
761     }
762
763     if ( p_sys->i_overall_duration == 0 )
764     {
765         /* Try in mehd if fragmented */
766         MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
767         if ( p_mehd && p_mehd->data.p_mehd )
768             p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
769         else
770             p_sys->i_overall_duration = p_sys->moovfragment.i_duration;
771     }
772
773     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
774     {
775         msg_Err( p_demux, "cannot find any /moov/trak" );
776         goto error;
777     }
778     msg_Dbg( p_demux, "found %d track%c",
779                         p_sys->i_tracks,
780                         p_sys->i_tracks ? 's':' ' );
781
782     if( InitTracks( p_demux ) != VLC_SUCCESS )
783         goto error;
784
785     /* Search the first chap reference (like quicktime) and
786      * check that at least 1 stream is enabled */
787     p_sys->p_tref_chap = NULL;
788     b_enabled_es = false;
789     for( i = 0; i < p_sys->i_tracks; i++ )
790     {
791         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
792
793
794         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
795         if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
796             b_enabled_es = true;
797
798         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
799         if( p_chap && p_chap->data.p_tref_generic &&
800             p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
801             p_sys->p_tref_chap = p_chap;
802     }
803
804     /* now process each track and extract all useful information */
805     for( i = 0; i < p_sys->i_tracks; i++ )
806     {
807         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
808         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
809
810         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
811         {
812             const char *psz_cat;
813             switch( p_sys->track[i].fmt.i_cat )
814             {
815                 case( VIDEO_ES ):
816                     psz_cat = "video";
817                     break;
818                 case( AUDIO_ES ):
819                     psz_cat = "audio";
820                     break;
821                 case( SPU_ES ):
822                     psz_cat = "subtitle";
823                     break;
824
825                 default:
826                     psz_cat = "unknown";
827                     break;
828             }
829
830             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
831                      p_sys->track[i].i_track_ID, psz_cat,
832                      p_sys->track[i].b_enable ? "enable":"disable",
833                      p_sys->track[i].fmt.psz_language ?
834                      p_sys->track[i].fmt.psz_language : "undef" );
835         }
836         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
837         {
838             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
839                      p_sys->track[i].i_track_ID,
840                      p_sys->track[i].fmt.psz_language ?
841                      p_sys->track[i].fmt.psz_language : "undef" );
842         }
843         else
844         {
845             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
846                      p_sys->track[i].i_track_ID );
847         }
848     }
849
850     mp4_fragment_t *p_fragment = &p_sys->moovfragment;
851     while ( p_fragment )
852     {
853         msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRIu64"<->%"PRIu64", duration %"PRId64,
854                  p_fragment->p_moox->i_pos, p_fragment->i_chunk_range_min_offset,
855                  p_fragment->i_chunk_range_max_offset, CLOCK_FREQ * p_fragment->i_duration / p_sys->i_timescale );
856         p_fragment = p_fragment->p_next;
857     }
858
859     /* */
860     LoadChapter( p_demux );
861
862     return VLC_SUCCESS;
863
864 error:
865     if( p_sys->p_root )
866     {
867         MP4_BoxFree( p_demux->s, p_sys->p_root );
868     }
869     free( p_sys );
870     return VLC_EGENERIC;
871 }
872
873 /*****************************************************************************
874  * Demux: read packet and send them to decoders
875  *****************************************************************************
876  * TODO check for newly selected track (ie audio upt to now )
877  *****************************************************************************/
878 static int Demux( demux_t *p_demux )
879 {
880     demux_sys_t *p_sys = p_demux->p_sys;
881     unsigned int i_track;
882
883
884     unsigned int i_track_selected;
885
886     /* check for newly selected/unselected track */
887     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
888          i_track++ )
889     {
890         mp4_track_t *tk = &p_sys->track[i_track];
891         bool b;
892
893         if( !tk->b_ok || tk->b_chapter ||
894             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
895         {
896             continue;
897         }
898
899         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
900
901         if( tk->b_selected && !b )
902         {
903             MP4_TrackUnselect( p_demux, tk );
904         }
905         else if( !tk->b_selected && b)
906         {
907             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
908         }
909
910         if( tk->b_selected )
911         {
912             i_track_selected++;
913         }
914     }
915
916     if( i_track_selected <= 0 )
917     {
918         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
919         if( p_sys->i_timescale > 0 )
920         {
921             int64_t i_length = CLOCK_FREQ *
922                                (mtime_t)p_sys->moovfragment.i_duration /
923                                (mtime_t)p_sys->i_timescale;
924             if( MP4_GetMoviePTS( p_sys ) >= i_length )
925                 return 0;
926             return 1;
927         }
928
929         msg_Warn( p_demux, "no track selected, exiting..." );
930         return 0;
931     }
932
933     /* */
934     MP4_UpdateSeekpoint( p_demux );
935
936     /* first wait for the good time to read a packet */
937     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
938
939     bool b_data_sent = false;
940
941     /* Find next track matching contiguous data */
942     mp4_track_t *tk = NULL;
943     uint64_t i_candidate_pos = UINT64_MAX;
944     mtime_t i_candidate_dts = INT64_MAX;
945     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
946     {
947         mp4_track_t *tk_tmp = &p_sys->track[i_track];
948         if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
949             continue;
950
951         if ( p_sys->b_seekmode )
952         {
953             mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk_tmp );
954             if ( i_dts <= i_candidate_dts )
955             {
956                 tk = tk_tmp;
957                 i_candidate_dts = i_dts;
958                 i_candidate_pos = MP4_TrackGetPos( tk_tmp );
959             }
960         }
961         else
962         {
963             /* Try to avoid seeking on non fastseekable. Will fail with non interleaved content */
964             uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
965             if ( i_pos <= i_candidate_pos )
966             {
967                 i_candidate_pos = i_pos;
968                 tk = tk_tmp;
969             }
970         }
971     }
972
973     if ( !tk )
974     {
975         msg_Dbg( p_demux, "Could not select track by data position" );
976         goto end;
977     }
978     else if ( p_sys->b_seekmode )
979     {
980         if( stream_Seek( p_demux->s, i_candidate_pos ) )
981         {
982             msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
983                       tk->i_track_ID );
984             MP4_TrackUnselect( p_demux, tk );
985             goto end;
986         }
987     }
988
989 #if 0
990     msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
991              MP4_TrackGetDTS( p_demux, tk ),
992              MP4_GetMoviePTS( p_sys ), i_candidate_pos );
993 #endif
994
995     uint32_t i_nb_samples = 0;
996     uint32_t i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
997     if( i_samplessize > 0 )
998     {
999         block_t *p_block;
1000         int64_t i_delta;
1001         uint64_t i_current_pos;
1002
1003         /* go,go go ! */
1004         if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
1005             goto end;
1006
1007         if( i_current_pos != i_candidate_pos )
1008         {
1009             if( stream_Seek( p_demux->s, i_candidate_pos ) )
1010             {
1011                 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1012                           ": Failed to seek to %"PRIu64,
1013                           tk->i_track_ID, i_candidate_pos );
1014                 MP4_TrackUnselect( p_demux, tk );
1015                 goto end;
1016             }
1017             i_current_pos = i_candidate_pos;
1018         }
1019
1020         /* now read pes */
1021         if( !(p_block = MP4_Block_Read( p_demux, tk, i_samplessize )) )
1022         {
1023             msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1024                       ": Failed to read %d bytes sample at %"PRIu64,
1025                       tk->i_track_ID, i_samplessize, i_current_pos );
1026             MP4_TrackUnselect( p_demux, tk );
1027             goto end;
1028         }
1029
1030         /* dts */
1031         p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
1032         /* pts */
1033         i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1034         if( i_delta != -1 )
1035             p_block->i_pts = p_block->i_dts + i_delta;
1036         else if( tk->fmt.i_cat != VIDEO_ES )
1037             p_block->i_pts = p_block->i_dts;
1038         else
1039             p_block->i_pts = VLC_TS_INVALID;
1040
1041         if ( !b_data_sent )
1042         {
1043             es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1044             b_data_sent = true;
1045         }
1046         MP4_Block_Send( p_demux, tk, p_block );
1047     }
1048
1049     /* Next sample */
1050     if ( i_nb_samples ) /* sample size could be 0, need to go fwd. see return */
1051         MP4_TrackNextSample( p_demux, tk, i_nb_samples );
1052
1053 end:
1054     if ( b_data_sent )
1055     {
1056         p_sys->i_pcr = INT64_MAX;
1057         for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1058         {
1059             mp4_track_t *tk = &p_sys->track[i_track];
1060             if ( !tk->b_ok || !tk->b_selected  ||
1061                  (tk->fmt.i_cat != AUDIO_ES && tk->fmt.i_cat != VIDEO_ES) )
1062                 continue;
1063
1064             mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1065             p_sys->i_pcr = __MIN( i_dts, p_sys->i_pcr );
1066
1067             if ( !p_sys->b_seekmode && i_dts > p_sys->i_pcr + 2*CLOCK_FREQ )
1068             {
1069                 msg_Dbg( p_demux, "that media doesn't look interleaved, will need to seek");
1070                 p_sys->b_seekmode = true;
1071             }
1072
1073             p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
1074         }
1075     }
1076
1077     return b_data_sent || ( i_samplessize == 0 && i_nb_samples );
1078 }
1079
1080 static void MP4_UpdateSeekpoint( demux_t *p_demux )
1081 {
1082     demux_sys_t *p_sys = p_demux->p_sys;
1083     int64_t i_time;
1084     int i;
1085     if( !p_sys->p_title )
1086         return;
1087     i_time = MP4_GetMoviePTS( p_sys );
1088     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
1089     {
1090         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
1091             break;
1092     }
1093     i--;
1094
1095     if( i != p_demux->info.i_seekpoint && i >= 0 )
1096     {
1097         p_demux->info.i_seekpoint = i;
1098         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1099     }
1100 }
1101 /*****************************************************************************
1102  * Seek: Go to i_date
1103 ******************************************************************************/
1104 static int Seek( demux_t *p_demux, mtime_t i_date )
1105 {
1106     demux_sys_t *p_sys = p_demux->p_sys;
1107     unsigned int i_track;
1108
1109     /* First update global time */
1110     p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
1111     p_sys->i_pcr  = VLC_TS_INVALID;
1112
1113     /* Now for each stream try to go to this time */
1114     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1115     {
1116         mp4_track_t *tk = &p_sys->track[i_track];
1117         MP4_TrackSeek( p_demux, tk, i_date );
1118     }
1119     MP4_UpdateSeekpoint( p_demux );
1120
1121     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1122
1123     return VLC_SUCCESS;
1124 }
1125
1126 static int LeafSeekIntoFragment( demux_t *p_demux, mp4_fragment_t *p_fragment )
1127 {
1128     demux_sys_t *p_sys = p_demux->p_sys;
1129     uint64_t i64 = p_fragment->i_chunk_range_min_offset;
1130
1131     if ( p_fragment->p_moox->i_type == ATOM_moov )
1132     {
1133         mp4_track_t *p_track;
1134         unsigned int i_chunk;
1135         int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i64, &p_track, &i_chunk );
1136         if ( i_ret == VLC_EGENERIC )
1137         {
1138             msg_Dbg( p_demux, "moov seek failed to identify %"PRIu64, i64 );
1139             return i_ret;
1140         }
1141         msg_Dbg( p_demux, "moov seeking to %"PRIu64, i64 );
1142     }
1143     else
1144     {
1145         i64 = p_fragment->i_chunk_range_min_offset;
1146         msg_Dbg( p_demux, "moof seeking to %"PRIu64, i64 );
1147     }
1148
1149     if( stream_Seek( p_demux->s, i64 ) )
1150     {
1151         msg_Err( p_demux, "seek failed to %"PRIu64, i64 );
1152         return VLC_EGENERIC;
1153     }
1154
1155     /* map context */
1156     p_sys->context.p_fragment = p_fragment;
1157     p_sys->context.i_current_box_type = ATOM_mdat;
1158     LeafMapTrafTrunContextes( p_demux, p_fragment->p_moox );
1159     p_sys->context.i_mdatbytesleft = p_fragment->i_chunk_range_max_offset - i64;
1160
1161     mtime_t i_time_base = LeafGetFragmentTimeOffset( p_demux, p_fragment );
1162     for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1163     {
1164         p_sys->track[i_track].i_time = i_time_base * p_sys->track[i_track].i_timescale / p_sys->i_timescale;
1165     }
1166     p_sys->i_time = i_time_base;
1167     p_sys->i_pcr  = VLC_TS_INVALID;
1168
1169     return VLC_SUCCESS;
1170 }
1171
1172 static int LeafSeekToTime( demux_t *p_demux, mtime_t i_nztime )
1173 {
1174     demux_sys_t *p_sys = p_demux->p_sys;
1175     mp4_fragment_t *p_fragment;
1176     uint64_t i64 = 0;
1177     if ( !p_sys->i_timescale || !p_sys->i_overall_duration || !p_sys->b_seekable )
1178          return VLC_EGENERIC;
1179
1180     if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1181     {
1182         ProbeIndex( p_demux );
1183         p_sys->b_index_probed = true;
1184     }
1185
1186     p_fragment = GetFragmentByTime( p_demux, i_nztime );
1187     if ( !p_fragment )
1188     {
1189         mtime_t i_mooftime;
1190         msg_Dbg( p_demux, "seek can't find matching fragment for %"PRId64", trying index", i_nztime );
1191         if ( LeafIndexGetMoofPosByTime( p_demux, i_nztime, &i64, &i_mooftime ) == VLC_SUCCESS )
1192         {
1193             msg_Dbg( p_demux, "seek trying to go to unknown but indexed fragment at %"PRId64, i64 );
1194             if( stream_Seek( p_demux->s, i64 ) )
1195             {
1196                 msg_Err( p_demux, "seek to moof failed %"PRId64, i64 );
1197                 return VLC_EGENERIC;
1198             }
1199             p_sys->context.i_current_box_type = 0;
1200             p_sys->context.i_mdatbytesleft = 0;
1201             p_sys->context.p_fragment = NULL;
1202             for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1203             {
1204                 p_sys->track[i_track].i_time = i_mooftime / CLOCK_FREQ * p_sys->track[i_track].i_timescale;
1205             }
1206             p_sys->i_time = i_mooftime / CLOCK_FREQ * p_sys->i_timescale;
1207             p_sys->i_pcr  = VLC_TS_INVALID;
1208         }
1209         else
1210         {
1211             msg_Warn( p_demux, "seek by index failed" );
1212             return VLC_EGENERIC;
1213         }
1214     }
1215     else
1216     {
1217         msg_Dbg( p_demux, "seeking to fragment data starting at %"PRIu64" for time %"PRId64,
1218                            p_fragment->i_chunk_range_min_offset, i_nztime );
1219         if ( LeafSeekIntoFragment( p_demux, p_fragment ) != VLC_SUCCESS )
1220             return VLC_EGENERIC;
1221     }
1222
1223     /* And set next display time in that trun/fragment */
1224     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + i_nztime );
1225     return VLC_SUCCESS;
1226 }
1227
1228 static int LeafSeekToPos( demux_t *p_demux, double f )
1229 {
1230     demux_sys_t *p_sys = p_demux->p_sys;
1231     if ( !p_sys->b_seekable )
1232         return VLC_EGENERIC;
1233
1234     if ( p_sys->i_timescale && p_sys->i_overall_duration )
1235     {
1236         return LeafSeekToTime( p_demux,
1237                     (mtime_t)( f * CLOCK_FREQ * p_sys->i_overall_duration /
1238                                p_sys->i_timescale ) );
1239     }
1240
1241     if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1242     {
1243         ProbeIndex( p_demux );
1244         p_sys->b_index_probed = true;
1245     }
1246
1247     /* Blind seek to pos only */
1248     uint64_t i64 = (uint64_t) stream_Size( p_demux->s ) * f;
1249     mp4_fragment_t *p_fragment = GetFragmentByPos( p_demux, i64, false );
1250     if ( p_fragment )
1251     {
1252         msg_Dbg( p_demux, "Seeking to fragment data starting at %"PRIu64" for pos %"PRIu64,
1253                  p_fragment->i_chunk_range_min_offset, i64 );
1254         return LeafSeekIntoFragment( p_demux, p_fragment );
1255     }
1256     else
1257     {
1258         msg_Dbg( p_demux, "Cant get fragment for data starting at %"PRIu64, i64 );
1259         return VLC_EGENERIC;
1260     }
1261 }
1262
1263 static int MP4_frg_Seek( demux_t *p_demux, double f )
1264 {
1265     demux_sys_t *p_sys = p_demux->p_sys;
1266
1267     int64_t i64 = stream_Size( p_demux->s );
1268     if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1269     {
1270         return VLC_EGENERIC;
1271     }
1272     else
1273     {
1274         /* update global time */
1275         p_sys->i_time = (uint64_t)(f * (double)p_sys->moovfragment.i_duration);
1276         p_sys->i_pcr  = MP4_GetMoviePTS( p_sys );
1277
1278         for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1279         {
1280             mp4_track_t *tk = &p_sys->track[i_track];
1281
1282             /* We don't want the current chunk to be flushed */
1283             tk->cchunk->i_sample = tk->cchunk->i_sample_count;
1284
1285             /* reset/update some values */
1286             tk->i_sample = tk->i_sample_first = 0;
1287             tk->i_first_dts = p_sys->i_time;
1288
1289             /* We want to discard the current chunk and get the next one at once */
1290             tk->b_has_non_empty_cchunk = false;
1291         }
1292         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
1293         return VLC_SUCCESS;
1294     }
1295 }
1296
1297 /*****************************************************************************
1298  * Control:
1299  *****************************************************************************/
1300 static int Control( demux_t *p_demux, int i_query, va_list args )
1301 {
1302     demux_sys_t *p_sys = p_demux->p_sys;
1303
1304     double f, *pf;
1305     int64_t i64, *pi64;
1306
1307     switch( i_query )
1308     {
1309         case DEMUX_GET_POSITION:
1310             pf = (double*)va_arg( args, double * );
1311             if( p_sys->i_overall_duration > 0 )
1312             {
1313                 *pf = (double)p_sys->i_time / (double)p_sys->i_overall_duration;
1314             }
1315             else
1316             {
1317                 *pf = 0.0;
1318             }
1319             return VLC_SUCCESS;
1320
1321         case DEMUX_SET_POSITION:
1322             f = (double)va_arg( args, double );
1323             if ( p_demux->pf_demux == DemuxAsLeaf )
1324                 return LeafSeekToPos( p_demux, f );
1325             else if ( p_demux->pf_demux == DemuxFrg )
1326                 return MP4_frg_Seek( p_demux, f );
1327             else if( p_sys->i_timescale > 0 )
1328             {
1329                 i64 = (int64_t)( f * CLOCK_FREQ *
1330                                  (double)p_sys->i_overall_duration /
1331                                  (double)p_sys->i_timescale );
1332                 return Seek( p_demux, i64 );
1333             }
1334             else return VLC_EGENERIC;
1335
1336         case DEMUX_GET_TIME:
1337             pi64 = (int64_t*)va_arg( args, int64_t * );
1338             if( p_sys->i_timescale > 0 )
1339             {
1340                 *pi64 = CLOCK_FREQ *
1341                         (mtime_t)p_sys->i_time /
1342                         (mtime_t)p_sys->i_timescale;
1343             }
1344             else *pi64 = 0;
1345             return VLC_SUCCESS;
1346
1347         case DEMUX_SET_TIME:
1348             i64 = (int64_t)va_arg( args, int64_t );
1349             if ( p_demux->pf_demux == DemuxAsLeaf )
1350                 return LeafSeekToTime( p_demux, i64 );
1351             else
1352                 return Seek( p_demux, i64 );
1353
1354         case DEMUX_GET_LENGTH:
1355             pi64 = (int64_t*)va_arg( args, int64_t * );
1356             if( p_sys->i_timescale > 0 )
1357             {
1358                 *pi64 = CLOCK_FREQ *
1359                         (mtime_t)p_sys->i_overall_duration /
1360                         (mtime_t)p_sys->i_timescale;
1361             }
1362             else *pi64 = 0;
1363             return VLC_SUCCESS;
1364
1365         case DEMUX_GET_FPS:
1366             pf = (double*)va_arg( args, double* );
1367             *pf = p_sys->f_fps;
1368             return VLC_SUCCESS;
1369
1370         case DEMUX_GET_ATTACHMENTS:
1371         {
1372             input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1373             int *pi_int = va_arg( args, int * );
1374
1375             MP4_Box_t  *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
1376             if ( !p_covr ) return VLC_EGENERIC;
1377             MP4_Box_t  *p_box;
1378             int i_count = 0;
1379
1380             for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1381             {
1382                 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
1383                     i_count++;
1384             }
1385
1386             if ( i_count == 0 )
1387                 return VLC_EGENERIC;
1388
1389             *ppp_attach = (input_attachment_t**)
1390                     malloc( sizeof(input_attachment_t*) * i_count );
1391             if( !(*ppp_attach) ) return VLC_ENOMEM;
1392             char *psz_mime;
1393             char *psz_filename;
1394             i_count = 0;
1395             for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1396             {
1397                 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1398                     continue;
1399
1400                 if ( !memcmp( p_box->data.p_data->p_blob,
1401                               "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1402                 {
1403                     psz_mime = strdup( "image/png" );
1404                 }
1405                 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1406                 {
1407                     psz_mime = strdup( "image/jpeg" );
1408                 }
1409                 else
1410                 {
1411                     continue;
1412                 }
1413
1414                 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1415                 {
1416                     (*ppp_attach)[i_count++] =
1417                         vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1418                             p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1419                     free( psz_filename );
1420                 }
1421
1422                 free( psz_mime );
1423             }
1424
1425             if ( i_count == 0 )
1426             {
1427                 free( *ppp_attach );
1428                 return VLC_EGENERIC;
1429             }
1430
1431             *pi_int = i_count;
1432
1433             return VLC_SUCCESS;
1434         }
1435
1436         case DEMUX_GET_META:
1437         {
1438             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1439             MP4_Box_t  *p_0xa9xxx;
1440
1441             MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1442             if ( p_covr )
1443                 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1444
1445             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1446             if( p_udta == NULL )
1447             {
1448                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1449                 if( p_udta == NULL && p_covr == NULL )
1450                     return VLC_EGENERIC;
1451                 else
1452                     return VLC_SUCCESS;
1453             }
1454
1455             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1456                  p_0xa9xxx = p_0xa9xxx->p_next )
1457             {
1458
1459                 if( !p_0xa9xxx || !BOXDATA(p_0xa9xxx) )
1460                     continue;
1461
1462                 /* FIXME FIXME: should convert from whatever the character
1463                  * encoding of MP4 meta data is to UTF-8. */
1464 #define SET(fct) do { char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" ); \
1465     if( psz_utf ) { EnsureUTF8( psz_utf );  \
1466                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1467
1468                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1469                 switch( p_0xa9xxx->i_type )
1470                 {
1471                 case ATOM_0xa9nam: /* Full name */
1472                     SET( vlc_meta_SetTitle );
1473                     break;
1474                 case ATOM_0xa9aut:
1475                     SET( vlc_meta_SetArtist );
1476                     break;
1477                 case ATOM_0xa9ART:
1478                     SET( vlc_meta_SetArtist );
1479                     break;
1480                 case ATOM_0xa9cpy:
1481                     SET( vlc_meta_SetCopyright );
1482                     break;
1483                 case ATOM_0xa9day: /* Creation Date */
1484                     SET( vlc_meta_SetDate );
1485                     break;
1486                 case ATOM_0xa9des: /* Description */
1487                     SET( vlc_meta_SetDescription );
1488                     break;
1489                 case ATOM_0xa9gen: /* Genre */
1490                     SET( vlc_meta_SetGenre );
1491                     break;
1492
1493                 case ATOM_gnre:
1494                     if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1495                         vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1496                     break;
1497
1498                 case ATOM_0xa9alb: /* Album */
1499                     SET( vlc_meta_SetAlbum );
1500                     break;
1501
1502                 case ATOM_0xa9trk: /* Track */
1503                     SET( vlc_meta_SetTrackNum );
1504                     break;
1505                 case ATOM_trkn:
1506                 {
1507                     char psz_trck[11];
1508                     snprintf( psz_trck, sizeof( psz_trck ), "%i",
1509                               p_0xa9xxx->data.p_trkn->i_track_number );
1510                     vlc_meta_SetTrackNum( p_meta, psz_trck );
1511                     if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1512                     {
1513                         snprintf( psz_trck, sizeof( psz_trck ), "%i",
1514                                   p_0xa9xxx->data.p_trkn->i_track_total );
1515                         vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1516                     }
1517                     break;
1518                 }
1519                 case ATOM_0xa9cmt: /* Commment */
1520                     SET( vlc_meta_SetDescription );
1521                     break;
1522
1523                 case ATOM_0xa9url: /* URL */
1524                     SET( vlc_meta_SetURL );
1525                     break;
1526
1527                 case ATOM_0xa9too: /* Encoder Tool */
1528                 case ATOM_0xa9enc: /* Encoded By */
1529                     SET( vlc_meta_SetEncodedBy );
1530                     break;
1531
1532                 case ATOM_0xa9pub:
1533                     SET( vlc_meta_SetPublisher );
1534                     break;
1535
1536                 case ATOM_0xa9dir:
1537                     SET( vlc_meta_SetDirector );
1538                     break;
1539
1540                 default:
1541                     break;
1542                 }
1543 #undef SET
1544                 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1545                 {
1546                     { ATOM_0xa9wrt, N_("Writer") },
1547                     { ATOM_0xa9com, N_("Composer") },
1548                     { ATOM_0xa9prd, N_("Producer") },
1549                     { ATOM_0xa9inf, N_("Information") },
1550                     { ATOM_0xa9dis, N_("Disclaimer") },
1551                     { ATOM_0xa9req, N_("Requirements") },
1552                     { ATOM_0xa9fmt, N_("Original Format") },
1553                     { ATOM_0xa9dsa, N_("Display Source As") },
1554                     { ATOM_0xa9hst, N_("Host Computer") },
1555                     { ATOM_0xa9prf, N_("Performers") },
1556                     { ATOM_0xa9ope, N_("Original Performer") },
1557                     { ATOM_0xa9src, N_("Providers Source Content") },
1558                     { ATOM_0xa9wrn, N_("Warning") },
1559                     { ATOM_0xa9swr, N_("Software") },
1560                     { ATOM_0xa9lyr, N_("Lyrics") },
1561                     { ATOM_0xa9mak, N_("Record Company") },
1562                     { ATOM_0xa9mod, N_("Model") },
1563                     { ATOM_0xa9PRD, N_("Product") },
1564                     { ATOM_0xa9grp, N_("Grouping") },
1565                     { ATOM_0xa9gen, N_("Genre") },
1566                     { ATOM_0xa9st3, N_("Sub-Title") },
1567                     { ATOM_0xa9arg, N_("Arranger") },
1568                     { ATOM_0xa9ard, N_("Art Director") },
1569                     { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1570                     { ATOM_0xa9con, N_("Conductor") },
1571                     { ATOM_0xa9des, N_("Song Description") },
1572                     { ATOM_0xa9lnt, N_("Liner Notes") },
1573                     { ATOM_0xa9phg, N_("Phonogram Rights") },
1574                     { ATOM_0xa9pub, N_("Publisher") },
1575                     { ATOM_0xa9sne, N_("Sound Engineer") },
1576                     { ATOM_0xa9sol, N_("Soloist") },
1577                     { ATOM_0xa9thx, N_("Thanks") },
1578                     { ATOM_0xa9xpd, N_("Executive Producer") },
1579                     { 0, "" },
1580                 };
1581                 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1582                 {
1583                     if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1584                     {
1585                         char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" );
1586                         if( psz_utf )
1587                         {
1588                              EnsureUTF8( psz_utf );
1589                              vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1590                              free( psz_utf );
1591                         }
1592                         break;
1593                     }
1594                 }
1595             }
1596             return VLC_SUCCESS;
1597         }
1598
1599         case DEMUX_GET_TITLE_INFO:
1600         {
1601             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1602             int *pi_int    = (int*)va_arg( args, int* );
1603             int *pi_title_offset = (int*)va_arg( args, int* );
1604             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1605
1606             if( !p_sys->p_title )
1607                 return VLC_EGENERIC;
1608
1609             *pi_int = 1;
1610             *ppp_title = malloc( sizeof( input_title_t*) );
1611             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1612             *pi_title_offset = 0;
1613             *pi_seekpoint_offset = 0;
1614             return VLC_SUCCESS;
1615         }
1616         case DEMUX_SET_TITLE:
1617         {
1618             const int i_title = (int)va_arg( args, int );
1619             if( !p_sys->p_title || i_title != 0 )
1620                 return VLC_EGENERIC;
1621             return VLC_SUCCESS;
1622         }
1623         case DEMUX_SET_SEEKPOINT:
1624         {
1625             const int i_seekpoint = (int)va_arg( args, int );
1626             if( !p_sys->p_title )
1627                 return VLC_EGENERIC;
1628             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1629         }
1630
1631         case DEMUX_SET_NEXT_DEMUX_TIME:
1632         case DEMUX_SET_GROUP:
1633         case DEMUX_HAS_UNSUPPORTED_META:
1634         case DEMUX_GET_PTS_DELAY:
1635         case DEMUX_CAN_RECORD:
1636             return VLC_EGENERIC;
1637
1638         default:
1639             msg_Warn( p_demux, "control query %u unimplemented", i_query );
1640             return VLC_EGENERIC;
1641     }
1642 }
1643
1644 /*****************************************************************************
1645  * Close: frees unused data
1646  *****************************************************************************/
1647 static void Close ( vlc_object_t * p_this )
1648 {
1649     demux_t *  p_demux = (demux_t *)p_this;
1650     demux_sys_t *p_sys = p_demux->p_sys;
1651     unsigned int i_track;
1652
1653     msg_Dbg( p_demux, "freeing all memory" );
1654
1655     MP4_BoxFree( p_demux->s, p_sys->p_root );
1656     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1657     {
1658         MP4_TrackDestroy(  &p_sys->track[i_track] );
1659     }
1660     FREENULL( p_sys->track );
1661
1662     if( p_sys->p_title )
1663         vlc_input_title_Delete( p_sys->p_title );
1664
1665     while( p_sys->moovfragment.p_next )
1666     {
1667         mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next->p_next;
1668         free( p_sys->moovfragment.p_next );
1669         p_sys->moovfragment.p_next = p_fragment;
1670     }
1671
1672     free( p_sys );
1673 }
1674
1675
1676
1677 /****************************************************************************
1678  * Local functions, specific to vlc
1679  ****************************************************************************/
1680 /* Chapters */
1681 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
1682 {
1683     demux_sys_t *p_sys = p_demux->p_sys;
1684     int i;
1685
1686     p_sys->p_title = vlc_input_title_New();
1687     for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
1688     {
1689         seekpoint_t *s = vlc_seekpoint_New();
1690
1691         s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
1692         EnsureUTF8( s->psz_name );
1693         s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
1694         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1695     }
1696 }
1697 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1698 {
1699     demux_sys_t *p_sys = p_demux->p_sys;
1700
1701     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1702     {
1703         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1704         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1705         uint32_t i_nb_samples = 0;
1706         const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
1707
1708         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1709         {
1710             char p_buffer[256];
1711             const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1712                                                     __MIN( sizeof(p_buffer), i_size ) );
1713             const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1714
1715             if( i_len > 0 )
1716             {
1717                 seekpoint_t *s = vlc_seekpoint_New();
1718
1719                 s->psz_name = strndup( &p_buffer[2], i_len );
1720                 EnsureUTF8( s->psz_name );
1721
1722                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1723
1724                 if( !p_sys->p_title )
1725                     p_sys->p_title = vlc_input_title_New();
1726                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1727             }
1728         }
1729         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1730                               tk->chunk[tk->i_chunk].i_sample_count )
1731             tk->i_chunk++;
1732     }
1733 }
1734 static void LoadChapter( demux_t  *p_demux )
1735 {
1736     demux_sys_t *p_sys = p_demux->p_sys;
1737     MP4_Box_t *p_chpl;
1738
1739     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
1740           BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
1741     {
1742         LoadChapterGpac( p_demux, p_chpl );
1743     }
1744     else if( p_sys->p_tref_chap )
1745     {
1746         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1747         unsigned int i, j;
1748
1749         /* Load the first subtitle track like quicktime */
1750         for( i = 0; i < p_chap->i_entry_count; i++ )
1751         {
1752             for( j = 0; j < p_sys->i_tracks; j++ )
1753             {
1754                 mp4_track_t *tk = &p_sys->track[j];
1755                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1756                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1757                     break;
1758             }
1759             if( j < p_sys->i_tracks )
1760             {
1761                 LoadChapterApple( p_demux, &p_sys->track[j] );
1762                 break;
1763             }
1764         }
1765     }
1766
1767     /* Add duration if titles are enabled */
1768     if( p_sys->p_title )
1769     {
1770         p_sys->p_title->i_length = CLOCK_FREQ *
1771                        (uint64_t)p_sys->i_overall_duration / (uint64_t)p_sys->i_timescale;
1772     }
1773 }
1774
1775 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1776 static int TrackCreateChunksIndex( demux_t *p_demux,
1777                                    mp4_track_t *p_demux_track )
1778 {
1779     demux_sys_t *p_sys = p_demux->p_sys;
1780
1781     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1782     MP4_Box_t *p_stsc;
1783
1784     unsigned int i_chunk;
1785     unsigned int i_index, i_last;
1786
1787     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1788           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1789         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1790     {
1791         return( VLC_EGENERIC );
1792     }
1793
1794     p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
1795     if( !p_demux_track->i_chunk_count )
1796     {
1797         msg_Warn( p_demux, "no chunk defined" );
1798     }
1799     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1800                                    sizeof( mp4_chunk_t ) );
1801     if( p_demux_track->chunk == NULL )
1802     {
1803         return VLC_ENOMEM;
1804     }
1805
1806     /* first we read chunk offset */
1807     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1808     {
1809         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1810
1811         ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
1812
1813         ck->i_first_dts = 0;
1814         ck->p_sample_count_dts = NULL;
1815         ck->p_sample_delta_dts = NULL;
1816         ck->p_sample_count_pts = NULL;
1817         ck->p_sample_offset_pts = NULL;
1818     }
1819
1820     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1821         to be used for the sample XXX begin to 1
1822         We construct it begining at the end */
1823     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1824     i_index = BOXDATA(p_stsc)->i_entry_count;
1825
1826     while( i_index-- > 0 )
1827     {
1828         for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1829              i_chunk < i_last; i_chunk++ )
1830         {
1831             if( i_chunk >= p_demux_track->i_chunk_count )
1832             {
1833                 msg_Warn( p_demux, "corrupted chunk table" );
1834                 return VLC_EGENERIC;
1835             }
1836
1837             p_demux_track->chunk[i_chunk].i_sample_description_index =
1838                     BOXDATA(p_stsc)->i_sample_description_index[i_index];
1839             p_demux_track->chunk[i_chunk].i_sample_count =
1840                     BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
1841         }
1842         i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1843     }
1844
1845     if ( p_demux_track->i_chunk_count )
1846     {
1847         p_demux_track->chunk[0].i_sample_first = 0;
1848         for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1849         {
1850             p_demux_track->chunk[i_chunk].i_sample_first =
1851                 p_demux_track->chunk[i_chunk-1].i_sample_first +
1852                     p_demux_track->chunk[i_chunk-1].i_sample_count;
1853         }
1854     }
1855
1856     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1857              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1858
1859     if ( p_demux_track->i_chunk_count && (
1860              p_sys->moovfragment.i_chunk_range_min_offset == 0 ||
1861              p_sys->moovfragment.i_chunk_range_min_offset > p_demux_track->chunk[0].i_offset
1862              ) )
1863         p_sys->moovfragment.i_chunk_range_min_offset = p_demux_track->chunk[0].i_offset;
1864
1865     return VLC_SUCCESS;
1866 }
1867
1868 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1869                               const uint32_t i_index,
1870                               uint32_t i_index_samples_left,
1871                               uint32_t i_sample_count,
1872                               const uint32_t *pi_index_sample_count,
1873                               const uint32_t i_table_count )
1874 {
1875     uint32_t i_array_offset;
1876     while( i_sample_count > 0 )
1877     {
1878         if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1879             i_array_offset = i_index + *pi_entry;
1880         else
1881             return VLC_EGENERIC;
1882
1883         if ( i_array_offset >= i_table_count )
1884         {
1885             msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset,  i_table_count );
1886             return VLC_EGENERIC;
1887         }
1888
1889         if ( i_index_samples_left )
1890         {
1891             if ( i_index_samples_left > i_sample_count )
1892             {
1893                 i_index_samples_left -= i_sample_count;
1894                 i_sample_count = 0;
1895                 *pi_entry +=1; /* No samples left, go copy */
1896                 break;
1897             }
1898             else
1899             {
1900                 i_sample_count -= i_index_samples_left;
1901                 i_index_samples_left = 0;
1902                 *pi_entry += 1;
1903                 continue;
1904             }
1905         }
1906         else
1907         {
1908             i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1909             *pi_entry += 1;
1910         }
1911     }
1912
1913     return VLC_SUCCESS;
1914 }
1915
1916 static int TrackCreateSamplesIndex( demux_t *p_demux,
1917                                     mp4_track_t *p_demux_track )
1918 {
1919     demux_sys_t *p_sys = p_demux->p_sys;
1920
1921     MP4_Box_t *p_box;
1922     MP4_Box_data_stsz_t *stsz;
1923     /* TODO use also stss and stsh table for seeking */
1924     /* FIXME use edit table */
1925
1926     /* Find stsz
1927      *  Gives the sample size for each samples. There is also a stz2 table
1928      *  (compressed form) that we need to implement TODO */
1929     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1930     if( !p_box )
1931     {
1932         /* FIXME and stz2 */
1933         msg_Warn( p_demux, "cannot find STSZ box" );
1934         return VLC_EGENERIC;
1935     }
1936     stsz = p_box->data.p_stsz;
1937
1938     /* Use stsz table to create a sample number -> sample size table */
1939     p_demux_track->i_sample_count = stsz->i_sample_count;
1940     if( stsz->i_sample_size )
1941     {
1942         /* 1: all sample have the same size, so no need to construct a table */
1943         p_demux_track->i_sample_size = stsz->i_sample_size;
1944         p_demux_track->p_sample_size = NULL;
1945     }
1946     else
1947     {
1948         /* 2: each sample can have a different size */
1949         p_demux_track->i_sample_size = 0;
1950         p_demux_track->p_sample_size =
1951             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1952         if( p_demux_track->p_sample_size == NULL )
1953             return VLC_ENOMEM;
1954
1955         for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1956         {
1957             p_demux_track->p_sample_size[i_sample] =
1958                     stsz->i_entry_size[i_sample];
1959         }
1960     }
1961
1962     if ( p_demux_track->i_chunk_count )
1963     {
1964         mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
1965         uint64_t i_total_size = lastchunk->i_offset;
1966         for( uint32_t i=0; i<lastchunk->i_sample_count; i++)
1967         {
1968             if( p_demux_track->i_sample_size == 0 )
1969                 i_total_size += stsz->i_entry_size[i];
1970             else
1971                 i_total_size += p_demux_track->i_sample_size;
1972         }
1973
1974         if ( i_total_size > p_sys->moovfragment.i_chunk_range_max_offset )
1975             p_sys->moovfragment.i_chunk_range_max_offset = i_total_size;
1976     }
1977
1978     /* Use stts table to create a sample number -> dts table.
1979      * XXX: if we don't want to waste too much memory, we can't expand
1980      *  the box! so each chunk will contain an "extract" of this table
1981      *  for fast research (problem with raw stream where a sample is sometime
1982      *  just channels*bits_per_sample/8 */
1983
1984      /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1985       *        differing in 2/2 fields and 1 signedness */
1986
1987     mtime_t i_next_dts = 0;
1988     /* Find stts
1989      *  Gives mapping between sample and decoding time
1990      */
1991     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1992     if( !p_box )
1993     {
1994         msg_Warn( p_demux, "cannot find STTS box" );
1995         return VLC_EGENERIC;
1996     }
1997     else
1998     {
1999         MP4_Box_data_stts_t *stts = p_box->data.p_stts;
2000
2001         msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
2002
2003         /* Create sample -> dts table per chunk */
2004         uint32_t i_index = 0;
2005         uint32_t i_current_index_samples_left = 0;
2006
2007         for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2008         {
2009             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2010             uint32_t i_entry, i_sample_count;
2011
2012             /* save first dts */
2013             ck->i_first_dts = i_next_dts;
2014             ck->i_last_dts  = i_next_dts;
2015
2016             /* count how many entries are needed for this chunk
2017              * for p_sample_delta_dts and p_sample_count_dts */
2018             i_entry = 0;
2019
2020             int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2021                                            i_current_index_samples_left,
2022                                            ck->i_sample_count,
2023                                            stts->pi_sample_count,
2024                                            stts->i_entry_count );
2025             if ( i_ret != VLC_SUCCESS )
2026                 return i_ret;
2027
2028             /* allocate them */
2029             ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
2030             ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
2031             if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
2032             {
2033                 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2034                 return VLC_ENOMEM;
2035             }
2036
2037             /* now copy */
2038             i_sample_count = ck->i_sample_count;
2039
2040             for( uint32_t i = 0; i < i_entry; i++ )
2041             {
2042                 if ( i_current_index_samples_left )
2043                 {
2044                     if ( i_current_index_samples_left > i_sample_count )
2045                     {
2046                         if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2047                         ck->p_sample_count_dts[i] = i_sample_count;
2048                         ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2049                         i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2050                         i_current_index_samples_left -= i_sample_count;
2051                         i_sample_count = 0;
2052                         assert( i == i_entry - 1 );
2053                         break;
2054                     }
2055                     else
2056                     {
2057                         if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
2058                         ck->p_sample_count_dts[i] = i_current_index_samples_left;
2059                         ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2060                         i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2061                         i_sample_count -= i_current_index_samples_left;
2062                         i_current_index_samples_left = 0;
2063                         i_index++;
2064                     }
2065                 }
2066                 else
2067                 {
2068                     if ( stts->pi_sample_count[i_index] > i_sample_count )
2069                     {
2070                         if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2071                         ck->p_sample_count_dts[i] = i_sample_count;
2072                         ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2073                         i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2074                         i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
2075                         i_sample_count = 0;
2076                         assert( i == i_entry - 1 );
2077                         // keep building from same index
2078                     }
2079                     else
2080                     {
2081                         if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
2082                         ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
2083                         ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2084                         i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2085                         i_sample_count -= stts->pi_sample_count[i_index];
2086                         i_index++;
2087                     }
2088                 }
2089
2090             }
2091         }
2092     }
2093
2094
2095     /* Find ctts
2096      *  Gives the delta between decoding time (dts) and composition table (pts)
2097      */
2098     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
2099     if( p_box && p_box->data.p_ctts )
2100     {
2101         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
2102
2103         msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
2104
2105         /* Create pts-dts table per chunk */
2106         uint32_t i_index = 0;
2107         uint32_t i_current_index_samples_left = 0;
2108
2109         for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2110         {
2111             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2112             uint32_t i_entry, i_sample_count;
2113
2114             /* count how many entries are needed for this chunk
2115              * for p_sample_offset_pts and p_sample_count_pts */
2116             i_entry = 0;
2117             int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2118                                            i_current_index_samples_left,
2119                                            ck->i_sample_count,
2120                                            ctts->pi_sample_count,
2121                                            ctts->i_entry_count );
2122             if ( i_ret != VLC_SUCCESS )
2123                 return i_ret;
2124
2125             /* allocate them */
2126             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
2127             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
2128             if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
2129             {
2130                 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2131                 return VLC_ENOMEM;
2132             }
2133
2134             /* now copy */
2135             i_sample_count = ck->i_sample_count;
2136
2137             for( uint32_t i = 0; i < i_entry; i++ )
2138             {
2139                 if ( i_current_index_samples_left )
2140                 {
2141                     if ( i_current_index_samples_left > i_sample_count )
2142                     {
2143                         ck->p_sample_count_pts[i] = i_sample_count;
2144                         ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2145                         i_current_index_samples_left -= i_sample_count;
2146                         i_sample_count = 0;
2147                         assert( i == i_entry - 1 );
2148                         break;
2149                     }
2150                     else
2151                     {
2152                         ck->p_sample_count_pts[i] = i_current_index_samples_left;
2153                         ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2154                         i_sample_count -= i_current_index_samples_left;
2155                         i_current_index_samples_left = 0;
2156                         i_index++;
2157                     }
2158                 }
2159                 else
2160                 {
2161                     if ( ctts->pi_sample_count[i_index] > i_sample_count )
2162                     {
2163                         ck->p_sample_count_pts[i] = i_sample_count;
2164                         ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2165                         i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
2166                         i_sample_count = 0;
2167                         assert( i == i_entry - 1 );
2168                         // keep building from same index
2169                     }
2170                     else
2171                     {
2172                         ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
2173                         ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2174                         i_sample_count -= ctts->pi_sample_count[i_index];
2175                         i_index++;
2176                     }
2177                 }
2178
2179
2180             }
2181         }
2182     }
2183
2184     msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
2185              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
2186              i_next_dts / p_demux_track->i_timescale );
2187
2188     return VLC_SUCCESS;
2189 }
2190
2191
2192 /**
2193  * It computes the sample rate for a video track using the given sample
2194  * description index
2195  */
2196 static void TrackGetESSampleRate( demux_t *p_demux,
2197                                   unsigned *pi_num, unsigned *pi_den,
2198                                   const mp4_track_t *p_track,
2199                                   unsigned i_sd_index,
2200                                   unsigned i_chunk )
2201 {
2202     *pi_num = 0;
2203     *pi_den = 0;
2204
2205     MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_demux->p_sys->p_root, "/moov" ),
2206                                               p_track->i_track_ID );
2207     MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
2208     if ( p_mdhd && BOXDATA(p_mdhd) )
2209     {
2210         vlc_ureduce( pi_num, pi_den,
2211                      (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
2212                      (uint64_t) BOXDATA(p_mdhd)->i_duration,
2213                      UINT16_MAX );
2214         return;
2215     }
2216
2217     if( p_track->i_chunk_count <= 0 )
2218         return;
2219
2220     /* */
2221     const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
2222     while( p_chunk > &p_track->chunk[0] &&
2223            p_chunk[-1].i_sample_description_index == i_sd_index )
2224     {
2225         p_chunk--;
2226     }
2227
2228     uint64_t i_sample = 0;
2229     uint64_t i_first_dts = p_chunk->i_first_dts;
2230     uint64_t i_last_dts;
2231     do
2232     {
2233         i_sample += p_chunk->i_sample_count;
2234         i_last_dts = p_chunk->i_last_dts;
2235         p_chunk++;
2236     }
2237     while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
2238            p_chunk->i_sample_description_index == i_sd_index );
2239
2240     if( i_sample > 1 && i_first_dts < i_last_dts )
2241         vlc_ureduce( pi_num, pi_den,
2242                      ( i_sample - 1) *  p_track->i_timescale,
2243                      i_last_dts - i_first_dts,
2244                      UINT16_MAX);
2245 }
2246
2247 /*
2248  * TrackCreateES:
2249  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
2250  */
2251 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
2252                           unsigned int i_chunk, es_out_id_t **pp_es )
2253 {
2254     demux_sys_t *p_sys = p_demux->p_sys;
2255     unsigned int i_sample_description_index;
2256
2257     if( p_sys->b_fragmented )
2258         i_sample_description_index = 1; /* XXX */
2259     else
2260         i_sample_description_index =
2261                 p_track->chunk[i_chunk].i_sample_description_index;
2262
2263     MP4_Box_t   *p_sample;
2264     MP4_Box_t   *p_esds;
2265     MP4_Box_t   *p_frma;
2266     MP4_Box_t   *p_enda;
2267     MP4_Box_t   *p_pasp;
2268
2269     if( pp_es )
2270         *pp_es = NULL;
2271
2272     if( !i_sample_description_index )
2273     {
2274         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
2275                   p_track->i_track_ID );
2276         return VLC_EGENERIC;
2277     }
2278
2279     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
2280                             i_sample_description_index - 1 );
2281
2282     if( !p_sample ||
2283         ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
2284     {
2285         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
2286                   p_track->i_track_ID );
2287         return VLC_EGENERIC;
2288     }
2289
2290     p_track->p_sample = p_sample;
2291
2292     if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) && p_frma->data.p_frma )
2293     {
2294         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
2295
2296         p_sample->i_type = p_frma->data.p_frma->i_type;
2297     }
2298
2299     p_enda = MP4_BoxGet( p_sample, "wave/enda" );
2300     if( !p_enda )
2301         p_enda = MP4_BoxGet( p_sample, "enda" );
2302
2303     p_pasp = MP4_BoxGet( p_sample, "pasp" );
2304
2305     /* */
2306     switch( p_track->fmt.i_cat )
2307     {
2308     case VIDEO_ES:
2309         if ( !p_sample->data.p_sample_vide )
2310             break;
2311         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
2312         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
2313         p_track->fmt.video.i_bits_per_pixel =
2314             p_sample->data.p_sample_vide->i_depth;
2315
2316         /* fall on display size */
2317         if( p_track->fmt.video.i_width <= 0 )
2318             p_track->fmt.video.i_width = p_track->i_width;
2319         if( p_track->fmt.video.i_height <= 0 )
2320             p_track->fmt.video.i_height = p_track->i_height;
2321
2322         /* Find out apect ratio from display size */
2323         if( p_track->i_width > 0 && p_track->i_height > 0 &&
2324             /* Work-around buggy muxed files */
2325             p_sample->data.p_sample_vide->i_width != p_track->i_width )
2326         {
2327             p_track->fmt.video.i_sar_num = p_track->i_width  * p_track->fmt.video.i_height;
2328             p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
2329         }
2330         if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
2331                       p_pasp->data.p_pasp->i_vertical_spacing > 0 )
2332         {
2333             p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
2334             p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
2335         }
2336
2337         /* Support for cropping (eg. in H263 files) */
2338         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
2339         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
2340
2341         /* Frame rate */
2342         TrackGetESSampleRate( p_demux,
2343                               &p_track->fmt.video.i_frame_rate,
2344                               &p_track->fmt.video.i_frame_rate_base,
2345                               p_track, i_sample_description_index, i_chunk );
2346
2347         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
2348                                 (float)p_track->fmt.video.i_frame_rate_base;
2349
2350         /* Rotation */
2351         switch( (int)p_track->f_rotation ) {
2352             case 90:
2353                 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
2354                 break;
2355             case 180:
2356                 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
2357                 break;
2358             case 270:
2359                 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
2360                 break;
2361         }
2362
2363         break;
2364
2365     case AUDIO_ES:
2366         if ( !p_sample->data.p_sample_soun )
2367             break;
2368         p_track->fmt.audio.i_channels =
2369             p_sample->data.p_sample_soun->i_channelcount;
2370         p_track->fmt.audio.i_rate =
2371             p_sample->data.p_sample_soun->i_sampleratehi;
2372         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
2373             p_sample->data.p_sample_soun->i_sampleratehi *
2374                 p_sample->data.p_sample_soun->i_samplesize;
2375         p_track->fmt.audio.i_bitspersample =
2376             p_sample->data.p_sample_soun->i_samplesize;
2377
2378         MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2379
2380         p_track->fmt.i_original_fourcc = p_sample->i_type;
2381
2382         if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
2383         {
2384             if( p_soun->i_qt_version == 0 )
2385             {
2386                 switch( p_sample->i_type )
2387                 {
2388                     case VLC_CODEC_ADPCM_IMA_QT:
2389                         p_soun->i_qt_version = 1;
2390                         p_soun->i_sample_per_packet = 64;
2391                         p_soun->i_bytes_per_packet  = 34;
2392                         p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
2393                         p_soun->i_bytes_per_sample  = 2;
2394                         break;
2395                     case VLC_CODEC_MACE3:
2396                         p_soun->i_qt_version = 1;
2397                         p_soun->i_sample_per_packet = 6;
2398                         p_soun->i_bytes_per_packet  = 2;
2399                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
2400                         p_soun->i_bytes_per_sample  = 2;
2401                         break;
2402                     case VLC_CODEC_MACE6:
2403                         p_soun->i_qt_version = 1;
2404                         p_soun->i_sample_per_packet = 12;
2405                         p_soun->i_bytes_per_packet  = 2;
2406                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
2407                         p_soun->i_bytes_per_sample  = 2;
2408                         break;
2409                     case VLC_CODEC_ALAW:
2410                     case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
2411                         p_soun->i_samplesize = 8;
2412                         p_track->i_sample_size = p_soun->i_channelcount;
2413                         break;
2414                     case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
2415                     case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
2416                     case VLC_FOURCC( 't', 'w', 'o', 's' ):
2417                     case VLC_FOURCC( 's', 'o', 'w', 't' ):
2418                         /* What would be the fun if you could trust the .mov */
2419                         p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
2420                         break;
2421                     default:
2422                         break;
2423                 }
2424
2425             }
2426             else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
2427             {
2428                 p_soun->i_qt_version = 0;
2429             }
2430         }
2431         else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
2432         {
2433             switch( p_sample->i_type )
2434             {
2435                 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2436                 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2437                     {
2438                         if( p_track->i_sample_size > 1 )
2439                             p_soun->i_qt_version = 0;
2440                         break;
2441                     }
2442                 case( ATOM_ac3 ):
2443                 case( ATOM_eac3 ):
2444                 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2445                     p_soun->i_qt_version = 0;
2446                     break;
2447                 default:
2448                     break;
2449             }
2450         }
2451
2452         if( p_track->i_sample_size != 0 &&
2453                 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2454                 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2455         {
2456             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2457             p_sample->data.p_sample_soun->i_qt_version = 0;
2458         }
2459
2460         /* Lookup for then channels extension */
2461         const MP4_Box_t *p_chan = MP4_BoxGet( p_sample, "chan" );
2462         if ( p_chan )
2463         {
2464             if ( BOXDATA(p_chan)->layout.i_channels_layout_tag == MP4_CHAN_USE_CHANNELS_BITMAP )
2465             {
2466                 uint32_t rgi_chans_sequence[AOUT_CHAN_MAX + 1];
2467                 uint16_t i_vlc_mapping = 0;
2468                 uint8_t i_channels = 0;
2469                 const uint32_t i_bitmap = BOXDATA(p_chan)->layout.i_channels_bitmap;
2470                 for (uint8_t i=0;i<MP4_CHAN_BITMAP_MAPPING_COUNT;i++)
2471                 {
2472                     if ( chan_bitmap_mapping[i].i_bitmap & i_bitmap )
2473                     {
2474                         i_channels++;
2475                         if ( (chan_bitmap_mapping[i].i_vlc & i_vlc_mapping) ||
2476                              i_channels > AOUT_CHAN_MAX )
2477                         {
2478                             /* double mapping or unsupported number of channels */
2479                             i_vlc_mapping = 0;
2480                             msg_Warn( p_demux, "discarding chan mapping" );
2481                             break;
2482                         }
2483                         i_vlc_mapping |= chan_bitmap_mapping[i].i_vlc;
2484                         rgi_chans_sequence[i_channels - 1] = chan_bitmap_mapping[i].i_vlc;
2485                     }
2486                 }
2487                 rgi_chans_sequence[i_channels] = 0;
2488                 p_track->b_chans_reorder = !!
2489                         aout_CheckChannelReorder( rgi_chans_sequence, NULL, i_vlc_mapping,
2490                                                   p_track->rgi_chans_reordering );
2491             }
2492
2493         }
2494
2495         break;
2496
2497     default:
2498         break;
2499     }
2500
2501     /* It's a little ugly but .. there are special cases */
2502     switch( p_sample->i_type )
2503     {
2504         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2505         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2506         {
2507             p_track->fmt.i_codec = VLC_CODEC_MPGA;
2508             break;
2509         }
2510         case( ATOM_eac3 ):
2511         {
2512             MP4_Box_t *p_dec3_box = MP4_BoxGet(  p_sample, "dec3", 0 );
2513
2514             p_track->fmt.i_codec = VLC_CODEC_EAC3;
2515             if( p_dec3_box )
2516             {
2517                 MP4_Box_data_dec3_t *p_dec3 = p_dec3_box->data.p_dec3;
2518                 p_track->fmt.audio.i_channels = 0;
2519                 p_track->fmt.i_bitrate = p_dec3->i_data_rate * 1000;
2520                 p_track->fmt.audio.i_bitspersample = 0;
2521             }
2522             break;
2523         }
2524         case( ATOM_ac3 ):
2525         {
2526             MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
2527
2528             p_track->fmt.i_codec = VLC_CODEC_A52;
2529             if( p_dac3_box )
2530             {
2531                 static const int pi_bitrate[] = {
2532                      32,  40,  48,  56,
2533                      64,  80,  96, 112,
2534                     128, 160, 192, 224,
2535                     256, 320, 384, 448,
2536                     512, 576, 640,
2537                 };
2538                 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2539                 p_track->fmt.audio.i_channels = 0;
2540                 p_track->fmt.i_bitrate = 0;
2541                 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2542                     p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2543                 p_track->fmt.audio.i_bitspersample = 0;
2544             }
2545             break;
2546         }
2547
2548         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2549         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2550         {
2551             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2552
2553             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2554                 p_track->fmt.i_codec = VLC_CODEC_U8;
2555             else
2556                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2557
2558             /* Buggy files workaround */
2559             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2560                 p_sample->data.p_sample_soun->i_sampleratehi) )
2561             {
2562                 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2563                           "(%u), making both equal (report any problem).",
2564                           p_track->i_timescale, p_soun->i_sampleratehi );
2565
2566                 if( p_soun->i_sampleratehi != 0 )
2567                     p_track->i_timescale = p_soun->i_sampleratehi;
2568                 else
2569                     p_soun->i_sampleratehi = p_track->i_timescale;
2570             }
2571             break;
2572         }
2573
2574         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2575             p_track->fmt.i_codec = VLC_CODEC_H263;
2576             break;
2577
2578         case( ATOM_c608 ): /* EIA608 closed captions */
2579         //case( ATOM_c708 ): /* EIA708 closed captions */
2580             p_track->fmt.i_codec = VLC_CODEC_EIA608_1;
2581             p_track->fmt.i_cat = SPU_ES;
2582             break;
2583
2584         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2585         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2586         {
2587             p_track->fmt.i_codec = VLC_CODEC_TX3G;
2588             MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2589             if ( p_text )
2590             {
2591                 text_style_t *p_style = text_style_New();
2592                 if ( p_style )
2593                 {
2594                     if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2595                         p_style->i_font_size = p_text->i_font_size;
2596                     if ( p_text->i_font_color )
2597                     {
2598                         p_style->i_font_color = p_text->i_font_color >> 8;
2599                         p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2600                     }
2601                     if ( p_text->i_background_color[3] >> 8 )
2602                     {
2603                         p_style->i_background_color = p_text->i_background_color[0] >> 8;
2604                         p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2605                         p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2606                         p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2607                     }
2608                 }
2609                 p_track->fmt.subs.p_style = p_style;
2610             }
2611             /* FIXME UTF-8 doesn't work here ? */
2612             if( p_track->b_mac_encoding )
2613                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2614             else
2615                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2616             break;
2617         }
2618         case VLC_FOURCC('y','v','1','2'):
2619             p_track->fmt.i_codec = VLC_CODEC_YV12;
2620             break;
2621         case VLC_FOURCC('y','u','v','2'):
2622             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2623             break;
2624
2625         case VLC_FOURCC('i','n','2','4'):
2626             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2627                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2628             break;
2629         case VLC_FOURCC('i','n','3','2'):
2630             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2631                                     VLC_CODEC_S32L : VLC_CODEC_S32B;
2632             break;
2633         case VLC_FOURCC('f','l','3','2'):
2634             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2635                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
2636             break;
2637         case VLC_FOURCC('f','l','6','4'):
2638             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2639                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
2640             break;
2641         case VLC_CODEC_DVD_LPCM:
2642         {
2643             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2644             if( p_soun->i_qt_version == 2 )
2645             {
2646                 /* Flags:
2647                  *  0x01: IsFloat
2648                  *  0x02: IsBigEndian
2649                  *  0x04: IsSigned
2650                  */
2651                 static const struct {
2652                     unsigned     i_flags;
2653                     unsigned     i_mask;
2654                     unsigned     i_bits;
2655                     vlc_fourcc_t i_codec;
2656                 } p_formats[] = {
2657                     { 0x01,           0x03, 32, VLC_CODEC_F32L },
2658                     { 0x01,           0x03, 64, VLC_CODEC_F64L },
2659                     { 0x01|0x02,      0x03, 32, VLC_CODEC_F32B },
2660                     { 0x01|0x02,      0x03, 64, VLC_CODEC_F64B },
2661
2662                     { 0x00,           0x05,  8, VLC_CODEC_U8 },
2663                     { 0x00|     0x04, 0x05,  8, VLC_CODEC_S8 },
2664
2665                     { 0x00,           0x07, 16, VLC_CODEC_U16L },
2666                     { 0x00|0x02,      0x07, 16, VLC_CODEC_U16B },
2667                     { 0x00     |0x04, 0x07, 16, VLC_CODEC_S16L },
2668                     { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2669
2670                     { 0x00,           0x07, 24, VLC_CODEC_U24L },
2671                     { 0x00|0x02,      0x07, 24, VLC_CODEC_U24B },
2672                     { 0x00     |0x04, 0x07, 24, VLC_CODEC_S24L },
2673                     { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2674
2675                     { 0x00,           0x07, 32, VLC_CODEC_U32L },
2676                     { 0x00|0x02,      0x07, 32, VLC_CODEC_U32B },
2677                     { 0x00     |0x04, 0x07, 32, VLC_CODEC_S32L },
2678                     { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2679
2680                     {0, 0, 0, 0}
2681                 };
2682
2683                 for( int i = 0; p_formats[i].i_codec; i++ )
2684                 {
2685                     if( p_formats[i].i_bits == p_soun->i_constbitsperchannel &&
2686                         (p_soun->i_formatflags & p_formats[i].i_mask) == p_formats[i].i_flags )
2687                     {
2688                         p_track->fmt.i_codec = p_formats[i].i_codec;
2689                         p_track->fmt.audio.i_bitspersample = p_soun->i_constbitsperchannel;
2690                         p_track->fmt.audio.i_blockalign =
2691                                 p_soun->i_channelcount * p_soun->i_constbitsperchannel / 8;
2692                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2693
2694                         p_soun->i_qt_version = 0;
2695                         break;
2696                     }
2697                 }
2698             }
2699             break;
2700         }
2701         default:
2702             p_track->fmt.i_codec = p_sample->i_type;
2703             break;
2704     }
2705
2706     /* now see if esds is present and if so create a data packet
2707         with decoder_specific_info  */
2708 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2709     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2710           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2711         ( p_esds->data.p_esds )&&
2712         ( p_decconfig ) )
2713     {
2714         /* First update information based on i_objectTypeIndication */
2715         switch( p_decconfig->i_objectTypeIndication )
2716         {
2717             case( 0x20 ): /* MPEG4 VIDEO */
2718                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2719                 break;
2720             case( 0x21 ): /* H.264 */
2721                 p_track->fmt.i_codec = VLC_CODEC_H264;
2722                 break;
2723             case( 0x40):
2724                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2725                 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2726                      p_decconfig->p_decoder_specific_info[0]       == 0xF8 &&
2727                     (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2728                 {
2729                     p_track->fmt.i_codec = VLC_CODEC_ALS;
2730                 }
2731                 break;
2732             case( 0x60):
2733             case( 0x61):
2734             case( 0x62):
2735             case( 0x63):
2736             case( 0x64):
2737             case( 0x65): /* MPEG2 video */
2738                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2739                 break;
2740             /* Theses are MPEG2-AAC */
2741             case( 0x66): /* main profile */
2742             case( 0x67): /* Low complexity profile */
2743             case( 0x68): /* Scaleable Sampling rate profile */
2744                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2745                 break;
2746             /* True MPEG 2 audio */
2747             case( 0x69):
2748                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2749                 break;
2750             case( 0x6a): /* MPEG1 video */
2751                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2752                 break;
2753             case( 0x6b): /* MPEG1 audio */
2754                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2755                 break;
2756             case( 0x6c ): /* jpeg */
2757                 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2758                 break;
2759             case( 0x6d ): /* png */
2760                 p_track->fmt.i_codec = VLC_CODEC_PNG;
2761                 break;
2762             case( 0x6e ): /* jpeg2000 */
2763                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2764                 break;
2765             case( 0xa3 ): /* vc1 */
2766                 p_track->fmt.i_codec = VLC_CODEC_VC1;
2767                 break;
2768             case( 0xa4 ):
2769                 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2770                 break;
2771             case( 0xa5 ):
2772                 p_track->fmt.i_codec = VLC_CODEC_A52;
2773                 break;
2774             case( 0xa6 ):
2775                 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2776                 break;
2777             case( 0xa9 ): /* dts */
2778             case( 0xaa ): /* DTS-HD HRA */
2779             case( 0xab ): /* DTS-HD Master Audio */
2780                 p_track->fmt.i_codec = VLC_CODEC_DTS;
2781                 break;
2782             case( 0xDD ):
2783                 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2784                 break;
2785
2786             /* Private ID */
2787             case( 0xe0 ): /* NeroDigital: dvd subs */
2788                 if( p_track->fmt.i_cat == SPU_ES )
2789                 {
2790                     p_track->fmt.i_codec = VLC_CODEC_SPU;
2791                     if( p_track->i_width > 0 )
2792                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2793                     if( p_track->i_height > 0 )
2794                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2795                     break;
2796                 }
2797             case( 0xe1 ): /* QCelp for 3gp */
2798                 if( p_track->fmt.i_cat == AUDIO_ES )
2799                 {
2800                     p_track->fmt.i_codec = VLC_CODEC_QCELP;
2801                 }
2802                 break;
2803
2804             /* Fallback */
2805             default:
2806                 /* Unknown entry, but don't touch i_fourcc */
2807                 msg_Warn( p_demux,
2808                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2809                           p_decconfig->i_objectTypeIndication,
2810                           p_track->i_track_ID );
2811                 break;
2812         }
2813         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2814         if( p_track->fmt.i_extra > 0 )
2815         {
2816             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2817             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2818                     p_track->fmt.i_extra );
2819         }
2820         if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2821             p_track->fmt.i_extra >= 16 * 4 )
2822         {
2823             for( int i = 0; i < 16; i++ )
2824             {
2825                 p_track->fmt.subs.spu.palette[1 + i] =
2826                             GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2827             }
2828             p_track->fmt.subs.spu.palette[0] = 0xBeef;
2829         }
2830     }
2831     else
2832     {
2833         switch( p_sample->i_type )
2834         {
2835             /* qt decoder, send the complete chunk */
2836             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2837             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2838             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2839             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2840             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2841             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2842             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2843             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2844             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2845             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2846             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2847             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2848                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2849                 break;
2850             /* qt decoder, send the complete chunk */
2851             case VLC_CODEC_SVQ1:
2852             case VLC_CODEC_SVQ3:
2853             case VLC_FOURCC( 'V', 'P', '3', '1' ):
2854             case VLC_FOURCC( '3', 'I', 'V', '1' ):
2855             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2856                 p_track->fmt.i_extra =
2857                     p_sample->data.p_sample_vide->i_qt_image_description;
2858                 if( p_track->fmt.i_extra > 0 )
2859                 {
2860                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2861                     memcpy( p_track->fmt.p_extra,
2862                             p_sample->data.p_sample_vide->p_qt_image_description,
2863                             p_track->fmt.i_extra);
2864                 }
2865                 break;
2866
2867             case VLC_CODEC_AMR_NB:
2868                 p_track->fmt.audio.i_rate = 8000;
2869                 break;
2870             case VLC_CODEC_AMR_WB:
2871                 p_track->fmt.audio.i_rate = 16000;
2872                 break;
2873             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2874             case VLC_CODEC_QDM2:
2875             case VLC_CODEC_ALAC:
2876                 p_track->fmt.i_extra =
2877                     p_sample->data.p_sample_soun->i_qt_description;
2878                 if( p_track->fmt.i_extra > 0 )
2879                 {
2880                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2881                     memcpy( p_track->fmt.p_extra,
2882                             p_sample->data.p_sample_soun->p_qt_description,
2883                             p_track->fmt.i_extra);
2884                 }
2885                 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2886                 {
2887                     p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2888                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2889                 }
2890                 break;
2891
2892             case VLC_FOURCC( 'v', 'c', '-', '1' ):
2893             {
2894                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2895                 if( p_dvc1 )
2896                 {
2897                     p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
2898                     if( p_track->fmt.i_extra > 0 )
2899                     {
2900                         p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
2901                         memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
2902                                 p_track->fmt.i_extra );
2903                     }
2904                 }
2905                 else
2906                 {
2907                     msg_Err( p_demux, "missing dvc1" );
2908                 }
2909                 break;
2910             }
2911
2912             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2913             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2914             {
2915                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2916
2917                 if( p_avcC )
2918                 {
2919                     p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
2920                     if( p_track->fmt.i_extra > 0 )
2921                     {
2922                         p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
2923                         memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
2924                                 p_track->fmt.i_extra );
2925                     }
2926                 }
2927                 else
2928                 {
2929                     msg_Err( p_demux, "missing avcC" );
2930                 }
2931                 break;
2932             }
2933             case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2934             case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2935             {
2936                 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2937
2938                 if( p_hvcC )
2939                 {
2940                     p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2941                     if( p_track->fmt.i_extra > 0 )
2942                     {
2943                         p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2944                         memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2945                                 p_track->fmt.i_extra );
2946                     }
2947                     p_track->fmt.i_codec = VLC_CODEC_HEVC;
2948                 }
2949                 else
2950                 {
2951                     msg_Err( p_demux, "missing hvcC" );
2952                 }
2953                 break;
2954             }
2955
2956
2957             case VLC_CODEC_ADPCM_MS:
2958             case VLC_CODEC_ADPCM_IMA_WAV:
2959             case VLC_CODEC_QCELP:
2960                 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2961                 break;
2962
2963             default:
2964                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2965                 break;
2966         }
2967     }
2968
2969 #undef p_decconfig
2970
2971     if( pp_es )
2972         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2973
2974     return VLC_SUCCESS;
2975 }
2976
2977 /* given a time it return sample/chunk
2978  * it also update elst field of the track
2979  */
2980 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2981                                    int64_t i_start, uint32_t *pi_chunk,
2982                                    uint32_t *pi_sample )
2983 {
2984     demux_sys_t *p_sys = p_demux->p_sys;
2985     MP4_Box_t   *p_box_stss;
2986     uint64_t     i_dts;
2987     unsigned int i_sample;
2988     unsigned int i_chunk;
2989     int          i_index;
2990
2991     /* FIXME see if it's needed to check p_track->i_chunk_count */
2992     if( p_track->i_chunk_count == 0 )
2993         return( VLC_EGENERIC );
2994
2995     /* handle elst (find the correct one) */
2996     MP4_TrackSetELST( p_demux, p_track, i_start );
2997     if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
2998     {
2999         MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3000         int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
3001
3002         /* now calculate i_start for this elst */
3003         /* offset */
3004         i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
3005         if( i_start < 0 )
3006         {
3007             *pi_chunk = 0;
3008             *pi_sample= 0;
3009
3010             return VLC_SUCCESS;
3011         }
3012         /* to track time scale */
3013         i_start  = i_start * p_track->i_timescale / CLOCK_FREQ;
3014         /* add elst offset */
3015         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
3016              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
3017             elst->i_media_time[p_track->i_elst] > 0 )
3018         {
3019             i_start += elst->i_media_time[p_track->i_elst];
3020         }
3021
3022         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
3023                  "ms (track)", p_track->i_elst,
3024                  i_mvt * 1000 / p_sys->i_timescale,
3025                  i_start * 1000 / p_track->i_timescale );
3026     }
3027     else
3028     {
3029         /* convert absolute time to in timescale unit */
3030         i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
3031     }
3032
3033     /* we start from sample 0/chunk 0, hope it won't take too much time */
3034     /* *** find good chunk *** */
3035     for( i_chunk = 0; ; i_chunk++ )
3036     {
3037         if( i_chunk + 1 >= p_track->i_chunk_count )
3038         {
3039             /* at the end and can't check if i_start in this chunk,
3040                it will be check while searching i_sample */
3041             i_chunk = p_track->i_chunk_count - 1;
3042             break;
3043         }
3044
3045         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
3046             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
3047         {
3048             break;
3049         }
3050     }
3051
3052     /* *** find sample in the chunk *** */
3053     i_sample = p_track->chunk[i_chunk].i_sample_first;
3054     i_dts    = p_track->chunk[i_chunk].i_first_dts;
3055     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
3056     {
3057         if( i_dts +
3058             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3059             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
3060         {
3061             i_dts    +=
3062                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3063                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3064
3065             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
3066             i_index++;
3067         }
3068         else
3069         {
3070             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
3071             {
3072                 break;
3073             }
3074             i_sample += ( i_start - i_dts ) /
3075                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3076             break;
3077         }
3078     }
3079
3080     if( i_sample >= p_track->i_sample_count )
3081     {
3082         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
3083                   "(seeking too far) chunk=%d sample=%d",
3084                   p_track->i_track_ID, i_chunk, i_sample );
3085         return( VLC_EGENERIC );
3086     }
3087
3088
3089     /* *** Try to find nearest sync points *** */
3090     if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
3091     {
3092         MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
3093         msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
3094                  p_track->i_track_ID );
3095         for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
3096         {
3097             if( i_index >= p_stss->i_entry_count - 1 ||
3098                 i_sample < p_stss->i_sample_number[i_index+1] )
3099             {
3100                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
3101                 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
3102                          i_sample, i_sync_sample );
3103
3104                 if( i_sync_sample <= i_sample )
3105                 {
3106                     while( i_chunk > 0 &&
3107                            i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
3108                         i_chunk--;
3109                 }
3110                 else
3111                 {
3112                     while( i_chunk < p_track->i_chunk_count - 1 &&
3113                            i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
3114                                             p_track->chunk[i_chunk].i_sample_count )
3115                         i_chunk++;
3116                 }
3117                 i_sample = i_sync_sample;
3118                 break;
3119             }
3120         }
3121     }
3122     else
3123     {
3124         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
3125                  "Sample Box (stss)", p_track->i_track_ID );
3126     }
3127
3128     *pi_chunk  = i_chunk;
3129     *pi_sample = i_sample;
3130
3131     return VLC_SUCCESS;
3132 }
3133
3134 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
3135                                  unsigned int i_chunk, unsigned int i_sample )
3136 {
3137     bool b_reselect = false;
3138
3139     /* now see if actual es is ok */
3140     if( p_track->i_chunk >= p_track->i_chunk_count ||
3141         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
3142             p_track->chunk[i_chunk].i_sample_description_index )
3143     {
3144         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
3145                   p_track->i_track_ID );
3146
3147         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
3148                         p_track->p_es, &b_reselect );
3149
3150         es_out_Del( p_demux->out, p_track->p_es );
3151
3152         p_track->p_es = NULL;
3153
3154         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
3155         {
3156             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3157                      p_track->i_track_ID );
3158
3159             p_track->b_ok       = false;
3160             p_track->b_selected = false;
3161             return VLC_EGENERIC;
3162         }
3163     }
3164
3165     /* select again the new decoder */
3166     if( b_reselect )
3167     {
3168         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
3169     }
3170
3171     p_track->i_chunk    = i_chunk;
3172     p_track->i_sample   = i_sample;
3173
3174     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3175 }
3176
3177 /****************************************************************************
3178  * MP4_TrackCreate:
3179  ****************************************************************************
3180  * Parse track information and create all needed data to run a track
3181  * If it succeed b_ok is set to 1 else to 0
3182  ****************************************************************************/
3183 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
3184                              MP4_Box_t *p_box_trak,
3185                              bool b_force_enable )
3186 {
3187     demux_sys_t *p_sys = p_demux->p_sys;
3188
3189     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
3190     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
3191     MP4_Box_t *p_elst;
3192
3193     MP4_Box_t *p_mdhd;
3194     MP4_Box_t *p_udta;
3195     MP4_Box_t *p_hdlr;
3196
3197     MP4_Box_t *p_vmhd;
3198     MP4_Box_t *p_smhd;
3199
3200     char language[4] = { '\0' };
3201
3202     /* hint track unsupported */
3203
3204     /* set default value (-> track unusable) */
3205     p_track->b_ok       = false;
3206     p_track->b_enable   = false;
3207     p_track->b_selected = false;
3208     p_track->b_chapter  = false;
3209     p_track->b_mac_encoding = false;
3210
3211     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
3212
3213     if( !p_tkhd )
3214     {
3215         return;
3216     }
3217
3218     /* do we launch this track by default ? */
3219     p_track->b_enable =
3220         ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
3221     if( !p_track->b_enable )
3222         p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
3223
3224     p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
3225
3226     p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
3227     p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
3228     p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
3229
3230     if( p_tref )
3231     {
3232 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
3233     }
3234
3235     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
3236     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
3237
3238     if( ( !p_mdhd )||( !p_hdlr ) )
3239     {
3240         return;
3241     }
3242
3243     p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
3244     if( p_track->i_timescale == 0 )
3245         return;
3246
3247     memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
3248     p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
3249
3250     switch( p_hdlr->data.p_hdlr->i_handler_type )
3251     {
3252         case( ATOM_soun ):
3253             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
3254             {
3255                 return;
3256             }
3257             p_track->fmt.i_cat = AUDIO_ES;
3258             break;
3259
3260         case( ATOM_vide ):
3261             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
3262             {
3263                 return;
3264             }
3265             p_track->fmt.i_cat = VIDEO_ES;
3266             break;
3267
3268         case( ATOM_tx3g ):
3269         case( ATOM_text ):
3270         case( ATOM_subp ):
3271         case( ATOM_sbtl ):
3272             p_track->fmt.i_codec = VLC_CODEC_TX3G;
3273             p_track->fmt.i_cat = SPU_ES;
3274             break;
3275
3276         /* closed captions */
3277         case( ATOM_clcp ):
3278             p_track->fmt.i_cat = SPU_ES;
3279             break;
3280
3281         default:
3282             return;
3283     }
3284
3285     p_track->i_elst = 0;
3286     p_track->i_elst_time = 0;
3287     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
3288     {
3289         MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
3290         unsigned int i;
3291
3292         msg_Warn( p_demux, "elst box found" );
3293         for( i = 0; i < elst->i_entry_count; i++ )
3294         {
3295             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
3296                      "ms) rate=%d.%d", i,
3297                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
3298                      elst->i_media_time[i] >= 0 ?
3299                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
3300                      INT64_C(-1),
3301                      elst->i_media_rate_integer[i],
3302                      elst->i_media_rate_fraction[i] );
3303         }
3304     }
3305
3306
3307 /*  TODO
3308     add support for:
3309     p_dinf = MP4_BoxGet( p_minf, "dinf" );
3310 */
3311     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
3312         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
3313     {
3314         return;
3315     }
3316
3317     /* Set language */
3318     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
3319     {
3320         p_track->fmt.psz_language = strdup( language );
3321     }
3322
3323     p_udta = MP4_BoxGet( p_box_trak, "udta" );
3324     if( p_udta )
3325     {
3326         MP4_Box_t *p_box_iter;
3327         for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
3328                  p_box_iter = p_box_iter->p_next )
3329         {
3330             switch( p_box_iter->i_type )
3331             {
3332                 case ATOM_0xa9nam:
3333                     p_track->fmt.psz_description =
3334                         strdup( p_box_iter->data.p_0xa9xxx->psz_text );
3335                     break;
3336                 case ATOM_name:
3337                     p_track->fmt.psz_description =
3338                         strdup( p_box_iter->data.p_name->psz_text );
3339                     break;
3340             }
3341         }
3342     }
3343
3344     /* Create chunk index table and sample index table */
3345     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
3346         TrackCreateSamplesIndex( p_demux, p_track ) )
3347     {
3348         msg_Err( p_demux, "cannot create chunks index" );
3349         return; /* cannot create chunks index */
3350     }
3351
3352     p_track->i_chunk  = 0;
3353     p_track->i_sample = 0;
3354
3355     /* Mark chapter only track */
3356     if( p_sys->p_tref_chap )
3357     {
3358         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
3359         unsigned int i;
3360
3361         for( i = 0; i < p_chap->i_entry_count; i++ )
3362         {
3363             if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
3364                 p_track->fmt.i_cat == UNKNOWN_ES )
3365             {
3366                 p_track->b_chapter = true;
3367                 p_track->b_enable = false;
3368                 break;
3369             }
3370         }
3371     }
3372
3373     /* now create es */
3374     if( b_force_enable &&
3375         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
3376     {
3377         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
3378                   p_track->i_track_ID );
3379         p_track->b_enable = true;
3380         p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
3381     }
3382
3383     p_track->p_es = NULL;
3384     if( TrackCreateES( p_demux,
3385                        p_track, p_track->i_chunk,
3386                        p_track->b_chapter ? NULL : &p_track->p_es ) )
3387     {
3388         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3389                  p_track->i_track_ID );
3390         return;
3391     }
3392     p_track->b_ok = true;
3393 #if 0
3394     {
3395         int i;
3396         for( i = 0; i < p_track->i_chunk_count; i++ )
3397         {
3398             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
3399                      i, p_track->chunk[i].i_sample_count,
3400                      p_track->chunk[i].i_first_dts );
3401
3402         }
3403     }
3404 #endif
3405 }
3406
3407 static void FreeAndResetChunk( mp4_chunk_t *ck )
3408 {
3409     free( ck->p_sample_count_dts );
3410     free( ck->p_sample_delta_dts );
3411     free( ck->p_sample_count_pts );
3412     free( ck->p_sample_offset_pts );
3413     free( ck->p_sample_size );
3414     for( uint32_t i = 0; i < ck->i_sample_count; i++ )
3415         free( ck->p_sample_data[i] );
3416     free( ck->p_sample_data );
3417     memset( ck, 0, sizeof( mp4_chunk_t ) );
3418 }
3419
3420 /****************************************************************************
3421  * MP4_TrackDestroy:
3422  ****************************************************************************
3423  * Destroy a track created by MP4_TrackCreate.
3424  ****************************************************************************/
3425 static void MP4_TrackDestroy( mp4_track_t *p_track )
3426 {
3427     unsigned int i_chunk;
3428
3429     p_track->b_ok = false;
3430     p_track->b_enable   = false;
3431     p_track->b_selected = false;
3432
3433     es_format_Clean( &p_track->fmt );
3434
3435     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
3436     {
3437         if( p_track->chunk )
3438         {
3439            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
3440            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
3441
3442            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
3443            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3444         }
3445     }
3446     FREENULL( p_track->chunk );
3447     if( p_track->cchunk ) {
3448         FreeAndResetChunk( p_track->cchunk );
3449         FREENULL( p_track->cchunk );
3450     }
3451
3452     if( !p_track->i_sample_size )
3453     {
3454         FREENULL( p_track->p_sample_size );
3455     }
3456 }
3457
3458 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3459                             mtime_t i_start )
3460 {
3461     if( !p_track->b_ok || p_track->b_chapter )
3462     {
3463         return VLC_EGENERIC;
3464     }
3465
3466     if( p_track->b_selected )
3467     {
3468         msg_Warn( p_demux, "track[Id 0x%x] already selected",
3469                   p_track->i_track_ID );
3470         return VLC_SUCCESS;
3471     }
3472
3473     return MP4_TrackSeek( p_demux, p_track, i_start );
3474 }
3475
3476 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3477 {
3478     if( !p_track->b_ok || p_track->b_chapter )
3479     {
3480         return;
3481     }
3482
3483     if( !p_track->b_selected )
3484     {
3485         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3486                   p_track->i_track_ID );
3487         return;
3488     }
3489     if( p_track->p_es )
3490     {
3491         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3492                         p_track->p_es, false );
3493     }
3494
3495     p_track->b_selected = false;
3496 }
3497
3498 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3499                           mtime_t i_start )
3500 {
3501     uint32_t i_chunk;
3502     uint32_t i_sample;
3503
3504     if( !p_track->b_ok || p_track->b_chapter )
3505         return VLC_EGENERIC;
3506
3507     p_track->b_selected = false;
3508
3509     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3510                                 &i_chunk, &i_sample ) )
3511     {
3512         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3513                   p_track->i_track_ID );
3514         return VLC_EGENERIC;
3515     }
3516
3517     p_track->b_selected = true;
3518     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3519         p_track->b_selected = true;
3520
3521     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3522 }
3523
3524
3525 /*
3526  * 3 types: for audio
3527  *
3528  */
3529 #define QT_V0_MAX_SAMPLES 1024
3530 static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3531 {
3532     uint32_t i_size = 0;
3533     *pi_nb_samples = 0;
3534
3535     if ( p_track->i_sample == p_track->i_sample_count )
3536         return 0;
3537
3538     if ( p_track->fmt.i_cat != AUDIO_ES )
3539     {
3540         *pi_nb_samples = 1;
3541
3542         if( p_track->i_sample_size == 0 ) /* all sizes are different */
3543             return p_track->p_sample_size[p_track->i_sample];
3544         else
3545             return p_track->i_sample_size;
3546     }
3547     else
3548     {
3549         const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
3550         const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3551         uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample + 1;
3552
3553         /* Group audio packets so we don't call demux for single sample unit */
3554         if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
3555             p_soun->i_constLPCMframesperaudiopacket &&
3556             p_soun->i_constbytesperaudiopacket )
3557         {
3558             /* uncompressed case */
3559             uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
3560             if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
3561                 i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
3562             *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
3563             return i_packets * p_soun->i_constbytesperaudiopacket;
3564         }
3565
3566         /* all samples have a different size */
3567         if( p_track->i_sample_size == 0 )
3568         {
3569             *pi_nb_samples = 1;
3570             return p_track->p_sample_size[p_track->i_sample];
3571         }
3572
3573         if( p_soun->i_qt_version == 1 )
3574         {
3575             if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
3576             {
3577                 /* in this case we are dealing with compressed data
3578                    -2 in V1: additional fields are meaningless (VBR and such) */
3579                 *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
3580                 if( p_track->fmt.audio.i_blockalign > 1 )
3581                     *pi_nb_samples = p_soun->i_sample_per_packet;
3582                 i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3583                 return i_size;
3584             }
3585             else /* uncompressed case */
3586             {
3587                 uint32_t i_packets;
3588                 if( p_track->fmt.audio.i_blockalign > 1 )
3589                     i_packets = 1;
3590                 else
3591                     i_packets = i_max_samples / p_soun->i_sample_per_packet;
3592
3593                 if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
3594                     i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
3595
3596                 *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
3597                 i_size = i_packets * p_soun->i_bytes_per_frame;
3598                 return i_size;
3599             }
3600         }
3601
3602         /* uncompressed v0 */
3603         *pi_nb_samples = 0;
3604         for( uint32_t i=p_track->i_sample;
3605              i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
3606              i<p_track->i_sample_count;
3607              i++ )
3608         {
3609             (*pi_nb_samples)++;
3610             if ( p_track->i_sample_size == 0 )
3611                 i_size += p_track->p_sample_size[i];
3612             else
3613                 i_size += p_track->i_sample_size;
3614             if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
3615                 break;
3616         }
3617     }
3618
3619     //fprintf( stderr, "size=%d\n", i_size );
3620     return i_size;
3621 }
3622
3623 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3624 {
3625     unsigned int i_sample;
3626     uint64_t i_pos;
3627
3628     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3629
3630     if( p_track->i_sample_size )
3631     {
3632         MP4_Box_data_sample_soun_t *p_soun =
3633             p_track->p_sample->data.p_sample_soun;
3634
3635         if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3636         {
3637             i_pos += ( p_track->i_sample -
3638                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
3639                      p_track->i_sample_size;
3640         }
3641         else
3642         {
3643             /* we read chunk by chunk unless a blockalign is requested */
3644             if( p_track->fmt.audio.i_blockalign > 1 )
3645                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3646                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3647         }
3648     }
3649     else
3650     {
3651         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3652              i_sample < p_track->i_sample; i_sample++ )
3653         {
3654             i_pos += p_track->p_sample_size[i_sample];
3655         }
3656     }
3657
3658     return i_pos;
3659 }
3660
3661 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3662 {
3663     if ( UINT32_MAX - p_track->i_sample < i_samples )
3664     {
3665         p_track->i_sample = UINT32_MAX;
3666         return VLC_EGENERIC;
3667     }
3668
3669     p_track->i_sample += i_samples;
3670
3671     if( p_track->i_sample >= p_track->i_sample_count )
3672         return VLC_EGENERIC;
3673
3674     /* Have we changed chunk ? */
3675     if( p_track->i_sample >=
3676             p_track->chunk[p_track->i_chunk].i_sample_first +
3677             p_track->chunk[p_track->i_chunk].i_sample_count )
3678     {
3679         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3680                                   p_track->i_sample ) )
3681         {
3682             msg_Warn( p_demux, "track[0x%x] will be disabled "
3683                       "(cannot restart decoder)", p_track->i_track_ID );
3684             MP4_TrackUnselect( p_demux, p_track );
3685             return VLC_EGENERIC;
3686         }
3687     }
3688
3689     /* Have we changed elst */
3690     if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3691     {
3692         demux_sys_t *p_sys = p_demux->p_sys;
3693         MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3694         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3695                         p_sys->i_timescale / CLOCK_FREQ;
3696
3697         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3698             i_mvt >= p_track->i_elst_time +
3699                      elst->i_segment_duration[p_track->i_elst] )
3700         {
3701             MP4_TrackSetELST( p_demux, p_track,
3702                               MP4_TrackGetDTS( p_demux, p_track ) );
3703         }
3704     }
3705
3706     return VLC_SUCCESS;
3707 }
3708
3709 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3710                               int64_t i_time )
3711 {
3712     demux_sys_t *p_sys = p_demux->p_sys;
3713     int         i_elst_last = tk->i_elst;
3714
3715     /* handle elst (find the correct one) */
3716     tk->i_elst      = 0;
3717     tk->i_elst_time = 0;
3718     if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3719     {
3720         MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3721         int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3722
3723         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3724         {
3725             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3726
3727             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3728             {
3729                 break;
3730             }
3731             tk->i_elst_time += i_dur;
3732         }
3733
3734         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3735         {
3736             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3737             tk->i_elst = elst->i_entry_count - 1;
3738             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3739         }
3740
3741         if( elst->i_media_time[tk->i_elst] < 0 )
3742         {
3743             /* track offset */
3744             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3745         }
3746     }
3747     if( i_elst_last != tk->i_elst )
3748     {
3749         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3750     }
3751 }
3752
3753 /******************************************************************************
3754  *     Here are the functions used for fragmented MP4
3755  *****************************************************************************/
3756
3757 /**
3758  * It computes the sample rate for a video track using current video chunk
3759  */
3760 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3761                                   const mp4_track_t *p_track )
3762 {
3763     if( p_track->cchunk->i_last_dts == 0 )
3764         return;
3765
3766     *pi_num = 0;
3767     *pi_den = 0;
3768
3769     /* */
3770     const mp4_chunk_t *p_chunk = p_track->cchunk;
3771
3772     uint32_t i_sample = p_chunk->i_sample_count;
3773     uint64_t i_first_dts = p_chunk->i_first_dts;
3774     uint64_t i_last_dts =  p_chunk->i_last_dts;
3775
3776     if( i_sample > 1 && i_first_dts < i_last_dts )
3777         vlc_ureduce( pi_num, pi_den,
3778                      ( i_sample - 1) *  p_track->i_timescale,
3779                      i_last_dts - i_first_dts,
3780                      UINT16_MAX);
3781 }
3782
3783 /**
3784  * Build raw avcC box (without the 8 bytes header)
3785  * \return The size of the box.
3786  */
3787 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3788                                                        const unsigned cpd_len )
3789 {
3790     uint8_t *avcC;
3791     unsigned sps_len = 0, pps_len = 0;
3792     const uint32_t mark = 0x00000001;
3793
3794     assert( CodecPrivateData[0] == 0 );
3795     assert( CodecPrivateData[1] == 0 );
3796     assert( CodecPrivateData[2] == 0 );
3797     assert( CodecPrivateData[3] == 1 );
3798
3799     uint32_t length = cpd_len + 3;
3800     avcC = calloc( length, 1 );
3801     if( unlikely( avcC == NULL ) )
3802         return 0;
3803
3804     uint8_t *sps = avcC + 8;
3805
3806     uint32_t candidate = ~mark;
3807     CodecPrivateData += 4;
3808     for( unsigned i = 0; i < cpd_len - 4; i++ )
3809     {
3810         sps[i] = CodecPrivateData[i];
3811         candidate = (candidate << 8) | CodecPrivateData[i];
3812         if( candidate == mark )
3813         {
3814             sps_len = i - 3;
3815             break;
3816         }
3817     }
3818     if( sps_len == 0 )
3819     {
3820         free( avcC );
3821         return 0;
3822     }
3823     uint8_t *pps = sps + sps_len + 3;
3824     pps_len = cpd_len - sps_len - 4 * 2;
3825     memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3826
3827     /* XXX */
3828     uint8_t AVCProfileIndication = 0x64;
3829     uint8_t profile_compatibility = 0x40;
3830     uint8_t AVCLevelIndication = 0x1f;
3831     uint8_t lengthSizeMinusOne = 0x03;
3832
3833     avcC[0] = 1;
3834     avcC[1] = AVCProfileIndication;
3835     avcC[2] = profile_compatibility;
3836     avcC[3] = AVCLevelIndication;
3837     avcC[4] = 0xfc + lengthSizeMinusOne;
3838     avcC[5] = 0xe0 + 1;
3839     avcC[6] = (sps_len & 0xff00)>>8;
3840     avcC[7] = sps_len & 0xff;
3841
3842     avcC[8+sps_len] = 1;
3843     avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3844     avcC[10+sps_len] = pps_len & 0xff;
3845
3846     *p_extra = avcC;
3847     return length;
3848 }
3849
3850 /**
3851  * Build a mp4_track_t from a StraBox
3852  */
3853
3854 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3855 {
3856     fmt->i_extra = p_data->cpd_len;
3857     fmt->p_extra = malloc( p_data->cpd_len );
3858     if( unlikely( !fmt->p_extra ) )
3859         return VLC_ENOMEM;
3860     memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3861     return VLC_SUCCESS;
3862   }
3863
3864 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3865 {
3866     demux_sys_t *p_sys = p_demux->p_sys;
3867     int ret;
3868     MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3869     if( !p_data )
3870         return VLC_EGENERIC;
3871
3872     p_track->b_ok       = true;
3873     p_track->b_selected = false;
3874     p_track->i_sample_count = UINT32_MAX;
3875
3876     p_track->i_timescale = p_sys->i_timescale;
3877     p_track->i_width = p_data->MaxWidth;
3878     p_track->i_height = p_data->MaxHeight;
3879     p_track->i_track_ID = p_data->i_track_ID;
3880
3881     es_format_t *fmt = &p_track->fmt;
3882     if( fmt == NULL )
3883         return VLC_EGENERIC;
3884
3885     es_format_Init( fmt, p_data->i_es_cat, 0 );
3886
3887     /* Set language FIXME */
3888     fmt->psz_language = strdup( "en" );
3889
3890     fmt->i_original_fourcc = p_data->FourCC;
3891     fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3892
3893     uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3894     /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3895      * for MS weird use of FourCC*/
3896     switch( fmt->i_cat )
3897     {
3898         case VIDEO_ES:
3899             if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3900                 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3901                 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3902             {
3903                 fmt->i_extra = build_raw_avcC( p_extra,
3904                         p_data->CodecPrivateData, p_data->cpd_len );
3905             }
3906             else
3907             {
3908                 ret = MP4_SetCodecExtraData( fmt, p_data );
3909                 if( ret != VLC_SUCCESS )
3910                     return ret;
3911             }
3912
3913             fmt->video.i_width = p_data->MaxWidth;
3914             fmt->video.i_height = p_data->MaxHeight;
3915             fmt->video.i_bits_per_pixel = 0x18;
3916             fmt->video.i_visible_width = p_data->MaxWidth;
3917             fmt->video.i_visible_height = p_data->MaxHeight;
3918
3919             /* Frame rate */
3920             ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3921                                   &fmt->video.i_frame_rate_base, p_track );
3922
3923             if( fmt->video.i_frame_rate_base != 0 )
3924             {
3925                 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3926                                         (float)fmt->video.i_frame_rate_base;
3927             }
3928             else
3929                 p_demux->p_sys->f_fps = 24;
3930
3931             break;
3932
3933         case AUDIO_ES:
3934             fmt->audio.i_channels = p_data->Channels;
3935             fmt->audio.i_rate = p_data->SamplingRate;
3936             fmt->audio.i_bitspersample = p_data->BitsPerSample;
3937             fmt->audio.i_blockalign = p_data->nBlockAlign;
3938
3939             fmt->i_bitrate = p_data->Bitrate;
3940
3941             ret = MP4_SetCodecExtraData( fmt, p_data );
3942             if( ret != VLC_SUCCESS )
3943                 return ret;
3944
3945             break;
3946
3947         default:
3948             break;
3949     }
3950
3951     return VLC_SUCCESS;
3952 }
3953
3954 /**
3955  * Return the track identified by tid
3956  */
3957 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3958 {
3959     demux_sys_t *p_sys = p_demux->p_sys;
3960
3961     mp4_track_t *ret = NULL;
3962     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3963     {
3964         ret = &p_sys->track[i];
3965         if( ret->i_track_ID == tid )
3966             return ret;
3967     }
3968     msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3969     return NULL;
3970 }
3971
3972 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3973 {
3974     msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3975     mp4_chunk_t *ck = tk->cchunk;
3976     while( ck->i_sample < ck->i_sample_count )
3977     {
3978         block_t *p_block;
3979         int64_t i_delta;
3980
3981         if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3982             return;
3983
3984         uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3985         assert( sample_size > 0 );
3986         p_block = block_Alloc( sample_size );
3987         if( unlikely( !p_block ) )
3988             return;
3989
3990         uint8_t *src = ck->p_sample_data[ck->i_sample];
3991         memcpy( p_block->p_buffer, src, sample_size );
3992         ck->i_sample++;
3993
3994         /* dts */
3995         p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3996         /* pts */
3997         i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3998         if( i_delta != -1 )
3999             p_block->i_pts = p_block->i_dts + i_delta;
4000         else if( tk->fmt.i_cat != VIDEO_ES )
4001             p_block->i_pts = p_block->i_dts;
4002         else
4003             p_block->i_pts = VLC_TS_INVALID;
4004
4005         MP4_Block_Send( p_demux, tk, p_block );
4006
4007         tk->i_sample++;
4008     }
4009 }
4010
4011 /**
4012  * Re-init decoder.
4013  * \Note If we call that function too soon,
4014  * before the track has been selected by MP4_TrackSelect
4015  * (during the first execution of Demux), then the track gets disabled
4016  */
4017 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
4018 {
4019     demux_sys_t *p_sys = p_demux->p_sys;
4020
4021     uint32_t i_sample = 0;
4022     bool b_smooth = false;
4023     MP4_Box_t *p_stra = NULL, *p_trak = NULL;
4024
4025     if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
4026         b_smooth = true;
4027
4028     if( b_smooth )
4029     {
4030         p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
4031         if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4032             return VLC_EGENERIC;
4033     }
4034     else /* DASH */
4035     {
4036         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
4037         if( !p_trak )
4038             return VLC_EGENERIC;
4039     }
4040
4041     i_sample = p_track->i_sample;
4042     es_out_Del( p_demux->out, p_track->p_es );
4043     es_format_Clean( &p_track->fmt );
4044
4045     if( b_smooth )
4046         MP4_frg_TrackCreate( p_demux, p_track, p_stra );
4047     else /* DASH */
4048         MP4_TrackCreate( p_demux, p_track, p_trak, true );
4049
4050     p_track->i_sample = i_sample;
4051
4052     /* Temporary hack until we support track selection */
4053     p_track->b_selected = true;
4054     p_track->b_ok = true;
4055     p_track->b_enable = true;
4056
4057     p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
4058     p_track->b_codec_need_restart = false;
4059
4060     return VLC_SUCCESS;
4061 }
4062
4063 /**
4064  * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
4065  * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
4066  * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
4067  * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
4068  */
4069 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
4070 {
4071     MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
4072     MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
4073     if( p_moof == NULL)
4074     {
4075         msg_Warn( p_demux, "no moof box found!" );
4076         return VLC_EGENERIC;
4077     }
4078
4079     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4080     if( p_traf == NULL)
4081     {
4082         msg_Warn( p_demux, "no traf box found!" );
4083         return VLC_EGENERIC;
4084     }
4085
4086     MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4087     if( p_tfhd == NULL)
4088     {
4089         msg_Warn( p_demux, "no tfhd box found!" );
4090         return VLC_EGENERIC;
4091     }
4092
4093     uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
4094     *i_tk_id = i_track_ID;
4095     assert( i_track_ID > 0 );
4096     msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
4097
4098     mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
4099     if( !p_track )
4100         return VLC_EGENERIC;
4101
4102     mp4_chunk_t *ret = p_track->cchunk;
4103
4104     if( BOXDATA(p_tfhd)->b_empty )
4105         msg_Warn( p_demux, "No samples in this chunk!" );
4106
4107     /* Usually we read 100 ms of each track. However, suppose we have two tracks,
4108      * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
4109      * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
4110      * and so on. Finally, suppose that we get the chunks the other way around,
4111      * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
4112      * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
4113      * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
4114      * flush it, i.e. send to the decoder the samples not yet sent.
4115      * Note that all the samples to be flushed should worth less than 100 ms,
4116      * (though I did not do the formal proof) and thus this flushing mechanism
4117      * should not cause A/V sync issues, or delays or whatever.
4118      */
4119     if( ret->i_sample < ret->i_sample_count )
4120         FlushChunk( p_demux, p_track );
4121
4122     if( ret->i_sample_count )
4123         FreeAndResetChunk( ret );
4124
4125     uint32_t default_duration = 0;
4126     if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4127         default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
4128
4129     uint32_t default_size = 0;
4130     if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4131         default_size = BOXDATA(p_tfhd)->i_default_sample_size;
4132
4133     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
4134     if( p_trun == NULL)
4135     {
4136         msg_Warn( p_demux, "no trun box found!" );
4137         return VLC_EGENERIC;
4138     }
4139     MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
4140
4141     ret->i_sample_count = p_trun_data->i_sample_count;
4142     assert( ret->i_sample_count > 0 );
4143     ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
4144     ret->i_sample_first = p_track->i_sample_first;
4145     p_track->i_sample_first += ret->i_sample_count;
4146
4147     ret->i_first_dts = p_track->i_first_dts;
4148
4149     /* XXX I already saw DASH content with no default_duration and no
4150      * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
4151      * This chunk of code might be buggy with segments having
4152      * more than one subsegment. */
4153     if( !default_duration )
4154     {
4155         MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
4156         if ( p_trex )
4157             default_duration = BOXDATA(p_trex)->i_default_sample_duration;
4158         else if( p_sidx )
4159         {
4160             MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
4161             assert( p_sidx_data->i_reference_count == 1 );
4162
4163             if( p_sidx_data->i_timescale == 0 )
4164                 return VLC_EGENERIC;
4165
4166             unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
4167                                         p_sidx_data->i_timescale;
4168             default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
4169
4170         }
4171     }
4172
4173     msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
4174
4175     ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4176     ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4177
4178     if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
4179         return VLC_ENOMEM;
4180
4181     ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4182     if( !ret->p_sample_count_pts )
4183         return VLC_ENOMEM;
4184
4185     if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4186     {
4187         ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
4188         if( !ret->p_sample_offset_pts )
4189             return VLC_ENOMEM;
4190     }
4191
4192     ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4193     if( !ret->p_sample_size )
4194         return VLC_ENOMEM;
4195
4196     ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
4197     if( !ret->p_sample_data )
4198         return VLC_ENOMEM;
4199
4200     uint32_t dur = 0, i_mdatlen = 0, len;
4201     uint32_t chunk_duration = 0, chunk_size = 0;
4202
4203     /* Skip header of mdat */
4204     uint8_t mdat[8];
4205     int i_read = stream_Read( p_demux->s, &mdat, 8 );
4206     i_mdatlen = GetDWBE( mdat );
4207     if ( i_read < 8 || i_mdatlen < 8 ||
4208          VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4209         return VLC_EGENERIC;
4210
4211     for( uint32_t i = 0; i < ret->i_sample_count; i++)
4212     {
4213         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
4214             dur = p_trun_data->p_samples[i].i_duration;
4215         else
4216             dur = default_duration;
4217         ret->p_sample_delta_dts[i] = dur;
4218         chunk_duration += dur;
4219
4220         ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
4221
4222         if( ret->p_sample_offset_pts )
4223         {
4224             if ( p_trun_data->i_version == 0 )
4225                 ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
4226             else
4227                 ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
4228         }
4229
4230         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
4231             len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
4232         else
4233             len = ret->p_sample_size[i] = default_size;
4234
4235         if ( chunk_size + len > ( i_mdatlen - 8 ) )
4236             return VLC_EGENERIC;
4237
4238         ret->p_sample_data[i] = malloc( len );
4239         if( ret->p_sample_data[i] == NULL )
4240             return VLC_ENOMEM;
4241         uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
4242         if( i_read < len )
4243             return VLC_EGENERIC;
4244         chunk_size += len;
4245     }
4246     ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
4247     p_track->i_first_dts = chunk_duration + ret->i_first_dts;
4248
4249     if( p_track->b_codec_need_restart &&
4250             p_track->fmt.i_cat == VIDEO_ES )
4251         ReInitDecoder( p_demux, p_track );
4252
4253     /* Skip if we didn't reach the end of mdat box */
4254     if ( chunk_size < (i_mdatlen - 8) )
4255         stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
4256
4257     p_track->b_has_non_empty_cchunk = true;
4258     return VLC_SUCCESS;
4259 }
4260
4261
4262 /**
4263  * Get the next chunk of the track identified by i_tk_id.
4264  * \Note We don't want to seek all the time, so if the first chunk given by the
4265  * input method doesn't belong to the right track, we don't throw it away,
4266  * and so, in general, this function fetch more than one chunk.
4267  * Not to mention that a new init fragment might be put everywhere
4268  * between two chunks by the input method.
4269  */
4270 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
4271 {
4272     demux_sys_t *p_sys = p_demux->p_sys;
4273     mp4_track_t *p_track;
4274
4275     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
4276     {
4277         MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4278         if( !p_chunk )
4279             return VLC_EGENERIC;
4280
4281         if( !p_chunk->p_first )
4282             goto MP4_frg_GetChunks_Error;
4283         uint32_t i_type = p_chunk->p_first->i_type;
4284         uint32_t tid = 0;
4285         if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
4286         {
4287             MP4_BoxFree( p_demux->s, p_sys->p_root );
4288             p_sys->p_root = p_chunk;
4289
4290             if( i_type == ATOM_ftyp ) /* DASH */
4291             {
4292                 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
4293                 if( !p_tkhd )
4294                 {
4295                     msg_Warn( p_demux, "No tkhd found!" );
4296                     goto MP4_frg_GetChunks_Error;
4297                 }
4298                 tid = p_tkhd->data.p_tkhd->i_track_ID;
4299             }
4300             else                      /* Smooth Streaming */
4301             {
4302                 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
4303                 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
4304                 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4305                 {
4306                     msg_Warn( p_demux, "No StraBox found!" );
4307                     goto MP4_frg_GetChunks_Error;
4308                 }
4309                 tid = p_stra->data.p_stra->i_track_ID;
4310             }
4311
4312             p_track = MP4_frg_GetTrackByID( p_demux, tid );
4313             if( !p_track )
4314                 goto MP4_frg_GetChunks_Error;
4315             p_track->b_codec_need_restart = true;
4316
4317             return MP4_frg_GetChunks( p_demux, i_tk_id );
4318         }
4319
4320         if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
4321             goto MP4_frg_GetChunks_Error;
4322
4323         MP4_BoxFree( p_demux->s, p_chunk );
4324
4325         if( tid == i_tk_id )
4326             break;
4327         else
4328             continue;
4329
4330 MP4_frg_GetChunks_Error:
4331         MP4_BoxFree( p_demux->s, p_chunk );
4332         return VLC_EGENERIC;
4333     }
4334
4335     return VLC_SUCCESS;
4336 }
4337
4338 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
4339 {
4340     if( !p_track->b_ok || p_track->b_chapter )
4341     {
4342         return VLC_EGENERIC;
4343     }
4344
4345     if( p_track->b_selected )
4346     {
4347         msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
4348         return VLC_SUCCESS;
4349     }
4350
4351     msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
4352     p_track->b_selected = true;
4353     return VLC_SUCCESS;
4354 }
4355
4356 /**
4357  * DemuxFrg: read packet and send them to decoders
4358  * \return 1 on success, 0 on error.
4359  * TODO check for newly selected track
4360  */
4361 int DemuxFrg( demux_t *p_demux )
4362 {
4363     demux_sys_t *p_sys = p_demux->p_sys;
4364     unsigned i_track;
4365     unsigned i_track_selected;
4366
4367     /* check for newly selected/unselected track */
4368     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
4369     {
4370         mp4_track_t *tk = &p_sys->track[i_track];
4371         bool b;
4372
4373         if( !tk->b_ok || tk->b_chapter )
4374             continue;
4375
4376         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
4377         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
4378
4379         if( tk->b_selected && !b )
4380         {
4381             MP4_TrackUnselect( p_demux, tk );
4382         }
4383         else if( !tk->b_selected && b)
4384         {
4385             MP4_frg_TrackSelect( p_demux, tk );
4386         }
4387
4388         if( tk->b_selected )
4389             i_track_selected++;
4390     }
4391
4392     if( i_track_selected <= 0 )
4393     {
4394         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
4395         if( p_sys->i_timescale > 0 )
4396         {
4397             int64_t i_length = CLOCK_FREQ *
4398                                (mtime_t)p_sys->moovfragment.i_duration /
4399                                (mtime_t)p_sys->i_timescale;
4400             if( MP4_GetMoviePTS( p_sys ) >= i_length )
4401                 return 0;
4402             return 1;
4403         }
4404
4405         msg_Warn( p_demux, "no track selected, exiting..." );
4406         return 0;
4407     }
4408
4409     /* first wait for the good time to read a packet */
4410     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4411
4412     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4413
4414     /* we will read 100ms for each stream so ...*/
4415     p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4416
4417     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4418     {
4419         mp4_track_t *tk = &p_sys->track[i_track];
4420
4421         if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4422         {
4423             msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4424             continue;
4425         }
4426
4427         if( !tk->b_has_non_empty_cchunk )
4428         {
4429             if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4430             {
4431                 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4432                 return 0;
4433             }
4434         }
4435
4436         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4437         {
4438             block_t *p_block;
4439             int64_t i_delta;
4440
4441             mp4_chunk_t *ck = tk->cchunk;
4442             if( ck->i_sample >= ck->i_sample_count )
4443             {
4444                 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4445                                     ck->i_sample, ck->i_sample_count );
4446                 return 0;
4447             }
4448
4449             uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4450             p_block = block_Alloc( sample_size );
4451             uint8_t *src = ck->p_sample_data[ck->i_sample];
4452             memcpy( p_block->p_buffer, src, sample_size );
4453
4454             ck->i_sample++;
4455             if( ck->i_sample == ck->i_sample_count )
4456                 tk->b_has_non_empty_cchunk = false;
4457
4458             /* dts */
4459             p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4460             /* pts */
4461             i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4462             if( i_delta != -1 )
4463                 p_block->i_pts = p_block->i_dts + i_delta;
4464             else if( tk->fmt.i_cat != VIDEO_ES )
4465                 p_block->i_pts = p_block->i_dts;
4466             else
4467                 p_block->i_pts = VLC_TS_INVALID;
4468
4469             MP4_Block_Send( p_demux, tk, p_block );
4470
4471             tk->i_sample++;
4472
4473             if( !tk->b_has_non_empty_cchunk )
4474                 break;
4475         }
4476     }
4477     return 1;
4478 }
4479
4480 static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
4481 {
4482     /* Read Next Chunk */
4483     MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4484     if( !p_chunk )
4485     {
4486         msg_Warn( p_demux, "no next chunk" );
4487         return NULL;
4488     }
4489
4490     if( !p_chunk->p_first )
4491     {
4492         msg_Warn( p_demux, "no next chunk child" );
4493         return NULL;
4494     }
4495
4496     return p_chunk;
4497 }
4498
4499 static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
4500 {
4501     while ( p_root )
4502     {
4503         if ( p_root->i_pos == i_pos )
4504         {
4505             assert( i_type == p_root->i_type );
4506             break;
4507         }
4508         p_root = p_root->p_next;
4509     }
4510     return (p_root != NULL);
4511 }
4512
4513 /* Keeps an ordered chain of all fragments */
4514 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
4515 {
4516     demux_sys_t *p_sys = p_demux->p_sys;
4517     mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
4518     if ( !p_moox )
4519         return false;
4520
4521     if( p_moox->i_type == ATOM_moov )
4522     {
4523         if ( !p_sys->moovfragment.p_moox )
4524         {
4525             p_sys->moovfragment.p_moox = p_moox;
4526             MP4_Box_t *p_mvhd;
4527             if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
4528             {
4529                 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
4530                 p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
4531             }
4532
4533             if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
4534             { /* duration might be wrong an be set to whole duration :/ */
4535                p_sys->moovfragment.i_duration = 0;
4536                MP4_Box_t *p_tkhd;
4537                MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
4538                while( p_trak )
4539                {
4540                    if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
4541                    {
4542                        if ( BOXDATA(p_tkhd)->i_duration > p_sys->moovfragment.i_duration )
4543                            p_sys->moovfragment.i_duration = BOXDATA(p_tkhd)->i_duration;
4544                    }
4545                    p_trak = p_trak->p_next;
4546                }
4547             }
4548
4549             msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4550             return true;
4551         }
4552         return false;
4553     }
4554     else // p_moox->i_type == ATOM_moof
4555     {
4556         assert(p_moox->i_type == ATOM_moof);
4557         mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
4558         while ( p_fragment )
4559         {
4560             if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
4561             {
4562                 p_base_fragment = p_fragment;
4563                 p_fragment = p_fragment->p_next;
4564             }
4565             else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
4566             {
4567                 /* already exists */
4568                 return false;
4569             }
4570         }
4571     }
4572
4573     /* Add the moof fragment */
4574     mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
4575     if ( !p_new ) return false;
4576     p_new->p_moox = p_moox;
4577     p_new->i_duration = 0;
4578     p_new->p_next = p_base_fragment->p_next;
4579     p_base_fragment->p_next = p_new;
4580     msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4581
4582     /* we have to probe all fragments :/ */
4583     uint64_t i_traf_base_data_offset = 0;
4584     uint64_t i_traf_min_offset = 0;
4585     uint32_t i_traf = 0;
4586     uint32_t i_traf_total_size = 0;
4587     uint32_t i_trafs_total_size = 0;
4588
4589     MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
4590     while ( p_traf )
4591     {
4592         if ( p_traf->i_type != ATOM_traf )
4593         {
4594            p_traf = p_traf->p_next;
4595            continue;
4596         }
4597         const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4598         const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4599         if ( !p_tfhd || !p_trun )
4600         {
4601            p_traf = p_traf->p_next;
4602            continue;
4603         }
4604
4605         uint32_t i_track_timescale = 0;
4606         uint32_t i_track_defaultsamplesize = 0;
4607         uint32_t i_track_defaultsampleduration = 0;
4608         if ( p_sys->b_smooth )
4609         {
4610             /* stra sets identical timescales */
4611             i_track_timescale = p_sys->i_timescale;
4612             i_track_defaultsamplesize = 1;
4613             i_track_defaultsampleduration = 1;
4614         }
4615         else
4616         {
4617             /* set trex for defaults */
4618              MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4619              if ( p_trex )
4620              {
4621                 i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
4622                 i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4623              }
4624
4625              MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4626              if ( p_trak )
4627              {
4628                 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4629                 if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4630              }
4631         }
4632
4633         if ( !i_track_timescale )
4634         {
4635            p_traf = p_traf->p_next;
4636            continue;
4637         }
4638
4639         if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4640         {
4641             i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
4642         }
4643         else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4644         {
4645             i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
4646         }
4647         else
4648         {
4649             if ( i_traf == 0 )
4650                 i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
4651             else
4652                 i_traf_base_data_offset += i_traf_total_size;
4653         }
4654
4655         i_traf_total_size = 0;
4656
4657         uint64_t i_trun_data_offset = i_traf_base_data_offset;
4658         uint64_t i_traf_duration = 0;
4659         uint32_t i_trun_size = 0;
4660         while ( p_trun && p_tfhd )
4661         {
4662             if ( p_trun->i_type != ATOM_trun )
4663             {
4664                p_trun = p_trun->p_next;
4665                continue;
4666             }
4667             const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4668
4669             /* Get data offset */
4670             if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
4671                 i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
4672             else
4673                 i_trun_data_offset += i_trun_size;
4674
4675             i_trun_size = 0;
4676
4677             /* Sum total time */
4678             if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4679             {
4680                 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4681                     i_traf_duration += p_trundata->p_samples[i].i_duration;
4682             }
4683             else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4684             {
4685                 i_traf_duration += p_trundata->i_sample_count *
4686                         BOXDATA(p_tfhd)->i_default_sample_duration;
4687             }
4688             else
4689             {
4690                 i_traf_duration += p_trundata->i_sample_count *
4691                         i_track_defaultsampleduration;
4692             }
4693
4694             /* Get total traf size */
4695             if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
4696             {
4697                 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4698                     i_trun_size += p_trundata->p_samples[i].i_size;
4699             }
4700             else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4701             {
4702                 i_trun_size += p_trundata->i_sample_count *
4703                         BOXDATA(p_tfhd)->i_default_sample_size;
4704             }
4705             else
4706             {
4707                 i_trun_size += p_trundata->i_sample_count *
4708                         i_track_defaultsamplesize;
4709             }
4710
4711             i_traf_total_size += i_trun_size;
4712
4713             if ( i_traf_min_offset )
4714                 i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
4715             else
4716                 i_traf_min_offset = i_trun_data_offset;
4717
4718             p_trun = p_trun->p_next;
4719         }
4720
4721         i_trafs_total_size += i_traf_total_size;
4722         p_new->i_duration = __MAX( p_new->i_duration, i_traf_duration * p_sys->i_timescale / i_track_timescale );
4723
4724         p_traf = p_traf->p_next;
4725         i_traf++;
4726     }
4727
4728     p_new->i_chunk_range_min_offset = i_traf_min_offset;
4729     p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
4730
4731     msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
4732
4733     /* compute total duration with that new fragment if no overall provided */
4734     MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
4735     if ( !p_mehd )
4736     {
4737         p_sys->i_overall_duration = 0;
4738         if ( p_sys->b_fragments_probed )
4739         {
4740             p_new = &p_sys->moovfragment;
4741             while ( p_new )
4742             {
4743                 p_sys->i_overall_duration += p_new->i_duration;
4744                 p_new = p_new->p_next;
4745             }
4746         }
4747     }
4748     else
4749         p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
4750
4751     msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale);
4752     return true;
4753 }
4754
4755 static int ProbeIndex( demux_t *p_demux )
4756 {
4757     demux_sys_t *p_sys = p_demux->p_sys;
4758     uint64_t i_backup_pos, i_stream_size;
4759     uint8_t mfro[MP4_MFRO_BOXSIZE];
4760     assert( p_sys->b_seekable );
4761
4762     if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4763         return VLC_SUCCESS;
4764
4765     i_stream_size = stream_Size( p_demux->s );
4766     if ( ( i_stream_size >> 62 ) ||
4767          ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
4768          ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
4769          ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4770        )
4771     {
4772         msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4773         return VLC_EGENERIC;
4774     }
4775
4776     if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4777          VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4778          GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4779     {
4780         uint32_t i_offset = GetDWBE( &mfro[12] );
4781         msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4782         if ( i_stream_size > i_offset &&
4783              stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4784         {
4785             msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4786             MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
4787         }
4788     }
4789
4790     return stream_Seek( p_demux->s, i_backup_pos );
4791 }
4792
4793 static int ProbeFragments( demux_t *p_demux, bool b_force )
4794 {
4795     demux_sys_t *p_sys = p_demux->p_sys;
4796     uint64_t i_current_pos;
4797
4798     if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4799         msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
4800
4801     assert( p_sys->p_root );
4802
4803     if ( p_sys->b_fastseekable || b_force )
4804     {
4805         MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
4806         p_sys->b_fragments_probed = true;
4807     }
4808     else
4809     {
4810         /* We stop at first moof, which validates our fragmentation condition
4811          * and we'll find others while reading. */
4812         MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
4813     }
4814
4815     if ( !p_sys->moovfragment.p_moox )
4816     {
4817         MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
4818         if ( !p_moov )
4819         {
4820             /* moov/mvex before probing should be present anyway */
4821             MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
4822             return VLC_EGENERIC;
4823         }
4824         AddFragment( p_demux, p_moov );
4825     }
4826
4827     MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
4828     while ( p_moof )
4829     {
4830         if ( p_moof->i_type == ATOM_moof )
4831             AddFragment( p_demux, p_moof );
4832         p_moof = p_moof->p_next;
4833     }
4834
4835     MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
4836     if ( p_mdat )
4837     {
4838         stream_Seek( p_demux->s, p_mdat->i_pos );
4839         msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
4840     }
4841
4842     return VLC_SUCCESS;
4843 }
4844
4845 static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
4846 {
4847     mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4848     while ( p_fragment )
4849     {
4850         if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
4851              ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
4852         {
4853             msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
4854                      p_fragment->i_chunk_range_min_offset, i_pos,
4855                      p_fragment->i_chunk_range_max_offset );
4856             return p_fragment;
4857         }
4858         else
4859         {
4860             p_fragment = p_fragment->p_next;
4861         }
4862     }
4863     return NULL;
4864 }
4865
4866 /* Get a matching fragment data start by clock time */
4867 static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
4868 {
4869     mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4870     mtime_t i_base_time = 0;
4871     while ( p_fragment )
4872     {
4873         mtime_t i_length = CLOCK_FREQ * p_fragment->i_duration / p_demux->p_sys->i_timescale;
4874         if ( i_time >= i_base_time &&
4875              i_time <= i_base_time + i_length )
4876         {
4877             return p_fragment;
4878         }
4879         else
4880         {
4881             i_base_time += i_length;
4882             p_fragment = p_fragment->p_next;
4883         }
4884
4885         if ( !p_demux->p_sys->b_fragments_probed )
4886             return NULL; /* We have no way to guess missing fragments time */
4887     }
4888     return NULL;
4889 }
4890
4891 /* Returns fragment scaled time offset */
4892 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment )
4893 {
4894     mtime_t i_base_scaledtime = 0;
4895     mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
4896     while ( p_current != p_fragment )
4897     {
4898         i_base_scaledtime += p_current->i_duration;
4899         p_current = p_current->p_next;
4900     }
4901     return i_base_scaledtime;
4902 }
4903
4904 static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
4905                       const uint32_t i_defaultduration, const uint32_t i_defaultsize,
4906                       const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
4907 {
4908     assert( p_trun->i_sample_count );
4909     msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
4910              i_defaultduration, i_defaultsize, p_track->i_first_dts );
4911
4912     uint32_t dur = 0, len;
4913     uint32_t chunk_size = 0;
4914     mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
4915
4916     mtime_t i_nzpts;
4917
4918     for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
4919     {
4920         i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
4921         i_nzpts = i_nzdts;
4922
4923         if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4924             dur = p_trun->p_samples[i].i_duration;
4925         else
4926             dur = i_defaultduration;
4927
4928         p_track->i_time += dur;
4929
4930         if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4931         {
4932             if ( p_trun->i_version == 0 )
4933                 i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4934             else
4935                 i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4936         }
4937
4938         if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
4939             len = p_trun->p_samples[i].i_size;
4940         else
4941             len = i_defaultsize;
4942
4943         assert( dur ); /* dur, dur ! */
4944         assert( len );
4945
4946         if ( chunk_size + len > *pi_mdatlen )
4947         {
4948             /* update data left in mdat */
4949             *pi_mdatlen -= chunk_size;
4950             return VLC_EGENERIC;
4951         }
4952
4953         block_t *p_block = MP4_Block_Read( p_demux, p_track, __MIN( len, INT32_MAX ) );
4954         uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
4955         if( i_read < len )
4956         {
4957             /* update data left in mdat */
4958             *pi_mdatlen -= chunk_size;
4959             *pi_mdatlen -= i_read;
4960             free( p_block );
4961             return VLC_EGENERIC;
4962         }
4963
4964         if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4965         {
4966             p_demux->p_sys->i_pcr = i_nzdts;
4967             es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
4968         }
4969
4970         if ( p_track->p_es )
4971         {
4972             p_block->i_dts = VLC_TS_0 + i_nzdts;
4973             p_block->i_pts = VLC_TS_0 + i_nzpts;
4974             p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
4975             MP4_Block_Send( p_demux, p_track, p_block );
4976         }
4977         else free( p_block );
4978
4979         chunk_size += len;
4980     }
4981
4982     /* update data left in mdat */
4983     *pi_mdatlen -= chunk_size;
4984     return VLC_SUCCESS;
4985 }
4986
4987 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
4988                                       mp4_track_t **pp_tk, unsigned int *pi_chunk )
4989 {
4990     const demux_sys_t *p_sys = p_demux->p_sys;
4991
4992     mp4_track_t *p_tk_closest = NULL;
4993     uint64_t i_closest = UINT64_MAX;
4994     unsigned int i_chunk_closest;
4995
4996     *pp_tk = NULL;
4997
4998     for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4999     {
5000         for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
5001         {
5002             if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
5003             {
5004                 i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
5005                 p_tk_closest = &p_sys->track[i_track];
5006                 i_chunk_closest = i_chunk;
5007             }
5008
5009             if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
5010             {
5011                 *pp_tk = &p_sys->track[i_track];
5012                 *pi_chunk = i_chunk;
5013                 return VLC_SUCCESS;
5014             }
5015         }
5016     }
5017
5018     if ( i_closest != UINT64_MAX )
5019     {
5020         *pi_pos = i_closest;
5021         *pp_tk = p_tk_closest;
5022         *pi_chunk = i_chunk_closest;
5023         return VLC_ENOOBJ;
5024     }
5025     else return VLC_EGENERIC;
5026 }
5027
5028 static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
5029                            uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
5030                            const uint32_t i_maxbytes, const uint32_t i_maxsamples )
5031 {
5032     MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
5033     if ( !p_stsz )
5034         return VLC_EGENERIC;
5035
5036     if ( BOXDATA(p_stsz)->i_sample_size == 0 )
5037     {
5038         uint32_t i_entry = i_sample;
5039         uint32_t i_totalbytes = 0;
5040         *pi_samplestoread = 1;
5041
5042         if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
5043             return VLC_EGENERIC;
5044
5045         *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
5046         i_totalbytes += *pi_samplessize;
5047
5048         if ( *pi_samplessize > i_maxbytes )
5049             return VLC_EGENERIC;
5050
5051         i_entry++;
5052         while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
5053                *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
5054                i_totalbytes + *pi_samplessize < i_maxbytes &&
5055                *pi_samplestoread < i_maxsamples
5056               )
5057         {
5058             i_totalbytes += *pi_samplessize;
5059             (*pi_samplestoread)++;
5060         }
5061
5062         *pi_samplessize = i_totalbytes;
5063     }
5064     else
5065     {
5066         /* all samples have same size */
5067         *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
5068         *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
5069         *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
5070         *pi_samplessize = *pi_samplessize * *pi_samplestoread;
5071     }
5072
5073     return VLC_SUCCESS;
5074 }
5075
5076 static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
5077 {
5078     mtime_t i_time = 0;
5079     uint32_t i_index = 0;
5080
5081     while( i_sample > 0 )
5082     {
5083         if( i_sample > p_chunk->p_sample_count_dts[i_index] )
5084         {
5085             i_time += p_chunk->p_sample_count_dts[i_index] *
5086                 p_chunk->p_sample_delta_dts[i_index];
5087             i_sample -= p_chunk->p_sample_count_dts[i_index];
5088             i_index++;
5089         }
5090         else
5091         {
5092             i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
5093             break;
5094         }
5095     }
5096
5097     return i_time;
5098 }
5099
5100 static int LeafParseMDATwithMOOV( demux_t *p_demux )
5101 {
5102     demux_sys_t *p_sys = p_demux->p_sys;
5103
5104     assert( p_sys->context.i_current_box_type == ATOM_mdat );
5105     assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
5106
5107     uint64_t i_current_pos;
5108     if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
5109         return VLC_EGENERIC;
5110
5111     if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
5112     {
5113         /* Ready mdat section */
5114         uint8_t mdat[8];
5115         int i_read = stream_Read( p_demux->s, &mdat, 8 );
5116         p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5117         if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5118              VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5119         {
5120             uint64_t i_pos;
5121             if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5122                 msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
5123             return VLC_EGENERIC;
5124         }
5125         i_current_pos += 8;
5126         p_sys->context.i_mdatbytesleft -= 8;
5127     }
5128
5129     while( p_sys->context.i_mdatbytesleft > 0 )
5130     {
5131         mp4_track_t *p_track;
5132         unsigned int i_chunk;
5133
5134         /**/
5135         uint64_t i_pos = i_current_pos;
5136         int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
5137         if ( i_ret == VLC_EGENERIC )
5138         {
5139             msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
5140             goto error;
5141         }
5142         else if( i_ret == VLC_ENOOBJ )
5143         {
5144             assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
5145             int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
5146             i_current_pos += i_read;
5147             p_sys->context.i_mdatbytesleft -= i_read;
5148             if ( i_read == 0 ) goto error;
5149             continue;
5150         }
5151         /**/
5152
5153         mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
5154
5155         uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
5156         uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
5157
5158         assert(i_nb_samples_in_chunk);
5159
5160         uint32_t i_nb_samples = 0;
5161         while ( i_nb_samples < i_nb_samples_in_chunk )
5162         {
5163             uint32_t i_samplessize = 0;
5164             uint32_t i_samplescounttoread = 0;
5165             i_ret = LeafMOOVGetSamplesSize( p_track,
5166                             i_nb_samples_at_chunk_start + i_nb_samples,
5167                             &i_samplescounttoread, &i_samplessize,
5168                             p_sys->context.i_mdatbytesleft,
5169                             /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
5170             if ( i_ret != VLC_SUCCESS )
5171                 goto error;
5172
5173             if( p_sys->context.i_mdatbytesleft &&
5174                 p_sys->context.i_mdatbytesleft  >= i_samplessize )
5175             {
5176                 block_t *p_block;
5177
5178                 /* now read pes */
5179
5180                 if( !(p_block = MP4_Block_Read( p_demux, p_track, i_samplessize )) )
5181                 {
5182                     uint64_t i_pos;
5183                     if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5184                     {
5185                         p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
5186                         msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
5187                     }
5188                     goto error;
5189                 }
5190
5191                 i_nb_samples += i_samplescounttoread;
5192                 i_current_pos += i_samplessize;
5193                 p_sys->context.i_mdatbytesleft -= i_samplessize;
5194
5195                 /* dts */
5196                 mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
5197                 i_time += p_chunk->i_first_dts;
5198                 p_track->i_time = i_time;
5199                 p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
5200
5201                 /* pts */
5202                 int64_t i_delta = MP4_TrackGetPTSDelta( p_demux, p_track );
5203                 if( i_delta != -1 )
5204                     p_block->i_pts = p_block->i_dts + i_delta;
5205                 else if( p_track->fmt.i_cat != VIDEO_ES )
5206                     p_block->i_pts = p_block->i_dts;
5207                 else
5208                     p_block->i_pts = VLC_TS_INVALID;
5209
5210                 MP4_Block_Send( p_demux, p_track, p_block );
5211
5212                 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
5213                 {
5214                     p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
5215                     p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
5216                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
5217                 }
5218
5219             }
5220             else
5221             {
5222                 // sample size > left bytes
5223                 break;
5224             }
5225
5226             p_track->i_sample += i_samplescounttoread;
5227         }
5228
5229         /* flag end of mdat section if needed */
5230         if ( p_sys->context.i_mdatbytesleft == 0 )
5231             p_sys->context.i_current_box_type = 0;
5232
5233         // next chunk
5234         return VLC_SUCCESS;
5235     }
5236
5237 error:
5238     /* Skip if we didn't reach the end of mdat box */
5239     if ( p_sys->context.i_mdatbytesleft  > 0 )
5240     {
5241         msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
5242                  p_sys->context.i_mdatbytesleft );
5243         stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5244     }
5245     p_sys->context.i_current_box_type = 0;
5246
5247     return VLC_SUCCESS;
5248 }
5249
5250 static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
5251 {
5252     demux_sys_t *p_sys = p_demux->p_sys;
5253
5254     for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5255     {
5256         mp4_track_t *p_track = &p_sys->track[i];
5257         if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
5258             continue;
5259         const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5260         uint64_t i_offset = 0;
5261
5262         if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
5263             i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
5264         else
5265             i_offset = i_moofpos;
5266
5267         //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5268           //  i_offset += i_moofpos;
5269
5270         if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
5271             i_offset += p_trun_data->i_data_offset;
5272         else
5273             return p_track;
5274
5275         if ( i_offset == i_pos )
5276             return p_track;
5277     }
5278
5279     return NULL;
5280 }
5281
5282 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
5283 {
5284     demux_sys_t *p_sys = p_demux->p_sys;
5285
5286     /* reset */
5287     for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5288     {
5289         mp4_track_t *p_track = &p_sys->track[i];
5290         p_track->context.p_tfhd = NULL;
5291         p_track->context.p_traf = NULL;
5292         p_track->context.p_trun = NULL;
5293     }
5294
5295     if ( p_moof->i_type == ATOM_moov )
5296         return VLC_SUCCESS;
5297
5298     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
5299     if( !p_traf )
5300     {
5301         msg_Warn( p_demux, "no traf box found!" );
5302         return VLC_EGENERIC;
5303     }
5304
5305     /* map contexts */
5306     while ( p_traf )
5307     {
5308         if ( p_traf->i_type == ATOM_traf )
5309         {
5310             MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
5311             for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
5312             {
5313                 mp4_track_t *p_track = &p_sys->track[i];
5314                 if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
5315                 {
5316                     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
5317                     if ( p_trun )
5318                     {
5319                         p_track->context.p_tfhd = p_tfhd;
5320                         p_track->context.p_traf = p_traf;
5321                         p_track->context.p_trun = p_trun;
5322                     }
5323                     p_tfhd = NULL; /* break loop */
5324                 }
5325             }
5326         }
5327         p_traf = p_traf->p_next;
5328     }
5329
5330     return VLC_SUCCESS;
5331 }
5332
5333 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
5334                                       uint64_t *pi_pos, mtime_t *pi_mooftime )
5335 {
5336     MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
5337     while ( p_tfra )
5338     {
5339         if ( p_tfra->i_type == ATOM_tfra )
5340         {
5341             int64_t i_pos = -1;
5342             const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
5343             mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
5344             if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
5345             {
5346                 for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
5347                 {
5348                     mtime_t i_time;
5349                     uint64_t i_offset;
5350                     if ( p_data->i_version == 1 )
5351                     {
5352                         i_time = *((uint64_t *)(p_data->p_time + i));
5353                         i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
5354                     }
5355                     else
5356                     {
5357                         i_time = p_data->p_time[i];
5358                         i_offset = p_data->p_moof_offset[i];
5359                     }
5360
5361                     if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
5362                     {
5363                         if ( i_pos == -1 ) /* Not in this traf */
5364                             break;
5365
5366                         *pi_pos = (uint64_t) i_pos;
5367                         *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
5368                         if ( p_track->fmt.i_cat == AUDIO_ES )
5369                             *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
5370                         else
5371                             *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
5372                         return VLC_SUCCESS;
5373                     }
5374                     else
5375                         i_pos = i_offset;
5376                 }
5377             }
5378         }
5379         p_tfra = p_tfra->p_next;
5380     }
5381     return VLC_EGENERIC;
5382 }
5383
5384 static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
5385 {
5386     demux_sys_t *p_sys = p_demux->p_sys;
5387     uint64_t i_pos;
5388     assert( p_moof->i_type == ATOM_moof );
5389     assert( p_sys->context.i_current_box_type == ATOM_mdat );
5390
5391     if ( p_sys->context.i_mdatbytesleft == 0 )
5392     {
5393         int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
5394         if ( i_ret != VLC_SUCCESS )
5395             return i_ret;
5396
5397         /* Ready mdat section */
5398         uint8_t mdat[8];
5399         int i_read = stream_Read( p_demux->s, &mdat, 8 );
5400         p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5401         if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5402              VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5403         {
5404             if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5405                 msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
5406             return VLC_EGENERIC;
5407         }
5408         p_sys->context.i_mdatbytesleft -= 8;
5409     }
5410
5411     if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5412         return VLC_EGENERIC;
5413     if ( p_sys->b_smooth )
5414         i_pos -= p_moof->i_pos;
5415     mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
5416     if( p_track )
5417     {
5418         MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
5419         uint32_t i_trun_sample_default_duration = 0;
5420         uint32_t i_trun_sample_default_size = 0;
5421
5422         if ( p_track->context.p_trun )
5423         {
5424             /* Get defaults for this/these RUN */
5425             if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
5426                 i_trun_sample_default_duration = p_tfhd_data->i_default_sample_duration;
5427
5428             if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
5429                 i_trun_sample_default_size = p_tfhd_data->i_default_sample_size;
5430
5431             if( !i_trun_sample_default_duration || !i_trun_sample_default_size )
5432             {
5433                 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
5434                 if ( p_trex )
5435                 {
5436                     while( p_trex && BOXDATA(p_trex)->i_track_ID != p_tfhd_data->i_track_ID )
5437                         p_trex = p_trex->p_next;
5438                     if ( p_trex && !i_trun_sample_default_duration )
5439                         i_trun_sample_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
5440                     if ( p_trex && !i_trun_sample_default_size )
5441                         i_trun_sample_default_size = BOXDATA(p_trex)->i_default_sample_size;
5442                 }
5443             }
5444
5445             const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5446
5447            /* NOW PARSE TRUN WITH MDAT */
5448             int i_ret = LeafParseTRUN( p_demux, p_track,
5449                                    i_trun_sample_default_duration, i_trun_sample_default_size,
5450                                    p_trun_data, & p_sys->context.i_mdatbytesleft );
5451             if ( i_ret != VLC_SUCCESS )
5452                 goto end;
5453
5454             p_track->context.p_trun = p_track->context.p_trun->p_next;
5455         }
5456
5457         if ( p_sys->context.i_mdatbytesleft == 0 )
5458             p_sys->context.i_current_box_type = 0;
5459         return VLC_SUCCESS;
5460     }
5461
5462 end:
5463     /* Skip if we didn't reach the end of mdat box */
5464     if ( p_sys->context.i_mdatbytesleft > 0 )
5465     {
5466         msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
5467         stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5468     }
5469
5470     p_sys->context.i_current_box_type = 0;
5471
5472     return VLC_SUCCESS;
5473 }
5474
5475 static int DemuxAsLeaf( demux_t *p_demux )
5476 {
5477     demux_sys_t *p_sys = p_demux->p_sys;
5478     unsigned i_track_selected = 0;
5479
5480     /* check for newly selected/unselected track */
5481     for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5482     {
5483         mp4_track_t *tk = &p_sys->track[i_track];
5484         bool b;
5485
5486         if( !tk->b_ok || tk->b_chapter )
5487             continue;
5488
5489         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5490         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5491
5492         if( tk->b_selected && !b )
5493             MP4_TrackUnselect( p_demux, tk );
5494         else if( !tk->b_selected && b)
5495             MP4_frg_TrackSelect( p_demux, tk );
5496
5497         if( tk->b_selected )
5498             i_track_selected++;
5499     }
5500
5501     if( i_track_selected <= 0 )
5502     {
5503         msg_Warn( p_demux, "no track selected, exiting..." );
5504         return 0;
5505     }
5506
5507     if ( p_sys->context.i_current_box_type != ATOM_mdat )
5508     {
5509         /* Othewise mdat is skipped. FIXME: mdat reading ! */
5510         const uint8_t *p_peek;
5511         int i_read  = stream_Peek( p_demux->s, &p_peek, 8 );
5512         if ( i_read < 8 )
5513             return 0;
5514
5515         p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5516
5517         if ( p_sys->context.i_current_box_type != ATOM_mdat )
5518         {
5519             if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
5520             {// only if !b_probed ??
5521                 MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
5522                 switch( p_sys->context.i_current_box_type )
5523                 {
5524                 case ATOM_moov:
5525                 case ATOM_moof:
5526                     /* create fragment */
5527                     AddFragment( p_demux, p_vroot->p_first );
5528                     //ft
5529                 default:
5530                     break;
5531                 }
5532
5533                 /* Append to root */
5534                 p_sys->p_root->p_last->p_next = p_vroot->p_first;
5535                 p_sys->p_root->p_last = p_vroot->p_first;
5536                 p_vroot->p_last = NULL;
5537                 p_vroot->p_next = NULL;
5538                 p_vroot->p_first = NULL;
5539                 MP4_BoxFree( p_demux->s, p_vroot );
5540             }
5541             else
5542             {
5543                 /* Skip */
5544                 msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
5545                 stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
5546             }
5547         }
5548         else
5549         {
5550             /* skip mdat header */
5551             p_sys->context.p_fragment = GetFragmentByPos( p_demux,
5552                                        stream_Tell( p_demux->s ) + 8, true );
5553         }
5554
5555     }
5556
5557     if ( p_sys->context.i_current_box_type == ATOM_mdat )
5558     {
5559         assert(p_sys->context.p_fragment);
5560         if ( p_sys->context.p_fragment )
5561         switch( p_sys->context.p_fragment->p_moox->i_type )
5562         {
5563             case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5564                 LeafParseMDATwithMOOV( p_demux );
5565             break;
5566             case ATOM_moof:
5567                 LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
5568             break;
5569         default:
5570              msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
5571              break;
5572         }
5573     }
5574
5575     /* Get current time */
5576     mtime_t i_lowest_dts = VLC_TS_INVALID;
5577     mtime_t i_lowest_time = INT64_MAX;
5578     for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5579     {
5580         const mp4_track_t *p_track = &p_sys->track[i_track];
5581         if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
5582             continue;
5583
5584         i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
5585
5586         if ( i_lowest_dts == VLC_TS_INVALID )
5587             i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
5588         else
5589             i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
5590     }
5591
5592     p_sys->i_time = i_lowest_time;
5593     p_sys->i_pcr = i_lowest_dts;
5594     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
5595
5596     return 1;
5597 }
5598
5599 #undef BOXDATA