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