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