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