]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
demux: mp4: don't trust atom type processing stsd (fix #12285)
[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 || p_sample->i_handler != ATOM_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 || p_sample->i_handler != ATOM_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             if ( p_sample->i_handler != ATOM_soun )
2552                 break;
2553             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2554
2555             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2556                 p_track->fmt.i_codec = VLC_CODEC_U8;
2557             else
2558                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2559
2560             /* Buggy files workaround */
2561             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2562                 p_sample->data.p_sample_soun->i_sampleratehi) )
2563             {
2564                 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2565                           "(%u), making both equal (report any problem).",
2566                           p_track->i_timescale, p_soun->i_sampleratehi );
2567
2568                 if( p_soun->i_sampleratehi != 0 )
2569                     p_track->i_timescale = p_soun->i_sampleratehi;
2570                 else
2571                     p_soun->i_sampleratehi = p_track->i_timescale;
2572             }
2573             break;
2574         }
2575
2576         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2577             p_track->fmt.i_codec = VLC_CODEC_H263;
2578             break;
2579
2580         case( ATOM_c608 ): /* EIA608 closed captions */
2581         //case( ATOM_c708 ): /* EIA708 closed captions */
2582             p_track->fmt.i_codec = VLC_CODEC_EIA608_1;
2583             p_track->fmt.i_cat = SPU_ES;
2584             break;
2585
2586         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2587         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2588         {
2589             if ( p_sample->i_handler != ATOM_text )
2590                 break;
2591             p_track->fmt.i_codec = VLC_CODEC_TX3G;
2592             MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2593             if ( p_text )
2594             {
2595                 text_style_t *p_style = text_style_New();
2596                 if ( p_style )
2597                 {
2598                     if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2599                         p_style->i_font_size = p_text->i_font_size;
2600                     if ( p_text->i_font_color )
2601                     {
2602                         p_style->i_font_color = p_text->i_font_color >> 8;
2603                         p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2604                     }
2605                     if ( p_text->i_background_color[3] >> 8 )
2606                     {
2607                         p_style->i_background_color = p_text->i_background_color[0] >> 8;
2608                         p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2609                         p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2610                         p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2611                     }
2612                 }
2613                 p_track->fmt.subs.p_style = p_style;
2614             }
2615             /* FIXME UTF-8 doesn't work here ? */
2616             if( p_track->b_mac_encoding )
2617                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2618             else
2619                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2620             break;
2621         }
2622         case VLC_FOURCC('y','v','1','2'):
2623             p_track->fmt.i_codec = VLC_CODEC_YV12;
2624             break;
2625         case VLC_FOURCC('y','u','v','2'):
2626             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2627             break;
2628
2629         case VLC_FOURCC('i','n','2','4'):
2630             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2631                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2632             break;
2633         case VLC_FOURCC('i','n','3','2'):
2634             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2635                                     VLC_CODEC_S32L : VLC_CODEC_S32B;
2636             break;
2637         case VLC_FOURCC('f','l','3','2'):
2638             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2639                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
2640             break;
2641         case VLC_FOURCC('f','l','6','4'):
2642             p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2643                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
2644             break;
2645         case VLC_CODEC_DVD_LPCM:
2646         {
2647             if ( p_sample->i_handler != ATOM_soun )
2648                 break;
2649             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2650             if( p_soun->i_qt_version == 2 )
2651             {
2652                 /* Flags:
2653                  *  0x01: IsFloat
2654                  *  0x02: IsBigEndian
2655                  *  0x04: IsSigned
2656                  */
2657                 static const struct {
2658                     unsigned     i_flags;
2659                     unsigned     i_mask;
2660                     unsigned     i_bits;
2661                     vlc_fourcc_t i_codec;
2662                 } p_formats[] = {
2663                     { 0x01,           0x03, 32, VLC_CODEC_F32L },
2664                     { 0x01,           0x03, 64, VLC_CODEC_F64L },
2665                     { 0x01|0x02,      0x03, 32, VLC_CODEC_F32B },
2666                     { 0x01|0x02,      0x03, 64, VLC_CODEC_F64B },
2667
2668                     { 0x00,           0x05,  8, VLC_CODEC_U8 },
2669                     { 0x00|     0x04, 0x05,  8, VLC_CODEC_S8 },
2670
2671                     { 0x00,           0x07, 16, VLC_CODEC_U16L },
2672                     { 0x00|0x02,      0x07, 16, VLC_CODEC_U16B },
2673                     { 0x00     |0x04, 0x07, 16, VLC_CODEC_S16L },
2674                     { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2675
2676                     { 0x00,           0x07, 24, VLC_CODEC_U24L },
2677                     { 0x00|0x02,      0x07, 24, VLC_CODEC_U24B },
2678                     { 0x00     |0x04, 0x07, 24, VLC_CODEC_S24L },
2679                     { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2680
2681                     { 0x00,           0x07, 32, VLC_CODEC_U32L },
2682                     { 0x00|0x02,      0x07, 32, VLC_CODEC_U32B },
2683                     { 0x00     |0x04, 0x07, 32, VLC_CODEC_S32L },
2684                     { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2685
2686                     {0, 0, 0, 0}
2687                 };
2688
2689                 for( int i = 0; p_formats[i].i_codec; i++ )
2690                 {
2691                     if( p_formats[i].i_bits == p_soun->i_constbitsperchannel &&
2692                         (p_soun->i_formatflags & p_formats[i].i_mask) == p_formats[i].i_flags )
2693                     {
2694                         p_track->fmt.i_codec = p_formats[i].i_codec;
2695                         p_track->fmt.audio.i_bitspersample = p_soun->i_constbitsperchannel;
2696                         p_track->fmt.audio.i_blockalign =
2697                                 p_soun->i_channelcount * p_soun->i_constbitsperchannel / 8;
2698                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2699
2700                         p_soun->i_qt_version = 0;
2701                         break;
2702                     }
2703                 }
2704             }
2705             break;
2706         }
2707         default:
2708             p_track->fmt.i_codec = p_sample->i_type;
2709             break;
2710     }
2711
2712     /* now see if esds is present and if so create a data packet
2713         with decoder_specific_info  */
2714 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2715     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2716           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2717         ( p_esds->data.p_esds )&&
2718         ( p_decconfig ) )
2719     {
2720         /* First update information based on i_objectTypeIndication */
2721         switch( p_decconfig->i_objectTypeIndication )
2722         {
2723             case( 0x20 ): /* MPEG4 VIDEO */
2724                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2725                 break;
2726             case( 0x21 ): /* H.264 */
2727                 p_track->fmt.i_codec = VLC_CODEC_H264;
2728                 break;
2729             case( 0x40):
2730                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2731                 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2732                      p_decconfig->p_decoder_specific_info[0]       == 0xF8 &&
2733                     (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2734                 {
2735                     p_track->fmt.i_codec = VLC_CODEC_ALS;
2736                 }
2737                 break;
2738             case( 0x60):
2739             case( 0x61):
2740             case( 0x62):
2741             case( 0x63):
2742             case( 0x64):
2743             case( 0x65): /* MPEG2 video */
2744                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2745                 break;
2746             /* Theses are MPEG2-AAC */
2747             case( 0x66): /* main profile */
2748             case( 0x67): /* Low complexity profile */
2749             case( 0x68): /* Scaleable Sampling rate profile */
2750                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2751                 break;
2752             /* True MPEG 2 audio */
2753             case( 0x69):
2754                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2755                 break;
2756             case( 0x6a): /* MPEG1 video */
2757                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2758                 break;
2759             case( 0x6b): /* MPEG1 audio */
2760                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2761                 break;
2762             case( 0x6c ): /* jpeg */
2763                 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2764                 break;
2765             case( 0x6d ): /* png */
2766                 p_track->fmt.i_codec = VLC_CODEC_PNG;
2767                 break;
2768             case( 0x6e ): /* jpeg2000 */
2769                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2770                 break;
2771             case( 0xa3 ): /* vc1 */
2772                 p_track->fmt.i_codec = VLC_CODEC_VC1;
2773                 break;
2774             case( 0xa4 ):
2775                 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2776                 break;
2777             case( 0xa5 ):
2778                 p_track->fmt.i_codec = VLC_CODEC_A52;
2779                 break;
2780             case( 0xa6 ):
2781                 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2782                 break;
2783             case( 0xa9 ): /* dts */
2784             case( 0xaa ): /* DTS-HD HRA */
2785             case( 0xab ): /* DTS-HD Master Audio */
2786                 p_track->fmt.i_codec = VLC_CODEC_DTS;
2787                 break;
2788             case( 0xDD ):
2789                 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2790                 break;
2791
2792             /* Private ID */
2793             case( 0xe0 ): /* NeroDigital: dvd subs */
2794                 if( p_track->fmt.i_cat == SPU_ES )
2795                 {
2796                     p_track->fmt.i_codec = VLC_CODEC_SPU;
2797                     if( p_track->i_width > 0 )
2798                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2799                     if( p_track->i_height > 0 )
2800                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2801                     break;
2802                 }
2803             case( 0xe1 ): /* QCelp for 3gp */
2804                 if( p_track->fmt.i_cat == AUDIO_ES )
2805                 {
2806                     p_track->fmt.i_codec = VLC_CODEC_QCELP;
2807                 }
2808                 break;
2809
2810             /* Fallback */
2811             default:
2812                 /* Unknown entry, but don't touch i_fourcc */
2813                 msg_Warn( p_demux,
2814                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2815                           p_decconfig->i_objectTypeIndication,
2816                           p_track->i_track_ID );
2817                 break;
2818         }
2819         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2820         if( p_track->fmt.i_extra > 0 )
2821         {
2822             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2823             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2824                     p_track->fmt.i_extra );
2825         }
2826         if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2827             p_track->fmt.i_extra >= 16 * 4 )
2828         {
2829             for( int i = 0; i < 16; i++ )
2830             {
2831                 p_track->fmt.subs.spu.palette[1 + i] =
2832                             GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2833             }
2834             p_track->fmt.subs.spu.palette[0] = 0xBeef;
2835         }
2836     }
2837     else
2838     {
2839         switch( p_sample->i_type )
2840         {
2841             /* qt decoder, send the complete chunk */
2842             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2843             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2844             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2845             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2846             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2847             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2848             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2849             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2850             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2851             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2852             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2853             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2854                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2855                 break;
2856             /* qt decoder, send the complete chunk */
2857             case VLC_CODEC_SVQ1:
2858             case VLC_CODEC_SVQ3:
2859             case VLC_FOURCC( 'V', 'P', '3', '1' ):
2860             case VLC_FOURCC( '3', 'I', 'V', '1' ):
2861             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2862             {
2863                 if ( p_sample->i_handler != ATOM_vide )
2864                     break;
2865                 p_track->fmt.i_extra =
2866                     p_sample->data.p_sample_vide->i_qt_image_description;
2867                 if( p_track->fmt.i_extra > 0 )
2868                 {
2869                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2870                     memcpy( p_track->fmt.p_extra,
2871                             p_sample->data.p_sample_vide->p_qt_image_description,
2872                             p_track->fmt.i_extra);
2873                 }
2874                 break;
2875             }
2876
2877             case VLC_CODEC_AMR_NB:
2878                 p_track->fmt.audio.i_rate = 8000;
2879                 break;
2880             case VLC_CODEC_AMR_WB:
2881                 p_track->fmt.audio.i_rate = 16000;
2882                 break;
2883             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2884             case VLC_CODEC_QDM2:
2885             case VLC_CODEC_ALAC:
2886             {
2887                 if ( p_sample->i_handler != ATOM_soun )
2888                     break;
2889                 p_track->fmt.i_extra =
2890                     p_sample->data.p_sample_soun->i_qt_description;
2891                 if( p_track->fmt.i_extra > 0 )
2892                 {
2893                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2894                     memcpy( p_track->fmt.p_extra,
2895                             p_sample->data.p_sample_soun->p_qt_description,
2896                             p_track->fmt.i_extra);
2897                 }
2898                 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2899                 {
2900                     p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2901                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2902                 }
2903                 break;
2904             }
2905             case VLC_FOURCC( 'v', 'c', '-', '1' ):
2906             {
2907                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2908                 if( p_dvc1 )
2909                 {
2910                     p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
2911                     if( p_track->fmt.i_extra > 0 )
2912                     {
2913                         p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
2914                         memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
2915                                 p_track->fmt.i_extra );
2916                     }
2917                 }
2918                 else
2919                 {
2920                     msg_Err( p_demux, "missing dvc1" );
2921                 }
2922                 break;
2923             }
2924
2925             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2926             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2927             {
2928                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2929
2930                 if( p_avcC )
2931                 {
2932                     p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
2933                     if( p_track->fmt.i_extra > 0 )
2934                     {
2935                         p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
2936                         memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
2937                                 p_track->fmt.i_extra );
2938                     }
2939                 }
2940                 else
2941                 {
2942                     msg_Err( p_demux, "missing avcC" );
2943                 }
2944                 break;
2945             }
2946             case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2947             case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2948             {
2949                 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2950
2951                 if( p_hvcC )
2952                 {
2953                     p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2954                     if( p_track->fmt.i_extra > 0 )
2955                     {
2956                         p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2957                         memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2958                                 p_track->fmt.i_extra );
2959                     }
2960                     p_track->fmt.i_codec = VLC_CODEC_HEVC;
2961                 }
2962                 else
2963                 {
2964                     msg_Err( p_demux, "missing hvcC" );
2965                 }
2966                 break;
2967             }
2968
2969
2970             case VLC_CODEC_ADPCM_MS:
2971             case VLC_CODEC_ADPCM_IMA_WAV:
2972             case VLC_CODEC_QCELP:
2973             {
2974                 if ( p_sample->i_handler == ATOM_soun )
2975                     p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2976                 break;
2977             }
2978
2979             default:
2980                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2981                 break;
2982         }
2983     }
2984
2985 #undef p_decconfig
2986
2987     if( pp_es )
2988         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2989
2990     return VLC_SUCCESS;
2991 }
2992
2993 /* given a time it return sample/chunk
2994  * it also update elst field of the track
2995  */
2996 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2997                                    int64_t i_start, uint32_t *pi_chunk,
2998                                    uint32_t *pi_sample )
2999 {
3000     demux_sys_t *p_sys = p_demux->p_sys;
3001     MP4_Box_t   *p_box_stss;
3002     uint64_t     i_dts;
3003     unsigned int i_sample;
3004     unsigned int i_chunk;
3005     int          i_index;
3006
3007     /* FIXME see if it's needed to check p_track->i_chunk_count */
3008     if( p_track->i_chunk_count == 0 )
3009         return( VLC_EGENERIC );
3010
3011     /* handle elst (find the correct one) */
3012     MP4_TrackSetELST( p_demux, p_track, i_start );
3013     if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3014     {
3015         MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3016         int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
3017
3018         /* now calculate i_start for this elst */
3019         /* offset */
3020         i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
3021         if( i_start < 0 )
3022         {
3023             *pi_chunk = 0;
3024             *pi_sample= 0;
3025
3026             return VLC_SUCCESS;
3027         }
3028         /* to track time scale */
3029         i_start  = i_start * p_track->i_timescale / CLOCK_FREQ;
3030         /* add elst offset */
3031         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
3032              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
3033             elst->i_media_time[p_track->i_elst] > 0 )
3034         {
3035             i_start += elst->i_media_time[p_track->i_elst];
3036         }
3037
3038         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
3039                  "ms (track)", p_track->i_elst,
3040                  i_mvt * 1000 / p_sys->i_timescale,
3041                  i_start * 1000 / p_track->i_timescale );
3042     }
3043     else
3044     {
3045         /* convert absolute time to in timescale unit */
3046         i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
3047     }
3048
3049     /* we start from sample 0/chunk 0, hope it won't take too much time */
3050     /* *** find good chunk *** */
3051     for( i_chunk = 0; ; i_chunk++ )
3052     {
3053         if( i_chunk + 1 >= p_track->i_chunk_count )
3054         {
3055             /* at the end and can't check if i_start in this chunk,
3056                it will be check while searching i_sample */
3057             i_chunk = p_track->i_chunk_count - 1;
3058             break;
3059         }
3060
3061         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
3062             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
3063         {
3064             break;
3065         }
3066     }
3067
3068     /* *** find sample in the chunk *** */
3069     i_sample = p_track->chunk[i_chunk].i_sample_first;
3070     i_dts    = p_track->chunk[i_chunk].i_first_dts;
3071     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
3072     {
3073         if( i_dts +
3074             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3075             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
3076         {
3077             i_dts    +=
3078                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3079                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3080
3081             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
3082             i_index++;
3083         }
3084         else
3085         {
3086             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
3087             {
3088                 break;
3089             }
3090             i_sample += ( i_start - i_dts ) /
3091                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3092             break;
3093         }
3094     }
3095
3096     if( i_sample >= p_track->i_sample_count )
3097     {
3098         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
3099                   "(seeking too far) chunk=%d sample=%d",
3100                   p_track->i_track_ID, i_chunk, i_sample );
3101         return( VLC_EGENERIC );
3102     }
3103
3104
3105     /* *** Try to find nearest sync points *** */
3106     if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
3107     {
3108         MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
3109         msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
3110                  p_track->i_track_ID );
3111         for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
3112         {
3113             if( i_index >= p_stss->i_entry_count - 1 ||
3114                 i_sample < p_stss->i_sample_number[i_index+1] )
3115             {
3116                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
3117                 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
3118                          i_sample, i_sync_sample );
3119
3120                 if( i_sync_sample <= i_sample )
3121                 {
3122                     while( i_chunk > 0 &&
3123                            i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
3124                         i_chunk--;
3125                 }
3126                 else
3127                 {
3128                     while( i_chunk < p_track->i_chunk_count - 1 &&
3129                            i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
3130                                             p_track->chunk[i_chunk].i_sample_count )
3131                         i_chunk++;
3132                 }
3133                 i_sample = i_sync_sample;
3134                 break;
3135             }
3136         }
3137     }
3138     else
3139     {
3140         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
3141                  "Sample Box (stss)", p_track->i_track_ID );
3142     }
3143
3144     *pi_chunk  = i_chunk;
3145     *pi_sample = i_sample;
3146
3147     return VLC_SUCCESS;
3148 }
3149
3150 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
3151                                  unsigned int i_chunk, unsigned int i_sample )
3152 {
3153     bool b_reselect = false;
3154
3155     /* now see if actual es is ok */
3156     if( p_track->i_chunk >= p_track->i_chunk_count ||
3157         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
3158             p_track->chunk[i_chunk].i_sample_description_index )
3159     {
3160         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
3161                   p_track->i_track_ID );
3162
3163         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
3164                         p_track->p_es, &b_reselect );
3165
3166         es_out_Del( p_demux->out, p_track->p_es );
3167
3168         p_track->p_es = NULL;
3169
3170         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
3171         {
3172             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3173                      p_track->i_track_ID );
3174
3175             p_track->b_ok       = false;
3176             p_track->b_selected = false;
3177             return VLC_EGENERIC;
3178         }
3179     }
3180
3181     /* select again the new decoder */
3182     if( b_reselect )
3183     {
3184         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
3185     }
3186
3187     p_track->i_chunk    = i_chunk;
3188     p_track->i_sample   = i_sample;
3189
3190     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3191 }
3192
3193 /****************************************************************************
3194  * MP4_TrackCreate:
3195  ****************************************************************************
3196  * Parse track information and create all needed data to run a track
3197  * If it succeed b_ok is set to 1 else to 0
3198  ****************************************************************************/
3199 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
3200                              MP4_Box_t *p_box_trak,
3201                              bool b_force_enable )
3202 {
3203     demux_sys_t *p_sys = p_demux->p_sys;
3204
3205     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
3206     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
3207     MP4_Box_t *p_elst;
3208
3209     MP4_Box_t *p_mdhd;
3210     MP4_Box_t *p_udta;
3211     MP4_Box_t *p_hdlr;
3212
3213     MP4_Box_t *p_vmhd;
3214     MP4_Box_t *p_smhd;
3215
3216     char language[4] = { '\0' };
3217
3218     /* hint track unsupported */
3219
3220     /* set default value (-> track unusable) */
3221     p_track->b_ok       = false;
3222     p_track->b_enable   = false;
3223     p_track->b_selected = false;
3224     p_track->b_chapter  = false;
3225     p_track->b_mac_encoding = false;
3226
3227     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
3228
3229     if( !p_tkhd )
3230     {
3231         return;
3232     }
3233
3234     /* do we launch this track by default ? */
3235     p_track->b_enable =
3236         ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
3237     if( !p_track->b_enable )
3238         p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
3239
3240     p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
3241
3242     p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
3243     p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
3244     p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
3245
3246     if( p_tref )
3247     {
3248 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
3249     }
3250
3251     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
3252     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
3253
3254     if( ( !p_mdhd )||( !p_hdlr ) )
3255     {
3256         return;
3257     }
3258
3259     p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
3260     if( p_track->i_timescale == 0 )
3261         return;
3262
3263     memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
3264     p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
3265
3266     switch( p_hdlr->data.p_hdlr->i_handler_type )
3267     {
3268         case( ATOM_soun ):
3269             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
3270             {
3271                 return;
3272             }
3273             p_track->fmt.i_cat = AUDIO_ES;
3274             break;
3275
3276         case( ATOM_vide ):
3277             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
3278             {
3279                 return;
3280             }
3281             p_track->fmt.i_cat = VIDEO_ES;
3282             break;
3283
3284         case( ATOM_tx3g ):
3285         case( ATOM_text ):
3286         case( ATOM_subp ):
3287         case( ATOM_sbtl ):
3288             p_track->fmt.i_codec = VLC_CODEC_TX3G;
3289             p_track->fmt.i_cat = SPU_ES;
3290             break;
3291
3292         /* closed captions */
3293         case( ATOM_clcp ):
3294             p_track->fmt.i_cat = SPU_ES;
3295             break;
3296
3297         default:
3298             return;
3299     }
3300
3301     p_track->i_elst = 0;
3302     p_track->i_elst_time = 0;
3303     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
3304     {
3305         MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
3306         unsigned int i;
3307
3308         msg_Warn( p_demux, "elst box found" );
3309         for( i = 0; i < elst->i_entry_count; i++ )
3310         {
3311             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
3312                      "ms) rate=%d.%d", i,
3313                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
3314                      elst->i_media_time[i] >= 0 ?
3315                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
3316                      INT64_C(-1),
3317                      elst->i_media_rate_integer[i],
3318                      elst->i_media_rate_fraction[i] );
3319         }
3320     }
3321
3322
3323 /*  TODO
3324     add support for:
3325     p_dinf = MP4_BoxGet( p_minf, "dinf" );
3326 */
3327     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
3328         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
3329     {
3330         return;
3331     }
3332
3333     /* Set language */
3334     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
3335     {
3336         p_track->fmt.psz_language = strdup( language );
3337     }
3338
3339     p_udta = MP4_BoxGet( p_box_trak, "udta" );
3340     if( p_udta )
3341     {
3342         MP4_Box_t *p_box_iter;
3343         for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
3344                  p_box_iter = p_box_iter->p_next )
3345         {
3346             switch( p_box_iter->i_type )
3347             {
3348                 case ATOM_0xa9nam:
3349                     p_track->fmt.psz_description =
3350                         strdup( p_box_iter->data.p_0xa9xxx->psz_text );
3351                     break;
3352                 case ATOM_name:
3353                     p_track->fmt.psz_description =
3354                         strdup( p_box_iter->data.p_name->psz_text );
3355                     break;
3356             }
3357         }
3358     }
3359
3360     /* Create chunk index table and sample index table */
3361     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
3362         TrackCreateSamplesIndex( p_demux, p_track ) )
3363     {
3364         msg_Err( p_demux, "cannot create chunks index" );
3365         return; /* cannot create chunks index */
3366     }
3367
3368     p_track->i_chunk  = 0;
3369     p_track->i_sample = 0;
3370
3371     /* Mark chapter only track */
3372     if( p_sys->p_tref_chap )
3373     {
3374         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
3375         unsigned int i;
3376
3377         for( i = 0; i < p_chap->i_entry_count; i++ )
3378         {
3379             if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
3380                 p_track->fmt.i_cat == UNKNOWN_ES )
3381             {
3382                 p_track->b_chapter = true;
3383                 p_track->b_enable = false;
3384                 break;
3385             }
3386         }
3387     }
3388
3389     /* now create es */
3390     if( b_force_enable &&
3391         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
3392     {
3393         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
3394                   p_track->i_track_ID );
3395         p_track->b_enable = true;
3396         p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
3397     }
3398
3399     p_track->p_es = NULL;
3400     if( TrackCreateES( p_demux,
3401                        p_track, p_track->i_chunk,
3402                        p_track->b_chapter ? NULL : &p_track->p_es ) )
3403     {
3404         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3405                  p_track->i_track_ID );
3406         return;
3407     }
3408     p_track->b_ok = true;
3409 #if 0
3410     {
3411         int i;
3412         for( i = 0; i < p_track->i_chunk_count; i++ )
3413         {
3414             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
3415                      i, p_track->chunk[i].i_sample_count,
3416                      p_track->chunk[i].i_first_dts );
3417
3418         }
3419     }
3420 #endif
3421 }
3422
3423 static void FreeAndResetChunk( mp4_chunk_t *ck )
3424 {
3425     free( ck->p_sample_count_dts );
3426     free( ck->p_sample_delta_dts );
3427     free( ck->p_sample_count_pts );
3428     free( ck->p_sample_offset_pts );
3429     free( ck->p_sample_size );
3430     for( uint32_t i = 0; i < ck->i_sample_count; i++ )
3431         free( ck->p_sample_data[i] );
3432     free( ck->p_sample_data );
3433     memset( ck, 0, sizeof( mp4_chunk_t ) );
3434 }
3435
3436 /****************************************************************************
3437  * MP4_TrackDestroy:
3438  ****************************************************************************
3439  * Destroy a track created by MP4_TrackCreate.
3440  ****************************************************************************/
3441 static void MP4_TrackDestroy( mp4_track_t *p_track )
3442 {
3443     unsigned int i_chunk;
3444
3445     p_track->b_ok = false;
3446     p_track->b_enable   = false;
3447     p_track->b_selected = false;
3448
3449     es_format_Clean( &p_track->fmt );
3450
3451     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
3452     {
3453         if( p_track->chunk )
3454         {
3455            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
3456            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
3457
3458            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
3459            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3460         }
3461     }
3462     FREENULL( p_track->chunk );
3463     if( p_track->cchunk ) {
3464         FreeAndResetChunk( p_track->cchunk );
3465         FREENULL( p_track->cchunk );
3466     }
3467
3468     if( !p_track->i_sample_size )
3469     {
3470         FREENULL( p_track->p_sample_size );
3471     }
3472 }
3473
3474 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3475                             mtime_t i_start )
3476 {
3477     if( !p_track->b_ok || p_track->b_chapter )
3478     {
3479         return VLC_EGENERIC;
3480     }
3481
3482     if( p_track->b_selected )
3483     {
3484         msg_Warn( p_demux, "track[Id 0x%x] already selected",
3485                   p_track->i_track_ID );
3486         return VLC_SUCCESS;
3487     }
3488
3489     return MP4_TrackSeek( p_demux, p_track, i_start );
3490 }
3491
3492 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3493 {
3494     if( !p_track->b_ok || p_track->b_chapter )
3495     {
3496         return;
3497     }
3498
3499     if( !p_track->b_selected )
3500     {
3501         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3502                   p_track->i_track_ID );
3503         return;
3504     }
3505     if( p_track->p_es )
3506     {
3507         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3508                         p_track->p_es, false );
3509     }
3510
3511     p_track->b_selected = false;
3512 }
3513
3514 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3515                           mtime_t i_start )
3516 {
3517     uint32_t i_chunk;
3518     uint32_t i_sample;
3519
3520     if( !p_track->b_ok || p_track->b_chapter )
3521         return VLC_EGENERIC;
3522
3523     p_track->b_selected = false;
3524
3525     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3526                                 &i_chunk, &i_sample ) )
3527     {
3528         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3529                   p_track->i_track_ID );
3530         return VLC_EGENERIC;
3531     }
3532
3533     p_track->b_selected = true;
3534     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3535         p_track->b_selected = true;
3536
3537     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3538 }
3539
3540
3541 /*
3542  * 3 types: for audio
3543  *
3544  */
3545 #define QT_V0_MAX_SAMPLES 1024
3546 static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3547 {
3548     uint32_t i_size = 0;
3549     *pi_nb_samples = 0;
3550
3551     if ( p_track->i_sample == p_track->i_sample_count )
3552         return 0;
3553
3554     if ( p_track->fmt.i_cat != AUDIO_ES )
3555     {
3556         *pi_nb_samples = 1;
3557
3558         if( p_track->i_sample_size == 0 ) /* all sizes are different */
3559             return p_track->p_sample_size[p_track->i_sample];
3560         else
3561             return p_track->i_sample_size;
3562     }
3563     else
3564     {
3565         const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
3566         const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3567         uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample + 1;
3568
3569         /* Group audio packets so we don't call demux for single sample unit */
3570         if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
3571             p_soun->i_constLPCMframesperaudiopacket &&
3572             p_soun->i_constbytesperaudiopacket )
3573         {
3574             /* uncompressed case */
3575             uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
3576             if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
3577                 i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
3578             *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
3579             return i_packets * p_soun->i_constbytesperaudiopacket;
3580         }
3581
3582         /* all samples have a different size */
3583         if( p_track->i_sample_size == 0 )
3584         {
3585             *pi_nb_samples = 1;
3586             return p_track->p_sample_size[p_track->i_sample];
3587         }
3588
3589         if( p_soun->i_qt_version == 1 )
3590         {
3591             if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
3592             {
3593                 /* in this case we are dealing with compressed data
3594                    -2 in V1: additional fields are meaningless (VBR and such) */
3595                 *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
3596                 if( p_track->fmt.audio.i_blockalign > 1 )
3597                     *pi_nb_samples = p_soun->i_sample_per_packet;
3598                 i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3599                 return i_size;
3600             }
3601             else /* uncompressed case */
3602             {
3603                 uint32_t i_packets;
3604                 if( p_track->fmt.audio.i_blockalign > 1 )
3605                     i_packets = 1;
3606                 else
3607                     i_packets = i_max_samples / p_soun->i_sample_per_packet;
3608
3609                 if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
3610                     i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
3611
3612                 *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
3613                 i_size = i_packets * p_soun->i_bytes_per_frame;
3614                 return i_size;
3615             }
3616         }
3617
3618         /* uncompressed v0 */
3619         *pi_nb_samples = 0;
3620         for( uint32_t i=p_track->i_sample;
3621              i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
3622              i<p_track->i_sample_count;
3623              i++ )
3624         {
3625             (*pi_nb_samples)++;
3626             if ( p_track->i_sample_size == 0 )
3627                 i_size += p_track->p_sample_size[i];
3628             else
3629                 i_size += p_track->i_sample_size;
3630             if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
3631                 break;
3632         }
3633     }
3634
3635     //fprintf( stderr, "size=%d\n", i_size );
3636     return i_size;
3637 }
3638
3639 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3640 {
3641     unsigned int i_sample;
3642     uint64_t i_pos;
3643
3644     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3645
3646     if( p_track->i_sample_size )
3647     {
3648         MP4_Box_data_sample_soun_t *p_soun =
3649             p_track->p_sample->data.p_sample_soun;
3650
3651         if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3652         {
3653             i_pos += ( p_track->i_sample -
3654                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
3655                      p_track->i_sample_size;
3656         }
3657         else
3658         {
3659             /* we read chunk by chunk unless a blockalign is requested */
3660             if( p_track->fmt.audio.i_blockalign > 1 )
3661                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3662                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3663         }
3664     }
3665     else
3666     {
3667         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3668              i_sample < p_track->i_sample; i_sample++ )
3669         {
3670             i_pos += p_track->p_sample_size[i_sample];
3671         }
3672     }
3673
3674     return i_pos;
3675 }
3676
3677 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3678 {
3679     if ( UINT32_MAX - p_track->i_sample < i_samples )
3680     {
3681         p_track->i_sample = UINT32_MAX;
3682         return VLC_EGENERIC;
3683     }
3684
3685     p_track->i_sample += i_samples;
3686
3687     if( p_track->i_sample >= p_track->i_sample_count )
3688         return VLC_EGENERIC;
3689
3690     /* Have we changed chunk ? */
3691     if( p_track->i_sample >=
3692             p_track->chunk[p_track->i_chunk].i_sample_first +
3693             p_track->chunk[p_track->i_chunk].i_sample_count )
3694     {
3695         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3696                                   p_track->i_sample ) )
3697         {
3698             msg_Warn( p_demux, "track[0x%x] will be disabled "
3699                       "(cannot restart decoder)", p_track->i_track_ID );
3700             MP4_TrackUnselect( p_demux, p_track );
3701             return VLC_EGENERIC;
3702         }
3703     }
3704
3705     /* Have we changed elst */
3706     if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3707     {
3708         demux_sys_t *p_sys = p_demux->p_sys;
3709         MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3710         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3711                         p_sys->i_timescale / CLOCK_FREQ;
3712
3713         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3714             i_mvt >= p_track->i_elst_time +
3715                      elst->i_segment_duration[p_track->i_elst] )
3716         {
3717             MP4_TrackSetELST( p_demux, p_track,
3718                               MP4_TrackGetDTS( p_demux, p_track ) );
3719         }
3720     }
3721
3722     return VLC_SUCCESS;
3723 }
3724
3725 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3726                               int64_t i_time )
3727 {
3728     demux_sys_t *p_sys = p_demux->p_sys;
3729     int         i_elst_last = tk->i_elst;
3730
3731     /* handle elst (find the correct one) */
3732     tk->i_elst      = 0;
3733     tk->i_elst_time = 0;
3734     if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3735     {
3736         MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3737         int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3738
3739         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3740         {
3741             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3742
3743             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3744             {
3745                 break;
3746             }
3747             tk->i_elst_time += i_dur;
3748         }
3749
3750         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3751         {
3752             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3753             tk->i_elst = elst->i_entry_count - 1;
3754             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3755         }
3756
3757         if( elst->i_media_time[tk->i_elst] < 0 )
3758         {
3759             /* track offset */
3760             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3761         }
3762     }
3763     if( i_elst_last != tk->i_elst )
3764     {
3765         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3766     }
3767 }
3768
3769 /******************************************************************************
3770  *     Here are the functions used for fragmented MP4
3771  *****************************************************************************/
3772
3773 /**
3774  * It computes the sample rate for a video track using current video chunk
3775  */
3776 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3777                                   const mp4_track_t *p_track )
3778 {
3779     if( p_track->cchunk->i_last_dts == 0 )
3780         return;
3781
3782     *pi_num = 0;
3783     *pi_den = 0;
3784
3785     /* */
3786     const mp4_chunk_t *p_chunk = p_track->cchunk;
3787
3788     uint32_t i_sample = p_chunk->i_sample_count;
3789     uint64_t i_first_dts = p_chunk->i_first_dts;
3790     uint64_t i_last_dts =  p_chunk->i_last_dts;
3791
3792     if( i_sample > 1 && i_first_dts < i_last_dts )
3793         vlc_ureduce( pi_num, pi_den,
3794                      ( i_sample - 1) *  p_track->i_timescale,
3795                      i_last_dts - i_first_dts,
3796                      UINT16_MAX);
3797 }
3798
3799 /**
3800  * Build raw avcC box (without the 8 bytes header)
3801  * \return The size of the box.
3802  */
3803 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3804                                                        const unsigned cpd_len )
3805 {
3806     uint8_t *avcC;
3807     unsigned sps_len = 0, pps_len = 0;
3808     const uint32_t mark = 0x00000001;
3809
3810     assert( CodecPrivateData[0] == 0 );
3811     assert( CodecPrivateData[1] == 0 );
3812     assert( CodecPrivateData[2] == 0 );
3813     assert( CodecPrivateData[3] == 1 );
3814
3815     uint32_t length = cpd_len + 3;
3816     avcC = calloc( length, 1 );
3817     if( unlikely( avcC == NULL ) )
3818         return 0;
3819
3820     uint8_t *sps = avcC + 8;
3821
3822     uint32_t candidate = ~mark;
3823     CodecPrivateData += 4;
3824     for( unsigned i = 0; i < cpd_len - 4; i++ )
3825     {
3826         sps[i] = CodecPrivateData[i];
3827         candidate = (candidate << 8) | CodecPrivateData[i];
3828         if( candidate == mark )
3829         {
3830             sps_len = i - 3;
3831             break;
3832         }
3833     }
3834     if( sps_len == 0 )
3835     {
3836         free( avcC );
3837         return 0;
3838     }
3839     uint8_t *pps = sps + sps_len + 3;
3840     pps_len = cpd_len - sps_len - 4 * 2;
3841     memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3842
3843     /* XXX */
3844     uint8_t AVCProfileIndication = 0x64;
3845     uint8_t profile_compatibility = 0x40;
3846     uint8_t AVCLevelIndication = 0x1f;
3847     uint8_t lengthSizeMinusOne = 0x03;
3848
3849     avcC[0] = 1;
3850     avcC[1] = AVCProfileIndication;
3851     avcC[2] = profile_compatibility;
3852     avcC[3] = AVCLevelIndication;
3853     avcC[4] = 0xfc + lengthSizeMinusOne;
3854     avcC[5] = 0xe0 + 1;
3855     avcC[6] = (sps_len & 0xff00)>>8;
3856     avcC[7] = sps_len & 0xff;
3857
3858     avcC[8+sps_len] = 1;
3859     avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3860     avcC[10+sps_len] = pps_len & 0xff;
3861
3862     *p_extra = avcC;
3863     return length;
3864 }
3865
3866 /**
3867  * Build a mp4_track_t from a StraBox
3868  */
3869
3870 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3871 {
3872     fmt->i_extra = p_data->cpd_len;
3873     fmt->p_extra = malloc( p_data->cpd_len );
3874     if( unlikely( !fmt->p_extra ) )
3875         return VLC_ENOMEM;
3876     memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3877     return VLC_SUCCESS;
3878   }
3879
3880 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3881 {
3882     demux_sys_t *p_sys = p_demux->p_sys;
3883     int ret;
3884     MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3885     if( !p_data )
3886         return VLC_EGENERIC;
3887
3888     p_track->b_ok       = true;
3889     p_track->b_selected = false;
3890     p_track->i_sample_count = UINT32_MAX;
3891
3892     p_track->i_timescale = p_sys->i_timescale;
3893     p_track->i_width = p_data->MaxWidth;
3894     p_track->i_height = p_data->MaxHeight;
3895     p_track->i_track_ID = p_data->i_track_ID;
3896
3897     es_format_t *fmt = &p_track->fmt;
3898     if( fmt == NULL )
3899         return VLC_EGENERIC;
3900
3901     es_format_Init( fmt, p_data->i_es_cat, 0 );
3902
3903     /* Set language FIXME */
3904     fmt->psz_language = strdup( "en" );
3905
3906     fmt->i_original_fourcc = p_data->FourCC;
3907     fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3908
3909     uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3910     /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3911      * for MS weird use of FourCC*/
3912     switch( fmt->i_cat )
3913     {
3914         case VIDEO_ES:
3915             if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3916                 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3917                 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3918             {
3919                 fmt->i_extra = build_raw_avcC( p_extra,
3920                         p_data->CodecPrivateData, p_data->cpd_len );
3921             }
3922             else
3923             {
3924                 ret = MP4_SetCodecExtraData( fmt, p_data );
3925                 if( ret != VLC_SUCCESS )
3926                     return ret;
3927             }
3928
3929             fmt->video.i_width = p_data->MaxWidth;
3930             fmt->video.i_height = p_data->MaxHeight;
3931             fmt->video.i_bits_per_pixel = 0x18;
3932             fmt->video.i_visible_width = p_data->MaxWidth;
3933             fmt->video.i_visible_height = p_data->MaxHeight;
3934
3935             /* Frame rate */
3936             ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3937                                   &fmt->video.i_frame_rate_base, p_track );
3938
3939             if( fmt->video.i_frame_rate_base != 0 )
3940             {
3941                 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3942                                         (float)fmt->video.i_frame_rate_base;
3943             }
3944             else
3945                 p_demux->p_sys->f_fps = 24;
3946
3947             break;
3948
3949         case AUDIO_ES:
3950             fmt->audio.i_channels = p_data->Channels;
3951             fmt->audio.i_rate = p_data->SamplingRate;
3952             fmt->audio.i_bitspersample = p_data->BitsPerSample;
3953             fmt->audio.i_blockalign = p_data->nBlockAlign;
3954
3955             fmt->i_bitrate = p_data->Bitrate;
3956
3957             ret = MP4_SetCodecExtraData( fmt, p_data );
3958             if( ret != VLC_SUCCESS )
3959                 return ret;
3960
3961             break;
3962
3963         default:
3964             break;
3965     }
3966
3967     return VLC_SUCCESS;
3968 }
3969
3970 /**
3971  * Return the track identified by tid
3972  */
3973 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3974 {
3975     demux_sys_t *p_sys = p_demux->p_sys;
3976
3977     mp4_track_t *ret = NULL;
3978     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3979     {
3980         ret = &p_sys->track[i];
3981         if( ret->i_track_ID == tid )
3982             return ret;
3983     }
3984     msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3985     return NULL;
3986 }
3987
3988 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3989 {
3990     msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3991     mp4_chunk_t *ck = tk->cchunk;
3992     while( ck->i_sample < ck->i_sample_count )
3993     {
3994         block_t *p_block;
3995         int64_t i_delta;
3996
3997         if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3998             return;
3999
4000         uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4001         assert( sample_size > 0 );
4002         p_block = block_Alloc( sample_size );
4003         if( unlikely( !p_block ) )
4004             return;
4005
4006         uint8_t *src = ck->p_sample_data[ck->i_sample];
4007         memcpy( p_block->p_buffer, src, sample_size );
4008         ck->i_sample++;
4009
4010         /* dts */
4011         p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4012         /* pts */
4013         i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4014         if( i_delta != -1 )
4015             p_block->i_pts = p_block->i_dts + i_delta;
4016         else if( tk->fmt.i_cat != VIDEO_ES )
4017             p_block->i_pts = p_block->i_dts;
4018         else
4019             p_block->i_pts = VLC_TS_INVALID;
4020
4021         MP4_Block_Send( p_demux, tk, p_block );
4022
4023         tk->i_sample++;
4024     }
4025 }
4026
4027 /**
4028  * Re-init decoder.
4029  * \Note If we call that function too soon,
4030  * before the track has been selected by MP4_TrackSelect
4031  * (during the first execution of Demux), then the track gets disabled
4032  */
4033 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
4034 {
4035     demux_sys_t *p_sys = p_demux->p_sys;
4036
4037     uint32_t i_sample = 0;
4038     bool b_smooth = false;
4039     MP4_Box_t *p_stra = NULL, *p_trak = NULL;
4040
4041     if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
4042         b_smooth = true;
4043
4044     if( b_smooth )
4045     {
4046         p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
4047         if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4048             return VLC_EGENERIC;
4049     }
4050     else /* DASH */
4051     {
4052         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
4053         if( !p_trak )
4054             return VLC_EGENERIC;
4055     }
4056
4057     i_sample = p_track->i_sample;
4058     es_out_Del( p_demux->out, p_track->p_es );
4059     es_format_Clean( &p_track->fmt );
4060
4061     if( b_smooth )
4062         MP4_frg_TrackCreate( p_demux, p_track, p_stra );
4063     else /* DASH */
4064         MP4_TrackCreate( p_demux, p_track, p_trak, true );
4065
4066     p_track->i_sample = i_sample;
4067
4068     /* Temporary hack until we support track selection */
4069     p_track->b_selected = true;
4070     p_track->b_ok = true;
4071     p_track->b_enable = true;
4072
4073     p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
4074     p_track->b_codec_need_restart = false;
4075
4076     return VLC_SUCCESS;
4077 }
4078
4079 /**
4080  * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
4081  * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
4082  * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
4083  * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
4084  */
4085 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
4086 {
4087     MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
4088     MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
4089     if( p_moof == NULL)
4090     {
4091         msg_Warn( p_demux, "no moof box found!" );
4092         return VLC_EGENERIC;
4093     }
4094
4095     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4096     if( p_traf == NULL)
4097     {
4098         msg_Warn( p_demux, "no traf box found!" );
4099         return VLC_EGENERIC;
4100     }
4101
4102     MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4103     if( p_tfhd == NULL)
4104     {
4105         msg_Warn( p_demux, "no tfhd box found!" );
4106         return VLC_EGENERIC;
4107     }
4108
4109     uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
4110     *i_tk_id = i_track_ID;
4111     assert( i_track_ID > 0 );
4112     msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
4113
4114     mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
4115     if( !p_track )
4116         return VLC_EGENERIC;
4117
4118     mp4_chunk_t *ret = p_track->cchunk;
4119
4120     if( BOXDATA(p_tfhd)->b_empty )
4121         msg_Warn( p_demux, "No samples in this chunk!" );
4122
4123     /* Usually we read 100 ms of each track. However, suppose we have two tracks,
4124      * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
4125      * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
4126      * and so on. Finally, suppose that we get the chunks the other way around,
4127      * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
4128      * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
4129      * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
4130      * flush it, i.e. send to the decoder the samples not yet sent.
4131      * Note that all the samples to be flushed should worth less than 100 ms,
4132      * (though I did not do the formal proof) and thus this flushing mechanism
4133      * should not cause A/V sync issues, or delays or whatever.
4134      */
4135     if( ret->i_sample < ret->i_sample_count )
4136         FlushChunk( p_demux, p_track );
4137
4138     if( ret->i_sample_count )
4139         FreeAndResetChunk( ret );
4140
4141     uint32_t default_duration = 0;
4142     if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4143         default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
4144
4145     uint32_t default_size = 0;
4146     if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4147         default_size = BOXDATA(p_tfhd)->i_default_sample_size;
4148
4149     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
4150     if( p_trun == NULL)
4151     {
4152         msg_Warn( p_demux, "no trun box found!" );
4153         return VLC_EGENERIC;
4154     }
4155     MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
4156
4157     ret->i_sample_count = p_trun_data->i_sample_count;
4158     assert( ret->i_sample_count > 0 );
4159     ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
4160     ret->i_sample_first = p_track->i_sample_first;
4161     p_track->i_sample_first += ret->i_sample_count;
4162
4163     ret->i_first_dts = p_track->i_first_dts;
4164
4165     /* XXX I already saw DASH content with no default_duration and no
4166      * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
4167      * This chunk of code might be buggy with segments having
4168      * more than one subsegment. */
4169     if( !default_duration )
4170     {
4171         MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
4172         if ( p_trex )
4173             default_duration = BOXDATA(p_trex)->i_default_sample_duration;
4174         else if( p_sidx )
4175         {
4176             MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
4177             assert( p_sidx_data->i_reference_count == 1 );
4178
4179             if( p_sidx_data->i_timescale == 0 )
4180                 return VLC_EGENERIC;
4181
4182             unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
4183                                         p_sidx_data->i_timescale;
4184             default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
4185
4186         }
4187     }
4188
4189     msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
4190
4191     ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4192     ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4193
4194     if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
4195         return VLC_ENOMEM;
4196
4197     ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4198     if( !ret->p_sample_count_pts )
4199         return VLC_ENOMEM;
4200
4201     if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4202     {
4203         ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
4204         if( !ret->p_sample_offset_pts )
4205             return VLC_ENOMEM;
4206     }
4207
4208     ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4209     if( !ret->p_sample_size )
4210         return VLC_ENOMEM;
4211
4212     ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
4213     if( !ret->p_sample_data )
4214         return VLC_ENOMEM;
4215
4216     uint32_t dur = 0, i_mdatlen = 0, len;
4217     uint32_t chunk_duration = 0, chunk_size = 0;
4218
4219     /* Skip header of mdat */
4220     uint8_t mdat[8];
4221     int i_read = stream_Read( p_demux->s, &mdat, 8 );
4222     i_mdatlen = GetDWBE( mdat );
4223     if ( i_read < 8 || i_mdatlen < 8 ||
4224          VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4225         return VLC_EGENERIC;
4226
4227     for( uint32_t i = 0; i < ret->i_sample_count; i++)
4228     {
4229         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
4230             dur = p_trun_data->p_samples[i].i_duration;
4231         else
4232             dur = default_duration;
4233         ret->p_sample_delta_dts[i] = dur;
4234         chunk_duration += dur;
4235
4236         ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
4237
4238         if( ret->p_sample_offset_pts )
4239         {
4240             if ( p_trun_data->i_version == 0 )
4241                 ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
4242             else
4243                 ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
4244         }
4245
4246         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
4247             len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
4248         else
4249             len = ret->p_sample_size[i] = default_size;
4250
4251         if ( chunk_size + len > ( i_mdatlen - 8 ) )
4252             return VLC_EGENERIC;
4253
4254         ret->p_sample_data[i] = malloc( len );
4255         if( ret->p_sample_data[i] == NULL )
4256             return VLC_ENOMEM;
4257         uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
4258         if( i_read < len )
4259             return VLC_EGENERIC;
4260         chunk_size += len;
4261     }
4262     ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
4263     p_track->i_first_dts = chunk_duration + ret->i_first_dts;
4264
4265     if( p_track->b_codec_need_restart &&
4266             p_track->fmt.i_cat == VIDEO_ES )
4267         ReInitDecoder( p_demux, p_track );
4268
4269     /* Skip if we didn't reach the end of mdat box */
4270     if ( chunk_size < (i_mdatlen - 8) )
4271         stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
4272
4273     p_track->b_has_non_empty_cchunk = true;
4274     return VLC_SUCCESS;
4275 }
4276
4277
4278 /**
4279  * Get the next chunk of the track identified by i_tk_id.
4280  * \Note We don't want to seek all the time, so if the first chunk given by the
4281  * input method doesn't belong to the right track, we don't throw it away,
4282  * and so, in general, this function fetch more than one chunk.
4283  * Not to mention that a new init fragment might be put everywhere
4284  * between two chunks by the input method.
4285  */
4286 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
4287 {
4288     demux_sys_t *p_sys = p_demux->p_sys;
4289     mp4_track_t *p_track;
4290
4291     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
4292     {
4293         MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4294         if( !p_chunk )
4295             return VLC_EGENERIC;
4296
4297         if( !p_chunk->p_first )
4298             goto MP4_frg_GetChunks_Error;
4299         uint32_t i_type = p_chunk->p_first->i_type;
4300         uint32_t tid = 0;
4301         if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
4302         {
4303             MP4_BoxFree( p_demux->s, p_sys->p_root );
4304             p_sys->p_root = p_chunk;
4305
4306             if( i_type == ATOM_ftyp ) /* DASH */
4307             {
4308                 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
4309                 if( !p_tkhd )
4310                 {
4311                     msg_Warn( p_demux, "No tkhd found!" );
4312                     goto MP4_frg_GetChunks_Error;
4313                 }
4314                 tid = p_tkhd->data.p_tkhd->i_track_ID;
4315             }
4316             else                      /* Smooth Streaming */
4317             {
4318                 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
4319                 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
4320                 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4321                 {
4322                     msg_Warn( p_demux, "No StraBox found!" );
4323                     goto MP4_frg_GetChunks_Error;
4324                 }
4325                 tid = p_stra->data.p_stra->i_track_ID;
4326             }
4327
4328             p_track = MP4_frg_GetTrackByID( p_demux, tid );
4329             if( !p_track )
4330                 goto MP4_frg_GetChunks_Error;
4331             p_track->b_codec_need_restart = true;
4332
4333             return MP4_frg_GetChunks( p_demux, i_tk_id );
4334         }
4335
4336         if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
4337             goto MP4_frg_GetChunks_Error;
4338
4339         MP4_BoxFree( p_demux->s, p_chunk );
4340
4341         if( tid == i_tk_id )
4342             break;
4343         else
4344             continue;
4345
4346 MP4_frg_GetChunks_Error:
4347         MP4_BoxFree( p_demux->s, p_chunk );
4348         return VLC_EGENERIC;
4349     }
4350
4351     return VLC_SUCCESS;
4352 }
4353
4354 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
4355 {
4356     if( !p_track->b_ok || p_track->b_chapter )
4357     {
4358         return VLC_EGENERIC;
4359     }
4360
4361     if( p_track->b_selected )
4362     {
4363         msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
4364         return VLC_SUCCESS;
4365     }
4366
4367     msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
4368     p_track->b_selected = true;
4369     return VLC_SUCCESS;
4370 }
4371
4372 /**
4373  * DemuxFrg: read packet and send them to decoders
4374  * \return 1 on success, 0 on error.
4375  * TODO check for newly selected track
4376  */
4377 int DemuxFrg( demux_t *p_demux )
4378 {
4379     demux_sys_t *p_sys = p_demux->p_sys;
4380     unsigned i_track;
4381     unsigned i_track_selected;
4382
4383     /* check for newly selected/unselected track */
4384     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
4385     {
4386         mp4_track_t *tk = &p_sys->track[i_track];
4387         bool b;
4388
4389         if( !tk->b_ok || tk->b_chapter )
4390             continue;
4391
4392         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
4393         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
4394
4395         if( tk->b_selected && !b )
4396         {
4397             MP4_TrackUnselect( p_demux, tk );
4398         }
4399         else if( !tk->b_selected && b)
4400         {
4401             MP4_frg_TrackSelect( p_demux, tk );
4402         }
4403
4404         if( tk->b_selected )
4405             i_track_selected++;
4406     }
4407
4408     if( i_track_selected <= 0 )
4409     {
4410         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
4411         if( p_sys->i_timescale > 0 )
4412         {
4413             int64_t i_length = CLOCK_FREQ *
4414                                (mtime_t)p_sys->moovfragment.i_duration /
4415                                (mtime_t)p_sys->i_timescale;
4416             if( MP4_GetMoviePTS( p_sys ) >= i_length )
4417                 return 0;
4418             return 1;
4419         }
4420
4421         msg_Warn( p_demux, "no track selected, exiting..." );
4422         return 0;
4423     }
4424
4425     /* first wait for the good time to read a packet */
4426     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4427
4428     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4429
4430     /* we will read 100ms for each stream so ...*/
4431     p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4432
4433     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4434     {
4435         mp4_track_t *tk = &p_sys->track[i_track];
4436
4437         if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4438         {
4439             msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4440             continue;
4441         }
4442
4443         if( !tk->b_has_non_empty_cchunk )
4444         {
4445             if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4446             {
4447                 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4448                 return 0;
4449             }
4450         }
4451
4452         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4453         {
4454             block_t *p_block;
4455             int64_t i_delta;
4456
4457             mp4_chunk_t *ck = tk->cchunk;
4458             if( ck->i_sample >= ck->i_sample_count )
4459             {
4460                 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4461                                     ck->i_sample, ck->i_sample_count );
4462                 return 0;
4463             }
4464
4465             uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4466             p_block = block_Alloc( sample_size );
4467             uint8_t *src = ck->p_sample_data[ck->i_sample];
4468             memcpy( p_block->p_buffer, src, sample_size );
4469
4470             ck->i_sample++;
4471             if( ck->i_sample == ck->i_sample_count )
4472                 tk->b_has_non_empty_cchunk = false;
4473
4474             /* dts */
4475             p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4476             /* pts */
4477             i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4478             if( i_delta != -1 )
4479                 p_block->i_pts = p_block->i_dts + i_delta;
4480             else if( tk->fmt.i_cat != VIDEO_ES )
4481                 p_block->i_pts = p_block->i_dts;
4482             else
4483                 p_block->i_pts = VLC_TS_INVALID;
4484
4485             MP4_Block_Send( p_demux, tk, p_block );
4486
4487             tk->i_sample++;
4488
4489             if( !tk->b_has_non_empty_cchunk )
4490                 break;
4491         }
4492     }
4493     return 1;
4494 }
4495
4496 static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
4497 {
4498     /* Read Next Chunk */
4499     MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4500     if( !p_chunk )
4501     {
4502         msg_Warn( p_demux, "no next chunk" );
4503         return NULL;
4504     }
4505
4506     if( !p_chunk->p_first )
4507     {
4508         msg_Warn( p_demux, "no next chunk child" );
4509         return NULL;
4510     }
4511
4512     return p_chunk;
4513 }
4514
4515 static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
4516 {
4517     while ( p_root )
4518     {
4519         if ( p_root->i_pos == i_pos )
4520         {
4521             assert( i_type == p_root->i_type );
4522             break;
4523         }
4524         p_root = p_root->p_next;
4525     }
4526     return (p_root != NULL);
4527 }
4528
4529 /* Keeps an ordered chain of all fragments */
4530 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
4531 {
4532     demux_sys_t *p_sys = p_demux->p_sys;
4533     mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
4534     if ( !p_moox )
4535         return false;
4536
4537     if( p_moox->i_type == ATOM_moov )
4538     {
4539         if ( !p_sys->moovfragment.p_moox )
4540         {
4541             p_sys->moovfragment.p_moox = p_moox;
4542             MP4_Box_t *p_mvhd;
4543             if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
4544             {
4545                 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
4546                 p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
4547             }
4548
4549             if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
4550             { /* duration might be wrong an be set to whole duration :/ */
4551                p_sys->moovfragment.i_duration = 0;
4552                MP4_Box_t *p_tkhd;
4553                MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
4554                while( p_trak )
4555                {
4556                    if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
4557                    {
4558                        if ( BOXDATA(p_tkhd)->i_duration > p_sys->moovfragment.i_duration )
4559                            p_sys->moovfragment.i_duration = BOXDATA(p_tkhd)->i_duration;
4560                    }
4561                    p_trak = p_trak->p_next;
4562                }
4563             }
4564
4565             msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4566             return true;
4567         }
4568         return false;
4569     }
4570     else // p_moox->i_type == ATOM_moof
4571     {
4572         assert(p_moox->i_type == ATOM_moof);
4573         mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
4574         while ( p_fragment )
4575         {
4576             if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
4577             {
4578                 p_base_fragment = p_fragment;
4579                 p_fragment = p_fragment->p_next;
4580             }
4581             else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
4582             {
4583                 /* already exists */
4584                 return false;
4585             }
4586         }
4587     }
4588
4589     /* Add the moof fragment */
4590     mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
4591     if ( !p_new ) return false;
4592     p_new->p_moox = p_moox;
4593     p_new->i_duration = 0;
4594     p_new->p_next = p_base_fragment->p_next;
4595     p_base_fragment->p_next = p_new;
4596     msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4597
4598     /* we have to probe all fragments :/ */
4599     uint64_t i_traf_base_data_offset = 0;
4600     uint64_t i_traf_min_offset = 0;
4601     uint32_t i_traf = 0;
4602     uint32_t i_traf_total_size = 0;
4603     uint32_t i_trafs_total_size = 0;
4604
4605     MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
4606     while ( p_traf )
4607     {
4608         if ( p_traf->i_type != ATOM_traf )
4609         {
4610            p_traf = p_traf->p_next;
4611            continue;
4612         }
4613         const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4614         const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4615         if ( !p_tfhd || !p_trun )
4616         {
4617            p_traf = p_traf->p_next;
4618            continue;
4619         }
4620
4621         uint32_t i_track_timescale = 0;
4622         uint32_t i_track_defaultsamplesize = 0;
4623         uint32_t i_track_defaultsampleduration = 0;
4624         if ( p_sys->b_smooth )
4625         {
4626             /* stra sets identical timescales */
4627             i_track_timescale = p_sys->i_timescale;
4628             i_track_defaultsamplesize = 1;
4629             i_track_defaultsampleduration = 1;
4630         }
4631         else
4632         {
4633             /* set trex for defaults */
4634              MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4635              if ( p_trex )
4636              {
4637                 i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
4638                 i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4639              }
4640
4641              MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4642              if ( p_trak )
4643              {
4644                 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4645                 if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4646              }
4647         }
4648
4649         if ( !i_track_timescale )
4650         {
4651            p_traf = p_traf->p_next;
4652            continue;
4653         }
4654
4655         if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4656         {
4657             i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
4658         }
4659         else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4660         {
4661             i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
4662         }
4663         else
4664         {
4665             if ( i_traf == 0 )
4666                 i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
4667             else
4668                 i_traf_base_data_offset += i_traf_total_size;
4669         }
4670
4671         i_traf_total_size = 0;
4672
4673         uint64_t i_trun_data_offset = i_traf_base_data_offset;
4674         uint64_t i_traf_duration = 0;
4675         uint32_t i_trun_size = 0;
4676         while ( p_trun && p_tfhd )
4677         {
4678             if ( p_trun->i_type != ATOM_trun )
4679             {
4680                p_trun = p_trun->p_next;
4681                continue;
4682             }
4683             const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4684
4685             /* Get data offset */
4686             if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
4687                 i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
4688             else
4689                 i_trun_data_offset += i_trun_size;
4690
4691             i_trun_size = 0;
4692
4693             /* Sum total time */
4694             if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4695             {
4696                 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4697                     i_traf_duration += p_trundata->p_samples[i].i_duration;
4698             }
4699             else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4700             {
4701                 i_traf_duration += p_trundata->i_sample_count *
4702                         BOXDATA(p_tfhd)->i_default_sample_duration;
4703             }
4704             else
4705             {
4706                 i_traf_duration += p_trundata->i_sample_count *
4707                         i_track_defaultsampleduration;
4708             }
4709
4710             /* Get total traf size */
4711             if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
4712             {
4713                 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4714                     i_trun_size += p_trundata->p_samples[i].i_size;
4715             }
4716             else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4717             {
4718                 i_trun_size += p_trundata->i_sample_count *
4719                         BOXDATA(p_tfhd)->i_default_sample_size;
4720             }
4721             else
4722             {
4723                 i_trun_size += p_trundata->i_sample_count *
4724                         i_track_defaultsamplesize;
4725             }
4726
4727             i_traf_total_size += i_trun_size;
4728
4729             if ( i_traf_min_offset )
4730                 i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
4731             else
4732                 i_traf_min_offset = i_trun_data_offset;
4733
4734             p_trun = p_trun->p_next;
4735         }
4736
4737         i_trafs_total_size += i_traf_total_size;
4738         p_new->i_duration = __MAX( p_new->i_duration, i_traf_duration * p_sys->i_timescale / i_track_timescale );
4739
4740         p_traf = p_traf->p_next;
4741         i_traf++;
4742     }
4743
4744     p_new->i_chunk_range_min_offset = i_traf_min_offset;
4745     p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
4746
4747     msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
4748
4749     /* compute total duration with that new fragment if no overall provided */
4750     MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
4751     if ( !p_mehd )
4752     {
4753         p_sys->i_overall_duration = 0;
4754         if ( p_sys->b_fragments_probed )
4755         {
4756             p_new = &p_sys->moovfragment;
4757             while ( p_new )
4758             {
4759                 p_sys->i_overall_duration += p_new->i_duration;
4760                 p_new = p_new->p_next;
4761             }
4762         }
4763     }
4764     else
4765         p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
4766
4767     msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale);
4768     return true;
4769 }
4770
4771 static int ProbeIndex( demux_t *p_demux )
4772 {
4773     demux_sys_t *p_sys = p_demux->p_sys;
4774     uint64_t i_backup_pos, i_stream_size;
4775     uint8_t mfro[MP4_MFRO_BOXSIZE];
4776     assert( p_sys->b_seekable );
4777
4778     if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4779         return VLC_SUCCESS;
4780
4781     i_stream_size = stream_Size( p_demux->s );
4782     if ( ( i_stream_size >> 62 ) ||
4783          ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
4784          ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
4785          ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4786        )
4787     {
4788         msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4789         return VLC_EGENERIC;
4790     }
4791
4792     if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4793          VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4794          GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4795     {
4796         uint32_t i_offset = GetDWBE( &mfro[12] );
4797         msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4798         if ( i_stream_size > i_offset &&
4799              stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4800         {
4801             msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4802             MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
4803         }
4804     }
4805
4806     return stream_Seek( p_demux->s, i_backup_pos );
4807 }
4808
4809 static int ProbeFragments( demux_t *p_demux, bool b_force )
4810 {
4811     demux_sys_t *p_sys = p_demux->p_sys;
4812     uint64_t i_current_pos;
4813
4814     if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4815         msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
4816
4817     assert( p_sys->p_root );
4818
4819     if ( p_sys->b_fastseekable || b_force )
4820     {
4821         MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
4822         p_sys->b_fragments_probed = true;
4823     }
4824     else
4825     {
4826         /* We stop at first moof, which validates our fragmentation condition
4827          * and we'll find others while reading. */
4828         MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
4829     }
4830
4831     if ( !p_sys->moovfragment.p_moox )
4832     {
4833         MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
4834         if ( !p_moov )
4835         {
4836             /* moov/mvex before probing should be present anyway */
4837             MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
4838             return VLC_EGENERIC;
4839         }
4840         AddFragment( p_demux, p_moov );
4841     }
4842
4843     MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
4844     while ( p_moof )
4845     {
4846         if ( p_moof->i_type == ATOM_moof )
4847             AddFragment( p_demux, p_moof );
4848         p_moof = p_moof->p_next;
4849     }
4850
4851     MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
4852     if ( p_mdat )
4853     {
4854         stream_Seek( p_demux->s, p_mdat->i_pos );
4855         msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
4856     }
4857
4858     return VLC_SUCCESS;
4859 }
4860
4861 static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
4862 {
4863     mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4864     while ( p_fragment )
4865     {
4866         if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
4867              ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
4868         {
4869             msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
4870                      p_fragment->i_chunk_range_min_offset, i_pos,
4871                      p_fragment->i_chunk_range_max_offset );
4872             return p_fragment;
4873         }
4874         else
4875         {
4876             p_fragment = p_fragment->p_next;
4877         }
4878     }
4879     return NULL;
4880 }
4881
4882 /* Get a matching fragment data start by clock time */
4883 static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
4884 {
4885     mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4886     mtime_t i_base_time = 0;
4887     while ( p_fragment )
4888     {
4889         mtime_t i_length = CLOCK_FREQ * p_fragment->i_duration / p_demux->p_sys->i_timescale;
4890         if ( i_time >= i_base_time &&
4891              i_time <= i_base_time + i_length )
4892         {
4893             return p_fragment;
4894         }
4895         else
4896         {
4897             i_base_time += i_length;
4898             p_fragment = p_fragment->p_next;
4899         }
4900
4901         if ( !p_demux->p_sys->b_fragments_probed )
4902             return NULL; /* We have no way to guess missing fragments time */
4903     }
4904     return NULL;
4905 }
4906
4907 /* Returns fragment scaled time offset */
4908 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment )
4909 {
4910     mtime_t i_base_scaledtime = 0;
4911     mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
4912     while ( p_current != p_fragment )
4913     {
4914         i_base_scaledtime += p_current->i_duration;
4915         p_current = p_current->p_next;
4916     }
4917     return i_base_scaledtime;
4918 }
4919
4920 static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
4921                       const uint32_t i_defaultduration, const uint32_t i_defaultsize,
4922                       const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
4923 {
4924     assert( p_trun->i_sample_count );
4925     msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
4926              i_defaultduration, i_defaultsize, p_track->i_first_dts );
4927
4928     uint32_t dur = 0, len;
4929     uint32_t chunk_size = 0;
4930     mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
4931
4932     mtime_t i_nzpts;
4933
4934     for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
4935     {
4936         i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
4937         i_nzpts = i_nzdts;
4938
4939         if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4940             dur = p_trun->p_samples[i].i_duration;
4941         else
4942             dur = i_defaultduration;
4943
4944         p_track->i_time += dur;
4945
4946         if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4947         {
4948             if ( p_trun->i_version == 0 )
4949                 i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4950             else
4951                 i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4952         }
4953
4954         if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
4955             len = p_trun->p_samples[i].i_size;
4956         else
4957             len = i_defaultsize;
4958
4959         assert( dur ); /* dur, dur ! */
4960         assert( len );
4961
4962         if ( chunk_size + len > *pi_mdatlen )
4963         {
4964             /* update data left in mdat */
4965             *pi_mdatlen -= chunk_size;
4966             return VLC_EGENERIC;
4967         }
4968
4969         block_t *p_block = MP4_Block_Read( p_demux, p_track, __MIN( len, INT32_MAX ) );
4970         uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
4971         if( i_read < len )
4972         {
4973             /* update data left in mdat */
4974             *pi_mdatlen -= chunk_size;
4975             *pi_mdatlen -= i_read;
4976             free( p_block );
4977             return VLC_EGENERIC;
4978         }
4979
4980         if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4981         {
4982             p_demux->p_sys->i_pcr = i_nzdts;
4983             es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
4984         }
4985
4986         if ( p_track->p_es )
4987         {
4988             p_block->i_dts = VLC_TS_0 + i_nzdts;
4989             p_block->i_pts = VLC_TS_0 + i_nzpts;
4990             p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
4991             MP4_Block_Send( p_demux, p_track, p_block );
4992         }
4993         else free( p_block );
4994
4995         chunk_size += len;
4996     }
4997
4998     /* update data left in mdat */
4999     *pi_mdatlen -= chunk_size;
5000     return VLC_SUCCESS;
5001 }
5002
5003 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
5004                                       mp4_track_t **pp_tk, unsigned int *pi_chunk )
5005 {
5006     const demux_sys_t *p_sys = p_demux->p_sys;
5007
5008     mp4_track_t *p_tk_closest = NULL;
5009     uint64_t i_closest = UINT64_MAX;
5010     unsigned int i_chunk_closest;
5011
5012     *pp_tk = NULL;
5013
5014     for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5015     {
5016         for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
5017         {
5018             if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
5019             {
5020                 i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
5021                 p_tk_closest = &p_sys->track[i_track];
5022                 i_chunk_closest = i_chunk;
5023             }
5024
5025             if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
5026             {
5027                 *pp_tk = &p_sys->track[i_track];
5028                 *pi_chunk = i_chunk;
5029                 return VLC_SUCCESS;
5030             }
5031         }
5032     }
5033
5034     if ( i_closest != UINT64_MAX )
5035     {
5036         *pi_pos = i_closest;
5037         *pp_tk = p_tk_closest;
5038         *pi_chunk = i_chunk_closest;
5039         return VLC_ENOOBJ;
5040     }
5041     else return VLC_EGENERIC;
5042 }
5043
5044 static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
5045                            uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
5046                            const uint32_t i_maxbytes, const uint32_t i_maxsamples )
5047 {
5048     MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
5049     if ( !p_stsz )
5050         return VLC_EGENERIC;
5051
5052     if ( BOXDATA(p_stsz)->i_sample_size == 0 )
5053     {
5054         uint32_t i_entry = i_sample;
5055         uint32_t i_totalbytes = 0;
5056         *pi_samplestoread = 1;
5057
5058         if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
5059             return VLC_EGENERIC;
5060
5061         *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
5062         i_totalbytes += *pi_samplessize;
5063
5064         if ( *pi_samplessize > i_maxbytes )
5065             return VLC_EGENERIC;
5066
5067         i_entry++;
5068         while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
5069                *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
5070                i_totalbytes + *pi_samplessize < i_maxbytes &&
5071                *pi_samplestoread < i_maxsamples
5072               )
5073         {
5074             i_totalbytes += *pi_samplessize;
5075             (*pi_samplestoread)++;
5076         }
5077
5078         *pi_samplessize = i_totalbytes;
5079     }
5080     else
5081     {
5082         /* all samples have same size */
5083         *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
5084         *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
5085         *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
5086         *pi_samplessize = *pi_samplessize * *pi_samplestoread;
5087     }
5088
5089     return VLC_SUCCESS;
5090 }
5091
5092 static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
5093 {
5094     mtime_t i_time = 0;
5095     uint32_t i_index = 0;
5096
5097     while( i_sample > 0 )
5098     {
5099         if( i_sample > p_chunk->p_sample_count_dts[i_index] )
5100         {
5101             i_time += p_chunk->p_sample_count_dts[i_index] *
5102                 p_chunk->p_sample_delta_dts[i_index];
5103             i_sample -= p_chunk->p_sample_count_dts[i_index];
5104             i_index++;
5105         }
5106         else
5107         {
5108             i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
5109             break;
5110         }
5111     }
5112
5113     return i_time;
5114 }
5115
5116 static int LeafParseMDATwithMOOV( demux_t *p_demux )
5117 {
5118     demux_sys_t *p_sys = p_demux->p_sys;
5119
5120     assert( p_sys->context.i_current_box_type == ATOM_mdat );
5121     assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
5122
5123     uint64_t i_current_pos;
5124     if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
5125         return VLC_EGENERIC;
5126
5127     if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
5128     {
5129         /* Ready mdat section */
5130         uint8_t mdat[8];
5131         int i_read = stream_Read( p_demux->s, &mdat, 8 );
5132         p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5133         if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5134              VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5135         {
5136             uint64_t i_pos;
5137             if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5138                 msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
5139             return VLC_EGENERIC;
5140         }
5141         i_current_pos += 8;
5142         p_sys->context.i_mdatbytesleft -= 8;
5143     }
5144
5145     while( p_sys->context.i_mdatbytesleft > 0 )
5146     {
5147         mp4_track_t *p_track;
5148         unsigned int i_chunk;
5149
5150         /**/
5151         uint64_t i_pos = i_current_pos;
5152         int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
5153         if ( i_ret == VLC_EGENERIC )
5154         {
5155             msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
5156             goto error;
5157         }
5158         else if( i_ret == VLC_ENOOBJ )
5159         {
5160             assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
5161             int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
5162             i_current_pos += i_read;
5163             p_sys->context.i_mdatbytesleft -= i_read;
5164             if ( i_read == 0 ) goto error;
5165             continue;
5166         }
5167         /**/
5168
5169         mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
5170
5171         uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
5172         uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
5173
5174         assert(i_nb_samples_in_chunk);
5175
5176         uint32_t i_nb_samples = 0;
5177         while ( i_nb_samples < i_nb_samples_in_chunk )
5178         {
5179             uint32_t i_samplessize = 0;
5180             uint32_t i_samplescounttoread = 0;
5181             i_ret = LeafMOOVGetSamplesSize( p_track,
5182                             i_nb_samples_at_chunk_start + i_nb_samples,
5183                             &i_samplescounttoread, &i_samplessize,
5184                             p_sys->context.i_mdatbytesleft,
5185                             /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
5186             if ( i_ret != VLC_SUCCESS )
5187                 goto error;
5188
5189             if( p_sys->context.i_mdatbytesleft &&
5190                 p_sys->context.i_mdatbytesleft  >= i_samplessize )
5191             {
5192                 block_t *p_block;
5193
5194                 /* now read pes */
5195
5196                 if( !(p_block = MP4_Block_Read( p_demux, p_track, i_samplessize )) )
5197                 {
5198                     uint64_t i_pos;
5199                     if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5200                     {
5201                         p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
5202                         msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
5203                     }
5204                     goto error;
5205                 }
5206
5207                 i_nb_samples += i_samplescounttoread;
5208                 i_current_pos += i_samplessize;
5209                 p_sys->context.i_mdatbytesleft -= i_samplessize;
5210
5211                 /* dts */
5212                 mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
5213                 i_time += p_chunk->i_first_dts;
5214                 p_track->i_time = i_time;
5215                 p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
5216
5217                 /* pts */
5218                 int64_t i_delta = MP4_TrackGetPTSDelta( p_demux, p_track );
5219                 if( i_delta != -1 )
5220                     p_block->i_pts = p_block->i_dts + i_delta;
5221                 else if( p_track->fmt.i_cat != VIDEO_ES )
5222                     p_block->i_pts = p_block->i_dts;
5223                 else
5224                     p_block->i_pts = VLC_TS_INVALID;
5225
5226                 MP4_Block_Send( p_demux, p_track, p_block );
5227
5228                 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
5229                 {
5230                     p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
5231                     p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
5232                     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
5233                 }
5234
5235             }
5236             else
5237             {
5238                 // sample size > left bytes
5239                 break;
5240             }
5241
5242             p_track->i_sample += i_samplescounttoread;
5243         }
5244
5245         /* flag end of mdat section if needed */
5246         if ( p_sys->context.i_mdatbytesleft == 0 )
5247             p_sys->context.i_current_box_type = 0;
5248
5249         // next chunk
5250         return VLC_SUCCESS;
5251     }
5252
5253 error:
5254     /* Skip if we didn't reach the end of mdat box */
5255     if ( p_sys->context.i_mdatbytesleft  > 0 )
5256     {
5257         msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
5258                  p_sys->context.i_mdatbytesleft );
5259         stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5260     }
5261     p_sys->context.i_current_box_type = 0;
5262
5263     return VLC_SUCCESS;
5264 }
5265
5266 static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
5267 {
5268     demux_sys_t *p_sys = p_demux->p_sys;
5269
5270     for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5271     {
5272         mp4_track_t *p_track = &p_sys->track[i];
5273         if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
5274             continue;
5275         const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5276         uint64_t i_offset = 0;
5277
5278         if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
5279             i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
5280         else
5281             i_offset = i_moofpos;
5282
5283         //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5284           //  i_offset += i_moofpos;
5285
5286         if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
5287             i_offset += p_trun_data->i_data_offset;
5288         else
5289             return p_track;
5290
5291         if ( i_offset == i_pos )
5292             return p_track;
5293     }
5294
5295     return NULL;
5296 }
5297
5298 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
5299 {
5300     demux_sys_t *p_sys = p_demux->p_sys;
5301
5302     /* reset */
5303     for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5304     {
5305         mp4_track_t *p_track = &p_sys->track[i];
5306         p_track->context.p_tfhd = NULL;
5307         p_track->context.p_traf = NULL;
5308         p_track->context.p_trun = NULL;
5309     }
5310
5311     if ( p_moof->i_type == ATOM_moov )
5312         return VLC_SUCCESS;
5313
5314     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
5315     if( !p_traf )
5316     {
5317         msg_Warn( p_demux, "no traf box found!" );
5318         return VLC_EGENERIC;
5319     }
5320
5321     /* map contexts */
5322     while ( p_traf )
5323     {
5324         if ( p_traf->i_type == ATOM_traf )
5325         {
5326             MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
5327             for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
5328             {
5329                 mp4_track_t *p_track = &p_sys->track[i];
5330                 if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
5331                 {
5332                     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
5333                     if ( p_trun )
5334                     {
5335                         p_track->context.p_tfhd = p_tfhd;
5336                         p_track->context.p_traf = p_traf;
5337                         p_track->context.p_trun = p_trun;
5338                     }
5339                     p_tfhd = NULL; /* break loop */
5340                 }
5341             }
5342         }
5343         p_traf = p_traf->p_next;
5344     }
5345
5346     return VLC_SUCCESS;
5347 }
5348
5349 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
5350                                       uint64_t *pi_pos, mtime_t *pi_mooftime )
5351 {
5352     MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
5353     while ( p_tfra )
5354     {
5355         if ( p_tfra->i_type == ATOM_tfra )
5356         {
5357             int64_t i_pos = -1;
5358             const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
5359             mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
5360             if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
5361             {
5362                 for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
5363                 {
5364                     mtime_t i_time;
5365                     uint64_t i_offset;
5366                     if ( p_data->i_version == 1 )
5367                     {
5368                         i_time = *((uint64_t *)(p_data->p_time + i));
5369                         i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
5370                     }
5371                     else
5372                     {
5373                         i_time = p_data->p_time[i];
5374                         i_offset = p_data->p_moof_offset[i];
5375                     }
5376
5377                     if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
5378                     {
5379                         if ( i_pos == -1 ) /* Not in this traf */
5380                             break;
5381
5382                         *pi_pos = (uint64_t) i_pos;
5383                         *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
5384                         if ( p_track->fmt.i_cat == AUDIO_ES )
5385                             *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
5386                         else
5387                             *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
5388                         return VLC_SUCCESS;
5389                     }
5390                     else
5391                         i_pos = i_offset;
5392                 }
5393             }
5394         }
5395         p_tfra = p_tfra->p_next;
5396     }
5397     return VLC_EGENERIC;
5398 }
5399
5400 static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
5401 {
5402     demux_sys_t *p_sys = p_demux->p_sys;
5403     uint64_t i_pos;
5404     assert( p_moof->i_type == ATOM_moof );
5405     assert( p_sys->context.i_current_box_type == ATOM_mdat );
5406
5407     if ( p_sys->context.i_mdatbytesleft == 0 )
5408     {
5409         int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
5410         if ( i_ret != VLC_SUCCESS )
5411             return i_ret;
5412
5413         /* Ready mdat section */
5414         uint8_t mdat[8];
5415         int i_read = stream_Read( p_demux->s, &mdat, 8 );
5416         p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5417         if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5418              VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5419         {
5420             if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5421                 msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
5422             return VLC_EGENERIC;
5423         }
5424         p_sys->context.i_mdatbytesleft -= 8;
5425     }
5426
5427     if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5428         return VLC_EGENERIC;
5429     if ( p_sys->b_smooth )
5430         i_pos -= p_moof->i_pos;
5431     mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
5432     if( p_track )
5433     {
5434         MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
5435         uint32_t i_trun_sample_default_duration = 0;
5436         uint32_t i_trun_sample_default_size = 0;
5437
5438         if ( p_track->context.p_trun )
5439         {
5440             /* Get defaults for this/these RUN */
5441             if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
5442                 i_trun_sample_default_duration = p_tfhd_data->i_default_sample_duration;
5443
5444             if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
5445                 i_trun_sample_default_size = p_tfhd_data->i_default_sample_size;
5446
5447             if( !i_trun_sample_default_duration || !i_trun_sample_default_size )
5448             {
5449                 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
5450                 if ( p_trex )
5451                 {
5452                     while( p_trex && BOXDATA(p_trex)->i_track_ID != p_tfhd_data->i_track_ID )
5453                         p_trex = p_trex->p_next;
5454                     if ( p_trex && !i_trun_sample_default_duration )
5455                         i_trun_sample_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
5456                     if ( p_trex && !i_trun_sample_default_size )
5457                         i_trun_sample_default_size = BOXDATA(p_trex)->i_default_sample_size;
5458                 }
5459             }
5460
5461             const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5462
5463            /* NOW PARSE TRUN WITH MDAT */
5464             int i_ret = LeafParseTRUN( p_demux, p_track,
5465                                    i_trun_sample_default_duration, i_trun_sample_default_size,
5466                                    p_trun_data, & p_sys->context.i_mdatbytesleft );
5467             if ( i_ret != VLC_SUCCESS )
5468                 goto end;
5469
5470             p_track->context.p_trun = p_track->context.p_trun->p_next;
5471         }
5472
5473         if ( p_sys->context.i_mdatbytesleft == 0 )
5474             p_sys->context.i_current_box_type = 0;
5475         return VLC_SUCCESS;
5476     }
5477
5478 end:
5479     /* Skip if we didn't reach the end of mdat box */
5480     if ( p_sys->context.i_mdatbytesleft > 0 )
5481     {
5482         msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
5483         stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5484     }
5485
5486     p_sys->context.i_current_box_type = 0;
5487
5488     return VLC_SUCCESS;
5489 }
5490
5491 static int DemuxAsLeaf( demux_t *p_demux )
5492 {
5493     demux_sys_t *p_sys = p_demux->p_sys;
5494     unsigned i_track_selected = 0;
5495
5496     /* check for newly selected/unselected track */
5497     for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5498     {
5499         mp4_track_t *tk = &p_sys->track[i_track];
5500         bool b;
5501
5502         if( !tk->b_ok || tk->b_chapter )
5503             continue;
5504
5505         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5506         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5507
5508         if( tk->b_selected && !b )
5509             MP4_TrackUnselect( p_demux, tk );
5510         else if( !tk->b_selected && b)
5511             MP4_frg_TrackSelect( p_demux, tk );
5512
5513         if( tk->b_selected )
5514             i_track_selected++;
5515     }
5516
5517     if( i_track_selected <= 0 )
5518     {
5519         msg_Warn( p_demux, "no track selected, exiting..." );
5520         return 0;
5521     }
5522
5523     if ( p_sys->context.i_current_box_type != ATOM_mdat )
5524     {
5525         /* Othewise mdat is skipped. FIXME: mdat reading ! */
5526         const uint8_t *p_peek;
5527         int i_read  = stream_Peek( p_demux->s, &p_peek, 8 );
5528         if ( i_read < 8 )
5529             return 0;
5530
5531         p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5532
5533         if ( p_sys->context.i_current_box_type != ATOM_mdat )
5534         {
5535             if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
5536             {// only if !b_probed ??
5537                 MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
5538                 switch( p_sys->context.i_current_box_type )
5539                 {
5540                 case ATOM_moov:
5541                 case ATOM_moof:
5542                     /* create fragment */
5543                     AddFragment( p_demux, p_vroot->p_first );
5544                     //ft
5545                 default:
5546                     break;
5547                 }
5548
5549                 /* Append to root */
5550                 p_sys->p_root->p_last->p_next = p_vroot->p_first;
5551                 p_sys->p_root->p_last = p_vroot->p_first;
5552                 p_vroot->p_last = NULL;
5553                 p_vroot->p_next = NULL;
5554                 p_vroot->p_first = NULL;
5555                 MP4_BoxFree( p_demux->s, p_vroot );
5556             }
5557             else
5558             {
5559                 /* Skip */
5560                 msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
5561                 stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
5562             }
5563         }
5564         else
5565         {
5566             /* skip mdat header */
5567             p_sys->context.p_fragment = GetFragmentByPos( p_demux,
5568                                        stream_Tell( p_demux->s ) + 8, true );
5569         }
5570
5571     }
5572
5573     if ( p_sys->context.i_current_box_type == ATOM_mdat )
5574     {
5575         assert(p_sys->context.p_fragment);
5576         if ( p_sys->context.p_fragment )
5577         switch( p_sys->context.p_fragment->p_moox->i_type )
5578         {
5579             case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5580                 LeafParseMDATwithMOOV( p_demux );
5581             break;
5582             case ATOM_moof:
5583                 LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
5584             break;
5585         default:
5586              msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
5587              break;
5588         }
5589     }
5590
5591     /* Get current time */
5592     mtime_t i_lowest_dts = VLC_TS_INVALID;
5593     mtime_t i_lowest_time = INT64_MAX;
5594     for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5595     {
5596         const mp4_track_t *p_track = &p_sys->track[i_track];
5597         if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
5598             continue;
5599
5600         i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
5601
5602         if ( i_lowest_dts == VLC_TS_INVALID )
5603             i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
5604         else
5605             i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
5606     }
5607
5608     p_sys->i_time = i_lowest_time;
5609     p_sys->i_pcr = i_lowest_dts;
5610     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
5611
5612     return 1;
5613 }
5614
5615 #undef BOXDATA