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