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