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