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