]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
Add HEVC support in MP4
[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 <vlc_common.h>
32 #include <vlc_plugin.h>
33
34 #include <vlc_demux.h>
35 #include <vlc_charset.h>                           /* EnsureUTF8 */
36 #include <vlc_meta.h>                              /* vlc_meta_t, vlc_meta_ */
37 #include <vlc_input.h>
38 #include <assert.h>
39
40 #include "libmp4.h"
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   Seek    ( demux_t *, mtime_t );
65 static int   Control ( demux_t *, int, va_list );
66
67 struct demux_sys_t
68 {
69     MP4_Box_t    *p_root;      /* container for the whole file */
70
71     mtime_t      i_pcr;
72
73     uint64_t     i_time;         /* time position of the presentation
74                                   * in movie timescale */
75     uint64_t     i_timescale;    /* movie time scale */
76     uint64_t     i_duration;     /* movie duration */
77     unsigned int i_tracks;       /* number of tracks */
78     mp4_track_t  *track;         /* array of track */
79     float        f_fps;          /* number of frame per seconds */
80
81     bool         b_fragmented;   /* fMP4 */
82
83     /* */
84     MP4_Box_t    *p_tref_chap;
85
86     /* */
87     input_title_t *p_title;
88 };
89
90 /*****************************************************************************
91  * Declaration of local function
92  *****************************************************************************/
93 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_force_enable );
94 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
95 static void MP4_TrackDestroy(  mp4_track_t * );
96
97 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
98 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
99
100 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
101
102 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
103 static int      MP4_TrackSampleSize( mp4_track_t * );
104 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
105 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
106
107 static void     MP4_UpdateSeekpoint( demux_t * );
108 static const char *MP4_ConvertMacCode( uint16_t );
109
110 /* Return time in microsecond of a track */
111 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
112 {
113     demux_sys_t *p_sys = p_demux->p_sys;
114     mp4_chunk_t chunk;
115     if( p_sys->b_fragmented )
116         chunk = *p_track->cchunk;
117     else
118         chunk = p_track->chunk[p_track->i_chunk];
119
120     unsigned int i_index = 0;
121     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
122     int64_t i_dts = chunk.i_first_dts;
123
124     while( i_sample > 0 )
125     {
126         if( i_sample > chunk.p_sample_count_dts[i_index] )
127         {
128             i_dts += chunk.p_sample_count_dts[i_index] *
129                 chunk.p_sample_delta_dts[i_index];
130             i_sample -= chunk.p_sample_count_dts[i_index];
131             i_index++;
132         }
133         else
134         {
135             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
136             break;
137         }
138     }
139
140     /* now handle elst */
141     if( p_track->p_elst )
142     {
143         demux_sys_t         *p_sys = p_demux->p_sys;
144         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
145
146         /* convert to offset */
147         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
148               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
149             elst->i_media_time[p_track->i_elst] > 0 )
150         {
151             i_dts -= elst->i_media_time[p_track->i_elst];
152         }
153
154         /* add i_elst_time */
155         i_dts += p_track->i_elst_time * p_track->i_timescale /
156             p_sys->i_timescale;
157
158         if( i_dts < 0 ) i_dts = 0;
159     }
160
161     return INT64_C(1000000) * i_dts / p_track->i_timescale;
162 }
163
164 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
165 {
166     demux_sys_t *p_sys = p_demux->p_sys;
167     mp4_chunk_t *ck;
168     if( p_sys->b_fragmented )
169         ck = p_track->cchunk;
170     else
171         ck = &p_track->chunk[p_track->i_chunk];
172
173     unsigned int i_index = 0;
174     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
175
176     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
177         return -1;
178
179     for( i_index = 0;; i_index++ )
180     {
181         if( i_sample < ck->p_sample_count_pts[i_index] )
182             return ck->p_sample_offset_pts[i_index] * INT64_C(1000000) /
183                    (int64_t)p_track->i_timescale;
184
185         i_sample -= ck->p_sample_count_pts[i_index];
186     }
187 }
188
189 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
190 {
191     return INT64_C(1000000) * p_sys->i_time / p_sys->i_timescale;
192 }
193
194 static void LoadChapter( demux_t  *p_demux );
195
196 static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
197 {
198     demux_sys_t *p_sys = p_demux->p_sys;
199
200     if( b_smooth ) /* Smooth Streaming */
201     {
202         if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
203         {
204             goto LoadInitFragError;
205         }
206         else
207         {
208             MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
209             if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
210                 goto LoadInitFragError;
211             /* Get number of tracks */
212             p_sys->i_tracks = 0;
213             for( int i = 0; i < 3; i++ )
214             {
215                 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
216                 if( p_stra && p_stra->data.p_stra->i_track_ID )
217                     p_sys->i_tracks++;
218                 /* Get timescale and duration of the video track; */
219                 if( p_sys->i_timescale == 0 )
220                 {
221                     p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
222                     p_sys->i_duration = p_stra->data.p_stra->i_duration;
223                     if( p_sys->i_timescale == 0 )
224                     {
225                         msg_Err( p_demux, "bad timescale" );
226                         goto LoadInitFragError;
227                     }
228                 }
229             }
230         }
231     }
232     else
233     {
234         /* Load all boxes ( except raw data ) */
235         if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
236         {
237             goto LoadInitFragError;
238         }
239     }
240     return VLC_SUCCESS;
241
242 LoadInitFragError:
243     msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
244     return VLC_EGENERIC;
245 }
246
247 static int InitTracks( demux_t *p_demux )
248 {
249     demux_sys_t *p_sys = p_demux->p_sys;
250
251     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
252     if( p_sys->track == NULL )
253         return VLC_EGENERIC;
254
255     if( p_sys->b_fragmented )
256     {
257         mp4_track_t *p_track;
258         for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
259         {
260             p_track = &p_sys->track[i];
261             p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
262             if( unlikely( !p_track->cchunk ) )
263             {
264                 free( p_sys->track );
265                 return VLC_EGENERIC;
266             }
267         }
268     }
269     return VLC_SUCCESS;
270 }
271
272 static void CreateTracksFromSmooBox( demux_t *p_demux )
273 {
274     demux_sys_t *p_sys = p_demux->p_sys;
275
276     MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
277     mp4_track_t *p_track;
278     int j = 0;
279     for( int i = 0; i < 3; i++ )
280     {
281         MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
282         if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
283             continue;
284         else
285         {
286             p_track = &p_sys->track[j]; j++;
287             MP4_frg_TrackCreate( p_demux, p_track, p_stra );
288             p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
289         }
290     }
291 }
292
293 /*****************************************************************************
294  * Open: check file and initializes MP4 structures
295  *****************************************************************************/
296 static int Open( vlc_object_t * p_this )
297 {
298     demux_t  *p_demux = (demux_t *)p_this;
299     demux_sys_t     *p_sys;
300
301     const uint8_t   *p_peek;
302
303     MP4_Box_t       *p_ftyp;
304     MP4_Box_t       *p_rmra;
305     MP4_Box_t       *p_mvhd;
306     MP4_Box_t       *p_trak;
307
308     unsigned int    i;
309     bool      b_seekable;
310     bool      b_enabled_es;
311
312     /* A little test to see if it could be a mp4 */
313     if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
314
315     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
316     {
317         case ATOM_moov:
318         case ATOM_foov:
319         case ATOM_moof:
320         case ATOM_mdat:
321         case ATOM_udta:
322         case ATOM_free:
323         case ATOM_skip:
324         case ATOM_wide:
325         case ATOM_uuid:
326         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
327             break;
328         case ATOM_ftyp:
329             /* We don't yet support f4v, but avformat does. */
330             if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
331                 return VLC_EGENERIC;
332             break;
333          default:
334             return VLC_EGENERIC;
335     }
336
337     /* I need to seek */
338     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
339     if( !b_seekable )
340     {
341         msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
342         return VLC_EGENERIC;
343     }
344
345     /*Set exported functions */
346     p_demux->pf_demux = Demux;
347     p_demux->pf_control = Control;
348
349     /* create our structure that will contains all data */
350     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
351
352     /* Is it Smooth Streaming? */
353     bool b_smooth = false;
354     if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
355     if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
356     {
357         b_smooth = true;
358         p_sys->b_fragmented = true;
359     }
360
361     if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
362         goto error;
363
364     if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
365     {
366         p_sys->b_fragmented = true;
367     }
368     if( p_sys->b_fragmented )
369     {
370         p_demux->pf_demux = DemuxFrg;
371     }
372
373     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
374     if( b_smooth )
375     {
376         if( InitTracks( p_demux ) != VLC_SUCCESS )
377             goto error;
378         CreateTracksFromSmooBox( p_demux );
379         return VLC_SUCCESS;
380     }
381     else if( p_sys->b_fragmented && b_seekable )
382     {
383         /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
384          * box. So if STREAM_CAN_FASTSEEK is true, we're assuming we've got such
385          * a file, and we let avformat do the job. */
386         msg_Warn( p_demux, "MP4 plugin discarded "\
387                 "(fast-seekable and fragmented, let avformat demux it)" );
388         stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
389         goto error;
390     }
391     else if( !p_sys->b_fragmented && !b_seekable )
392     {
393         msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
394         stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
395         goto error;
396     }
397
398     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
399
400     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
401     {
402         switch( p_ftyp->data.p_ftyp->i_major_brand )
403         {
404             case( ATOM_isom ):
405                 msg_Dbg( p_demux,
406                          "ISO Media file (isom) version %d.",
407                          p_ftyp->data.p_ftyp->i_minor_version );
408                 break;
409             case( ATOM_3gp4 ):
410             case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
411             case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
412             case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
413                 msg_Dbg( p_demux, "3GPP Media file Release: %c",
414 #ifdef WORDS_BIGENDIAN
415                         p_ftyp->data.p_ftyp->i_major_brand
416 #else
417                         p_ftyp->data.p_ftyp->i_major_brand >> 24
418 #endif
419                         );
420                 break;
421             case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
422                 msg_Dbg( p_demux, "Apple QuickTime file" );
423                 break;
424             case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
425                 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
426                 break;
427             default:
428                 msg_Dbg( p_demux,
429                          "unrecognized major file specification (%4.4s).",
430                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
431                 break;
432         }
433     }
434     else
435     {
436         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
437     }
438
439     /* the file need to have one moov box */
440     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
441     {
442         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
443
444         if( !p_foov )
445         {
446             msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
447             goto error;
448         }
449         /* we have a free box as a moov, rename it */
450         p_foov->i_type = ATOM_moov;
451     }
452
453     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
454     {
455         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
456         int        i;
457
458         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
459
460         input_thread_t *p_input = demux_GetParentInput( p_demux );
461         input_item_t *p_current = input_GetItem( p_input );
462
463         input_item_node_t *p_subitems = input_item_node_Create( p_current );
464
465         for( i = 0; i < i_count; i++ )
466         {
467             MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
468             char      *psz_ref;
469             uint32_t  i_ref_type;
470
471             if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
472             {
473                 continue;
474             }
475             i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
476
477             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
478                      psz_ref, (char*)&i_ref_type );
479
480             if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
481             {
482                 if( strstr( psz_ref, "qt5gateQT" ) )
483                 {
484                     msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
485                     continue;
486                 }
487                 if( !strncmp( psz_ref, "http://", 7 ) ||
488                     !strncmp( psz_ref, "rtsp://", 7 ) )
489                 {
490                     ;
491                 }
492                 else
493                 {
494                     char *psz_absolute;
495                     char *psz_path = strdup( p_demux->psz_location );
496                     char *end = strrchr( psz_path, '/' );
497                     if( end ) end[1] = '\0';
498                     else *psz_path = '\0';
499
500                     if( asprintf( &psz_absolute, "%s://%s%s",
501                                   p_demux->psz_access, psz_path, psz_ref ) < 0 )
502                     {
503                         free( psz_ref );
504                         free( psz_path );
505                         vlc_object_release( p_input) ;
506                         return VLC_ENOMEM;
507                     }
508
509                     free( psz_ref );
510                     psz_ref = psz_absolute;
511                     free( psz_path );
512                 }
513                 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
514                 input_item_t *p_item = input_item_New( psz_ref, NULL );
515                 input_item_CopyOptions( p_current, p_item );
516                 input_item_node_AppendItem( p_subitems, p_item );
517                 vlc_gc_decref( p_item );
518             }
519             else
520             {
521                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
522                          (char*)&p_rdrf->data.p_rdrf->i_ref_type );
523             }
524             free( psz_ref );
525         }
526         input_item_node_PostAndDelete( p_subitems );
527         vlc_object_release( p_input );
528     }
529
530     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
531     {
532         if( !p_rmra )
533         {
534             msg_Err( p_demux, "cannot find /moov/mvhd" );
535             goto error;
536         }
537         else
538         {
539             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
540             p_demux->pf_demux = DemuxRef;
541             return VLC_SUCCESS;
542         }
543     }
544     else
545     {
546         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
547         if( p_sys->i_timescale == 0 )
548         {
549             msg_Err( p_this, "bad timescale" );
550             goto error;
551         }
552         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
553     }
554
555     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
556     {
557         msg_Err( p_demux, "cannot find any /moov/trak" );
558         goto error;
559     }
560     msg_Dbg( p_demux, "found %d track%c",
561                         p_sys->i_tracks,
562                         p_sys->i_tracks ? 's':' ' );
563
564     if( InitTracks( p_demux ) != VLC_SUCCESS )
565         goto error;
566
567     /* Search the first chap reference (like quicktime) and
568      * check that at least 1 stream is enabled */
569     p_sys->p_tref_chap = NULL;
570     b_enabled_es = false;
571     for( i = 0; i < p_sys->i_tracks; i++ )
572     {
573         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
574
575
576         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
577         if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
578             b_enabled_es = true;
579
580         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
581         if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
582             p_sys->p_tref_chap = p_chap;
583     }
584
585     /* now process each track and extract all useful information */
586     for( i = 0; i < p_sys->i_tracks; i++ )
587     {
588         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
589         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
590
591         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
592         {
593             const char *psz_cat;
594             switch( p_sys->track[i].fmt.i_cat )
595             {
596                 case( VIDEO_ES ):
597                     psz_cat = "video";
598                     break;
599                 case( AUDIO_ES ):
600                     psz_cat = "audio";
601                     break;
602                 case( SPU_ES ):
603                     psz_cat = "subtitle";
604                     break;
605
606                 default:
607                     psz_cat = "unknown";
608                     break;
609             }
610
611             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
612                      p_sys->track[i].i_track_ID, psz_cat,
613                      p_sys->track[i].b_enable ? "enable":"disable",
614                      p_sys->track[i].fmt.psz_language ?
615                      p_sys->track[i].fmt.psz_language : "undef" );
616         }
617         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
618         {
619             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
620                      p_sys->track[i].i_track_ID,
621                      p_sys->track[i].fmt.psz_language ?
622                      p_sys->track[i].fmt.psz_language : "undef" );
623         }
624         else
625         {
626             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
627                      p_sys->track[i].i_track_ID );
628         }
629     }
630
631     /* */
632     LoadChapter( p_demux );
633
634     return VLC_SUCCESS;
635
636 error:
637     if( p_sys->p_root )
638     {
639         MP4_BoxFree( p_demux->s, p_sys->p_root );
640     }
641     free( p_sys );
642     return VLC_EGENERIC;
643 }
644
645 /*****************************************************************************
646  * Demux: read packet and send them to decoders
647  *****************************************************************************
648  * TODO check for newly selected track (ie audio upt to now )
649  *****************************************************************************/
650 static int Demux( demux_t *p_demux )
651 {
652     demux_sys_t *p_sys = p_demux->p_sys;
653     unsigned int i_track;
654
655
656     unsigned int i_track_selected;
657
658     /* check for newly selected/unselected track */
659     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
660          i_track++ )
661     {
662         mp4_track_t *tk = &p_sys->track[i_track];
663         bool b;
664
665         if( !tk->b_ok || tk->b_chapter ||
666             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
667         {
668             continue;
669         }
670
671         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
672
673         if( tk->b_selected && !b )
674         {
675             MP4_TrackUnselect( p_demux, tk );
676         }
677         else if( !tk->b_selected && b)
678         {
679             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
680         }
681
682         if( tk->b_selected )
683         {
684             i_track_selected++;
685         }
686     }
687
688     if( i_track_selected <= 0 )
689     {
690         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
691         if( p_sys->i_timescale > 0 )
692         {
693             int64_t i_length = (mtime_t)1000000 *
694                                (mtime_t)p_sys->i_duration /
695                                (mtime_t)p_sys->i_timescale;
696             if( MP4_GetMoviePTS( p_sys ) >= i_length )
697                 return 0;
698             return 1;
699         }
700
701         msg_Warn( p_demux, "no track selected, exiting..." );
702         return 0;
703     }
704
705     /* */
706     MP4_UpdateSeekpoint( p_demux );
707
708     /* first wait for the good time to read a packet */
709     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
710
711     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
712
713     /* we will read 100ms for each stream so ...*/
714     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
715
716     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
717     {
718         mp4_track_t *tk = &p_sys->track[i_track];
719
720         if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
721             continue;
722
723         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
724         {
725 #if 0
726             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
727                      MP4_TrackGetDTS( p_demux, tk ),
728                      MP4_GetMoviePTS( p_sys ) );
729 #endif
730
731             if( MP4_TrackSampleSize( tk ) > 0 )
732             {
733                 block_t *p_block;
734                 int64_t i_delta;
735
736                 /* go,go go ! */
737                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
738                 {
739                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
740                               tk->i_track_ID );
741                     MP4_TrackUnselect( p_demux, tk );
742                     break;
743                 }
744
745                 /* now read pes */
746                 if( !(p_block =
747                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
748                 {
749                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
750                               tk->i_track_ID );
751                     MP4_TrackUnselect( p_demux, tk );
752                     break;
753                 }
754
755                 else if( tk->fmt.i_cat == SPU_ES )
756                 {
757                     if( tk->fmt.i_codec == VLC_CODEC_SUBT &&
758                         p_block->i_buffer >= 2 )
759                     {
760                         size_t i_size = GetWBE( p_block->p_buffer );
761
762                         if( i_size + 2 <= p_block->i_buffer )
763                         {
764                             char *p;
765                             /* remove the length field, and append a '\0' */
766                             memmove( &p_block->p_buffer[0],
767                                      &p_block->p_buffer[2], i_size );
768                             p_block->p_buffer[i_size] = '\0';
769                             p_block->i_buffer = i_size + 1;
770
771                             /* convert \r -> \n */
772                             while( ( p = strchr((char *) p_block->p_buffer, '\r' ) ) )
773                             {
774                                 *p = '\n';
775                             }
776                         }
777                         else
778                         {
779                             /* Invalid */
780                             p_block->i_buffer = 0;
781                         }
782                     }
783                 }
784                 /* dts */
785                 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
786                 /* pts */
787                 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
788                 if( i_delta != -1 )
789                     p_block->i_pts = p_block->i_dts + i_delta;
790                 else if( tk->fmt.i_cat != VIDEO_ES )
791                     p_block->i_pts = p_block->i_dts;
792                 else
793                     p_block->i_pts = VLC_TS_INVALID;
794
795                 es_out_Send( p_demux->out, tk->p_es, p_block );
796             }
797
798             /* Next sample */
799             if( MP4_TrackNextSample( p_demux, tk ) )
800                 break;
801         }
802     }
803
804     return 1;
805 }
806
807 static void MP4_UpdateSeekpoint( demux_t *p_demux )
808 {
809     demux_sys_t *p_sys = p_demux->p_sys;
810     int64_t i_time;
811     int i;
812     if( !p_sys->p_title )
813         return;
814     i_time = MP4_GetMoviePTS( p_sys );
815     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
816     {
817         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
818             break;
819     }
820     i--;
821
822     if( i != p_demux->info.i_seekpoint && i >= 0 )
823     {
824         p_demux->info.i_seekpoint = i;
825         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
826     }
827 }
828 /*****************************************************************************
829  * Seek: Go to i_date
830 ******************************************************************************/
831 static int Seek( demux_t *p_demux, mtime_t i_date )
832 {
833     demux_sys_t *p_sys = p_demux->p_sys;
834     unsigned int i_track;
835
836     /* First update global time */
837     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
838     p_sys->i_pcr  = i_date;
839
840     /* Now for each stream try to go to this time */
841     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
842     {
843         mp4_track_t *tk = &p_sys->track[i_track];
844         MP4_TrackSeek( p_demux, tk, i_date );
845     }
846     MP4_UpdateSeekpoint( p_demux );
847
848     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
849
850     return VLC_SUCCESS;
851 }
852
853 static int MP4_frg_Seek( demux_t *p_demux, double f )
854 {
855     demux_sys_t *p_sys = p_demux->p_sys;
856
857     int64_t i64 = stream_Size( p_demux->s );
858     if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
859     {
860         return VLC_EGENERIC;
861     }
862     else
863     {
864         /* update global time */
865         p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
866         p_sys->i_pcr  = MP4_GetMoviePTS( p_sys );
867
868         for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
869         {
870             mp4_track_t *tk = &p_sys->track[i_track];
871
872             /* We don't want the current chunk to be flushed */
873             tk->cchunk->i_sample = tk->cchunk->i_sample_count;
874
875             /* reset/update some values */
876             tk->i_sample = tk->i_sample_first = 0;
877             tk->i_first_dts = p_sys->i_time;
878
879             /* We want to discard the current chunk and get the next one at once */
880             tk->b_has_non_empty_cchunk = false;
881         }
882         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
883         return VLC_SUCCESS;
884     }
885 }
886
887 /*****************************************************************************
888  * Control:
889  *****************************************************************************/
890 static int Control( demux_t *p_demux, int i_query, va_list args )
891 {
892     demux_sys_t *p_sys = p_demux->p_sys;
893
894     double f, *pf;
895     int64_t i64, *pi64;
896
897     switch( i_query )
898     {
899         case DEMUX_GET_POSITION:
900             pf = (double*)va_arg( args, double * );
901             if( p_sys->i_duration > 0 )
902             {
903                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
904             }
905             else
906             {
907                 *pf = 0.0;
908             }
909             return VLC_SUCCESS;
910
911         case DEMUX_SET_POSITION:
912             f = (double)va_arg( args, double );
913             if( p_sys->b_fragmented )
914             {
915                 return MP4_frg_Seek( p_demux, f );
916             }
917             else if( p_sys->i_timescale > 0 )
918             {
919                 i64 = (int64_t)( f * (double)1000000 *
920                                  (double)p_sys->i_duration /
921                                  (double)p_sys->i_timescale );
922                 return Seek( p_demux, i64 );
923             }
924             else return VLC_SUCCESS;
925
926         case DEMUX_GET_TIME:
927             pi64 = (int64_t*)va_arg( args, int64_t * );
928             if( p_sys->i_timescale > 0 )
929             {
930                 *pi64 = (mtime_t)1000000 *
931                         (mtime_t)p_sys->i_time /
932                         (mtime_t)p_sys->i_timescale;
933             }
934             else *pi64 = 0;
935             return VLC_SUCCESS;
936
937         case DEMUX_SET_TIME:
938             i64 = (int64_t)va_arg( args, int64_t );
939             return Seek( p_demux, i64 );
940
941         case DEMUX_GET_LENGTH:
942             pi64 = (int64_t*)va_arg( args, int64_t * );
943             if( p_sys->i_timescale > 0 )
944             {
945                 *pi64 = (mtime_t)1000000 *
946                         (mtime_t)p_sys->i_duration /
947                         (mtime_t)p_sys->i_timescale;
948             }
949             else *pi64 = 0;
950             return VLC_SUCCESS;
951
952         case DEMUX_GET_FPS:
953             pf = (double*)va_arg( args, double* );
954             *pf = p_sys->f_fps;
955             return VLC_SUCCESS;
956
957         case DEMUX_GET_META:
958         {
959             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
960             MP4_Box_t  *p_0xa9xxx;
961
962             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
963             if( p_udta == NULL )
964             {
965                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
966                 if( p_udta == NULL )
967                 {
968                     return VLC_EGENERIC;
969                 }
970             }
971
972             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
973                  p_0xa9xxx = p_0xa9xxx->p_next )
974             {
975
976                 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
977                     continue;
978
979                 /* FIXME FIXME: should convert from whatever the character
980                  * encoding of MP4 meta data is to UTF-8. */
981 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
982     if( psz_utf ) { EnsureUTF8( psz_utf );  \
983                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
984
985                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
986                 switch( p_0xa9xxx->i_type )
987                 {
988                 case ATOM_0xa9nam: /* Full name */
989                     SET( vlc_meta_SetTitle );
990                     break;
991                 case ATOM_0xa9aut:
992                     SET( vlc_meta_SetArtist );
993                     break;
994                 case ATOM_0xa9ART:
995                     SET( vlc_meta_SetArtist );
996                     break;
997                 case ATOM_0xa9cpy:
998                     SET( vlc_meta_SetCopyright );
999                     break;
1000                 case ATOM_0xa9day: /* Creation Date */
1001                     SET( vlc_meta_SetDate );
1002                     break;
1003                 case ATOM_0xa9des: /* Description */
1004                     SET( vlc_meta_SetDescription );
1005                     break;
1006                 case ATOM_0xa9gen: /* Genre */
1007                     SET( vlc_meta_SetGenre );
1008                     break;
1009
1010                 case ATOM_gnre:
1011                     if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1012                         vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1013                     break;
1014
1015                 case ATOM_0xa9alb: /* Album */
1016                     SET( vlc_meta_SetAlbum );
1017                     break;
1018
1019                 case ATOM_0xa9trk: /* Track */
1020                     SET( vlc_meta_SetTrackNum );
1021                     break;
1022                 case ATOM_trkn:
1023                 {
1024                     char psz_trck[11];
1025                     snprintf( psz_trck, sizeof( psz_trck ), "%i",
1026                               p_0xa9xxx->data.p_trkn->i_track_number );
1027                     vlc_meta_SetTrackNum( p_meta, psz_trck );
1028                     if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1029                     {
1030                         snprintf( psz_trck, sizeof( psz_trck ), "%i",
1031                                   p_0xa9xxx->data.p_trkn->i_track_total );
1032                         vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1033                     }
1034                     break;
1035                 }
1036                 case ATOM_0xa9cmt: /* Commment */
1037                     SET( vlc_meta_SetDescription );
1038                     break;
1039
1040                 case ATOM_0xa9url: /* URL */
1041                     SET( vlc_meta_SetURL );
1042                     break;
1043
1044                 case ATOM_0xa9too: /* Encoder Tool */
1045                 case ATOM_0xa9enc: /* Encoded By */
1046                     SET( vlc_meta_SetEncodedBy );
1047                     break;
1048
1049                 case ATOM_0xa9pub:
1050                     SET( vlc_meta_SetPublisher );
1051                     break;
1052
1053                 default:
1054                     break;
1055                 }
1056 #undef SET
1057                 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1058                 {
1059                     { ATOM_0xa9wrt, N_("Writer") },
1060                     { ATOM_0xa9com, N_("Composer") },
1061                     { ATOM_0xa9prd, N_("Producer") },
1062                     { ATOM_0xa9inf, N_("Information") },
1063                     { ATOM_0xa9dir, N_("Director") },
1064                     { ATOM_0xa9dis, N_("Disclaimer") },
1065                     { ATOM_0xa9req, N_("Requirements") },
1066                     { ATOM_0xa9fmt, N_("Original Format") },
1067                     { ATOM_0xa9dsa, N_("Display Source As") },
1068                     { ATOM_0xa9hst, N_("Host Computer") },
1069                     { ATOM_0xa9prf, N_("Performers") },
1070                     { ATOM_0xa9ope, N_("Original Performer") },
1071                     { ATOM_0xa9src, N_("Providers Source Content") },
1072                     { ATOM_0xa9wrn, N_("Warning") },
1073                     { ATOM_0xa9swr, N_("Software") },
1074                     { ATOM_0xa9lyr, N_("Lyrics") },
1075                     { ATOM_0xa9mak, N_("Record Company") },
1076                     { ATOM_0xa9mod, N_("Model") },
1077                     { ATOM_0xa9PRD, N_("Product") },
1078                     { ATOM_0xa9grp, N_("Grouping") },
1079                     { ATOM_0xa9gen, N_("Genre") },
1080                     { ATOM_0xa9st3, N_("Sub-Title") },
1081                     { ATOM_0xa9arg, N_("Arranger") },
1082                     { ATOM_0xa9ard, N_("Art Director") },
1083                     { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1084                     { ATOM_0xa9con, N_("Conductor") },
1085                     { ATOM_0xa9des, N_("Song Description") },
1086                     { ATOM_0xa9lnt, N_("Liner Notes") },
1087                     { ATOM_0xa9phg, N_("Phonogram Rights") },
1088                     { ATOM_0xa9pub, N_("Publisher") },
1089                     { ATOM_0xa9sne, N_("Sound Engineer") },
1090                     { ATOM_0xa9sol, N_("Soloist") },
1091                     { ATOM_0xa9thx, N_("Thanks") },
1092                     { ATOM_0xa9xpd, N_("Executive Producer") },
1093                     { 0, "" },
1094                 };
1095                 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1096                 {
1097                     if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1098                     {
1099                         char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1100                         if( psz_utf )
1101                         {
1102                              EnsureUTF8( psz_utf );
1103                              vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1104                              free( psz_utf );
1105                         }
1106                         break;
1107                     }
1108                 }
1109             }
1110             return VLC_SUCCESS;
1111         }
1112
1113         case DEMUX_GET_TITLE_INFO:
1114         {
1115             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1116             int *pi_int    = (int*)va_arg( args, int* );
1117             int *pi_title_offset = (int*)va_arg( args, int* );
1118             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1119
1120             if( !p_sys->p_title )
1121                 return VLC_EGENERIC;
1122
1123             *pi_int = 1;
1124             *ppp_title = malloc( sizeof( input_title_t*) );
1125             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1126             *pi_title_offset = 0;
1127             *pi_seekpoint_offset = 0;
1128             return VLC_SUCCESS;
1129         }
1130         case DEMUX_SET_TITLE:
1131         {
1132             const int i_title = (int)va_arg( args, int );
1133             if( !p_sys->p_title || i_title != 0 )
1134                 return VLC_EGENERIC;
1135             return VLC_SUCCESS;
1136         }
1137         case DEMUX_SET_SEEKPOINT:
1138         {
1139             const int i_seekpoint = (int)va_arg( args, int );
1140             if( !p_sys->p_title )
1141                 return VLC_EGENERIC;
1142             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1143         }
1144
1145         case DEMUX_SET_NEXT_DEMUX_TIME:
1146         case DEMUX_SET_GROUP:
1147         case DEMUX_HAS_UNSUPPORTED_META:
1148         case DEMUX_GET_ATTACHMENTS:
1149         case DEMUX_GET_PTS_DELAY:
1150         case DEMUX_CAN_RECORD:
1151             return VLC_EGENERIC;
1152
1153         default:
1154             msg_Warn( p_demux, "control query %u unimplemented", i_query );
1155             return VLC_EGENERIC;
1156     }
1157 }
1158
1159 /*****************************************************************************
1160  * Close: frees unused data
1161  *****************************************************************************/
1162 static void Close ( vlc_object_t * p_this )
1163 {
1164     demux_t *  p_demux = (demux_t *)p_this;
1165     demux_sys_t *p_sys = p_demux->p_sys;
1166     unsigned int i_track;
1167
1168     msg_Dbg( p_demux, "freeing all memory" );
1169
1170     MP4_BoxFree( p_demux->s, p_sys->p_root );
1171     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1172     {
1173         MP4_TrackDestroy(  &p_sys->track[i_track] );
1174     }
1175     FREENULL( p_sys->track );
1176
1177     if( p_sys->p_title )
1178         vlc_input_title_Delete( p_sys->p_title );
1179
1180     free( p_sys );
1181 }
1182
1183
1184
1185 /****************************************************************************
1186  * Local functions, specific to vlc
1187  ****************************************************************************/
1188 /* Chapters */
1189 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
1190 {
1191     demux_sys_t *p_sys = p_demux->p_sys;
1192     int i;
1193
1194     p_sys->p_title = vlc_input_title_New();
1195     for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1196     {
1197         seekpoint_t *s = vlc_seekpoint_New();
1198
1199         s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1200         EnsureUTF8( s->psz_name );
1201         s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1202         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1203     }
1204 }
1205 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1206 {
1207     demux_sys_t *p_sys = p_demux->p_sys;
1208
1209     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1210     {
1211         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1212         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1213         const unsigned int i_size = MP4_TrackSampleSize( tk );
1214
1215         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1216         {
1217             char p_buffer[256];
1218             const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1219             const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1220
1221             if( i_len > 0 )
1222             {
1223                 seekpoint_t *s = vlc_seekpoint_New();
1224
1225                 s->psz_name = strndup( &p_buffer[2], i_len );
1226                 EnsureUTF8( s->psz_name );
1227
1228                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1229
1230                 if( !p_sys->p_title )
1231                     p_sys->p_title = vlc_input_title_New();
1232                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1233             }
1234         }
1235         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1236                               tk->chunk[tk->i_chunk].i_sample_count )
1237             tk->i_chunk++;
1238     }
1239 }
1240 static void LoadChapter( demux_t  *p_demux )
1241 {
1242     demux_sys_t *p_sys = p_demux->p_sys;
1243     MP4_Box_t *p_chpl;
1244
1245     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1246     {
1247         LoadChapterGpac( p_demux, p_chpl );
1248     }
1249     else if( p_sys->p_tref_chap )
1250     {
1251         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1252         unsigned int i, j;
1253
1254         /* Load the first subtitle track like quicktime */
1255         for( i = 0; i < p_chap->i_entry_count; i++ )
1256         {
1257             for( j = 0; j < p_sys->i_tracks; j++ )
1258             {
1259                 mp4_track_t *tk = &p_sys->track[j];
1260                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1261                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1262                     break;
1263             }
1264             if( j < p_sys->i_tracks )
1265             {
1266                 LoadChapterApple( p_demux, &p_sys->track[j] );
1267                 break;
1268             }
1269         }
1270     }
1271
1272     /* Add duration if titles are enabled */
1273     if( p_sys->p_title )
1274     {
1275         p_sys->p_title->i_length = (uint64_t)1000000 *
1276                        (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1277     }
1278 }
1279
1280 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1281 static int TrackCreateChunksIndex( demux_t *p_demux,
1282                                    mp4_track_t *p_demux_track )
1283 {
1284     demux_sys_t *p_sys = p_demux->p_sys;
1285     if( p_sys->b_fragmented )
1286         return VLC_SUCCESS;
1287
1288     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1289     MP4_Box_t *p_stsc;
1290
1291     unsigned int i_chunk;
1292     unsigned int i_index, i_last;
1293
1294     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1295           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1296         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1297     {
1298         return( VLC_EGENERIC );
1299     }
1300
1301     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1302     if( !p_demux_track->i_chunk_count )
1303     {
1304         msg_Warn( p_demux, "no chunk defined" );
1305         return( VLC_EGENERIC );
1306     }
1307     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1308                                    sizeof( mp4_chunk_t ) );
1309     if( p_demux_track->chunk == NULL )
1310     {
1311         return VLC_ENOMEM;
1312     }
1313
1314     /* first we read chunk offset */
1315     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1316     {
1317         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1318
1319         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1320
1321         ck->i_first_dts = 0;
1322         ck->p_sample_count_dts = NULL;
1323         ck->p_sample_delta_dts = NULL;
1324         ck->p_sample_count_pts = NULL;
1325         ck->p_sample_offset_pts = NULL;
1326     }
1327
1328     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1329         to be used for the sample XXX begin to 1
1330         We construct it begining at the end */
1331     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1332     i_index = p_stsc->data.p_stsc->i_entry_count;
1333     if( !i_index )
1334     {
1335         msg_Warn( p_demux, "cannot read chunk table or table empty" );
1336         return( VLC_EGENERIC );
1337     }
1338
1339     while( i_index-- )
1340     {
1341         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1342              i_chunk < i_last; i_chunk++ )
1343         {
1344             if( i_chunk >= p_demux_track->i_chunk_count )
1345             {
1346                 msg_Warn( p_demux, "corrupted chunk table" );
1347                 return VLC_EGENERIC;
1348             }
1349
1350             p_demux_track->chunk[i_chunk].i_sample_description_index =
1351                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
1352             p_demux_track->chunk[i_chunk].i_sample_count =
1353                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1354         }
1355         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1356     }
1357
1358     p_demux_track->chunk[0].i_sample_first = 0;
1359     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1360     {
1361         p_demux_track->chunk[i_chunk].i_sample_first =
1362             p_demux_track->chunk[i_chunk-1].i_sample_first +
1363                 p_demux_track->chunk[i_chunk-1].i_sample_count;
1364     }
1365
1366     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1367              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1368
1369     return VLC_SUCCESS;
1370 }
1371
1372 static int TrackCreateSamplesIndex( demux_t *p_demux,
1373                                     mp4_track_t *p_demux_track )
1374 {
1375     demux_sys_t *p_sys = p_demux->p_sys;
1376     if( p_sys->b_fragmented )
1377         return VLC_SUCCESS;
1378
1379     MP4_Box_t *p_box;
1380     MP4_Box_data_stsz_t *stsz;
1381     MP4_Box_data_stts_t *stts;
1382     /* TODO use also stss and stsh table for seeking */
1383     /* FIXME use edit table */
1384     int64_t i_sample;
1385     int64_t i_chunk;
1386
1387     int64_t i_index;
1388     int64_t i_index_sample_used;
1389
1390     int64_t i_next_dts;
1391
1392     /* Find stsz
1393      *  Gives the sample size for each samples. There is also a stz2 table
1394      *  (compressed form) that we need to implement TODO */
1395     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1396     if( !p_box )
1397     {
1398         /* FIXME and stz2 */
1399         msg_Warn( p_demux, "cannot find STSZ box" );
1400         return VLC_EGENERIC;
1401     }
1402     stsz = p_box->data.p_stsz;
1403
1404     /* Find stts
1405      *  Gives mapping between sample and decoding time
1406      */
1407     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1408     if( !p_box )
1409     {
1410         msg_Warn( p_demux, "cannot find STTS box" );
1411         return VLC_EGENERIC;
1412     }
1413     stts = p_box->data.p_stts;
1414
1415     /* Use stsz table to create a sample number -> sample size table */
1416     p_demux_track->i_sample_count = stsz->i_sample_count;
1417     if( stsz->i_sample_size )
1418     {
1419         /* 1: all sample have the same size, so no need to construct a table */
1420         p_demux_track->i_sample_size = stsz->i_sample_size;
1421         p_demux_track->p_sample_size = NULL;
1422     }
1423     else
1424     {
1425         /* 2: each sample can have a different size */
1426         p_demux_track->i_sample_size = 0;
1427         p_demux_track->p_sample_size =
1428             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1429         if( p_demux_track->p_sample_size == NULL )
1430             return VLC_ENOMEM;
1431
1432         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1433         {
1434             p_demux_track->p_sample_size[i_sample] =
1435                     stsz->i_entry_size[i_sample];
1436         }
1437     }
1438
1439     /* Use stts table to create a sample number -> dts table.
1440      * XXX: if we don't want to waste too much memory, we can't expand
1441      *  the box! so each chunk will contain an "extract" of this table
1442      *  for fast research (problem with raw stream where a sample is sometime
1443      *  just channels*bits_per_sample/8 */
1444
1445     i_next_dts = 0;
1446     i_index = 0; i_index_sample_used = 0;
1447     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1448     {
1449         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1450         int64_t i_entry, i_sample_count, i;
1451
1452         /* save first dts */
1453         ck->i_first_dts = i_next_dts;
1454         ck->i_last_dts  = i_next_dts;
1455
1456         /* count how many entries are needed for this chunk
1457          * for p_sample_delta_dts and p_sample_count_dts */
1458         i_sample_count = ck->i_sample_count;
1459
1460         i_entry = 0;
1461         while( i_sample_count > 0 )
1462         {
1463             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1464             /* don't count already used sample in this entry */
1465             if( i_entry == 0 )
1466                 i_sample_count += i_index_sample_used;
1467
1468             i_entry++;
1469         }
1470
1471         /* allocate them */
1472         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1473         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1474
1475         if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1476             return VLC_ENOMEM;
1477
1478         /* now copy */
1479         i_sample_count = ck->i_sample_count;
1480         for( i = 0; i < i_entry; i++ )
1481         {
1482             int64_t i_used;
1483             int64_t i_rest;
1484
1485             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1486
1487             i_used = __MIN( i_rest, i_sample_count );
1488
1489             i_index_sample_used += i_used;
1490             i_sample_count -= i_used;
1491             i_next_dts += i_used * stts->i_sample_delta[i_index];
1492
1493             ck->p_sample_count_dts[i] = i_used;
1494             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1495             if( i_used > 0 )
1496                 ck->i_last_dts = i_next_dts - ck->p_sample_delta_dts[i];
1497
1498             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1499             {
1500                 i_index++;
1501                 i_index_sample_used = 0;
1502             }
1503         }
1504     }
1505
1506     /* Find ctts
1507      *  Gives the delta between decoding time (dts) and composition table (pts)
1508      */
1509     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1510     if( p_box )
1511     {
1512         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1513
1514         msg_Warn( p_demux, "CTTS table" );
1515
1516         /* Create pts-dts table per chunk */
1517         i_index = 0; i_index_sample_used = 0;
1518         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1519         {
1520             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1521             int64_t i_entry, i_sample_count, i;
1522
1523             /* count how many entries are needed for this chunk
1524              * for p_sample_delta_dts and p_sample_count_dts */
1525             i_sample_count = ck->i_sample_count;
1526
1527             i_entry = 0;
1528             while( i_sample_count > 0 )
1529             {
1530                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1531
1532                 /* don't count already used sample in this entry */
1533                 if( i_entry == 0 )
1534                     i_sample_count += i_index_sample_used;
1535
1536                 i_entry++;
1537             }
1538
1539             /* allocate them */
1540             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1541             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1542             if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1543                 return VLC_ENOMEM;
1544
1545             /* now copy */
1546             i_sample_count = ck->i_sample_count;
1547             for( i = 0; i < i_entry; i++ )
1548             {
1549                 int64_t i_used;
1550                 int64_t i_rest;
1551
1552                 i_rest = ctts->i_sample_count[i_index] -
1553                     i_index_sample_used;
1554
1555                 i_used = __MIN( i_rest, i_sample_count );
1556
1557                 i_index_sample_used += i_used;
1558                 i_sample_count -= i_used;
1559
1560                 ck->p_sample_count_pts[i] = i_used;
1561                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1562
1563                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1564                 {
1565                     i_index++;
1566                     i_index_sample_used = 0;
1567                 }
1568             }
1569         }
1570     }
1571
1572     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:%"PRId64"s",
1573              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1574              i_next_dts / p_demux_track->i_timescale );
1575
1576     return VLC_SUCCESS;
1577 }
1578
1579 /**
1580  * It computes the sample rate for a video track using the given sample
1581  * description index
1582  */
1583 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1584                                   const mp4_track_t *p_track,
1585                                   unsigned i_sd_index,
1586                                   unsigned i_chunk )
1587 {
1588     *pi_num = 0;
1589     *pi_den = 0;
1590
1591     if( p_track->i_chunk_count <= 0 )
1592         return;
1593
1594     /* */
1595     const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1596     while( p_chunk > &p_track->chunk[0] &&
1597            p_chunk[-1].i_sample_description_index == i_sd_index )
1598     {
1599         p_chunk--;
1600     }
1601
1602     uint64_t i_sample = 0;
1603     uint64_t i_first_dts = p_chunk->i_first_dts;
1604     uint64_t i_last_dts;
1605     do
1606     {
1607         i_sample += p_chunk->i_sample_count;
1608         i_last_dts = p_chunk->i_last_dts;
1609         p_chunk++;
1610     }
1611     while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1612            p_chunk->i_sample_description_index == i_sd_index );
1613
1614     if( i_sample > 1 && i_first_dts < i_last_dts )
1615         vlc_ureduce( pi_num, pi_den,
1616                      ( i_sample - 1) *  p_track->i_timescale,
1617                      i_last_dts - i_first_dts,
1618                      UINT16_MAX);
1619 }
1620
1621 /*
1622  * TrackCreateES:
1623  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1624  */
1625 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1626                           unsigned int i_chunk, es_out_id_t **pp_es )
1627 {
1628     demux_sys_t *p_sys = p_demux->p_sys;
1629     unsigned int i_sample_description_index;
1630
1631     if( p_sys->b_fragmented )
1632         i_sample_description_index = 1; /* XXX */
1633     else
1634         i_sample_description_index =
1635                 p_track->chunk[i_chunk].i_sample_description_index;
1636
1637     MP4_Box_t   *p_sample;
1638     MP4_Box_t   *p_esds;
1639     MP4_Box_t   *p_frma;
1640     MP4_Box_t   *p_enda;
1641     MP4_Box_t   *p_pasp;
1642
1643     if( pp_es )
1644         *pp_es = NULL;
1645
1646     if( !i_sample_description_index )
1647     {
1648         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1649                   p_track->i_track_ID );
1650         return VLC_EGENERIC;
1651     }
1652
1653     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1654                             i_sample_description_index - 1 );
1655
1656     if( !p_sample ||
1657         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1658     {
1659         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1660                   p_track->i_track_ID );
1661         return VLC_EGENERIC;
1662     }
1663
1664     p_track->p_sample = p_sample;
1665
1666     if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1667     {
1668         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1669
1670         p_sample->i_type = p_frma->data.p_frma->i_type;
1671     }
1672
1673     p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1674     if( !p_enda )
1675         p_enda = MP4_BoxGet( p_sample, "enda" );
1676
1677     p_pasp = MP4_BoxGet( p_sample, "pasp" );
1678
1679     /* */
1680     switch( p_track->fmt.i_cat )
1681     {
1682     case VIDEO_ES:
1683         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1684         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1685         p_track->fmt.video.i_bits_per_pixel =
1686             p_sample->data.p_sample_vide->i_depth;
1687
1688         /* fall on display size */
1689         if( p_track->fmt.video.i_width <= 0 )
1690             p_track->fmt.video.i_width = p_track->i_width;
1691         if( p_track->fmt.video.i_height <= 0 )
1692             p_track->fmt.video.i_height = p_track->i_height;
1693
1694         /* Find out apect ratio from display size */
1695         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1696             /* Work-around buggy muxed files */
1697             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1698         {
1699             p_track->fmt.video.i_sar_num = p_track->i_width  * p_track->fmt.video.i_height;
1700             p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1701         }
1702         if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1703                       p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1704         {
1705             p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1706             p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1707         }
1708
1709         /* Support for cropping (eg. in H263 files) */
1710         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1711         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1712
1713         /* Frame rate */
1714         TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1715                               &p_track->fmt.video.i_frame_rate_base,
1716                               p_track, i_sample_description_index, i_chunk );
1717         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1718                                 (float)p_track->fmt.video.i_frame_rate_base;
1719
1720         /* Rotation */
1721         switch( (int)p_track->f_rotation ) {
1722             case 90:
1723                 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1724                 break;
1725             case 180:
1726                 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1727                 break;
1728             case 270:
1729                 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1730                 break;
1731         }
1732
1733         break;
1734
1735     case AUDIO_ES:
1736         p_track->fmt.audio.i_channels =
1737             p_sample->data.p_sample_soun->i_channelcount;
1738         p_track->fmt.audio.i_rate =
1739             p_sample->data.p_sample_soun->i_sampleratehi;
1740         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1741             p_sample->data.p_sample_soun->i_sampleratehi *
1742                 p_sample->data.p_sample_soun->i_samplesize;
1743         p_track->fmt.audio.i_bitspersample =
1744             p_sample->data.p_sample_soun->i_samplesize;
1745
1746         if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1747         {
1748             MP4_Box_data_sample_soun_t *p_soun;
1749             p_soun = p_sample->data.p_sample_soun;
1750
1751             if( p_soun->i_qt_version == 0 )
1752             {
1753                 switch( p_sample->i_type )
1754                 {
1755                     case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1756                         p_soun->i_qt_version = 1;
1757                         p_soun->i_sample_per_packet = 64;
1758                         p_soun->i_bytes_per_packet  = 34;
1759                         p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1760                         p_soun->i_bytes_per_sample  = 2;
1761                         break;
1762                     case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1763                         p_soun->i_qt_version = 1;
1764                         p_soun->i_sample_per_packet = 6;
1765                         p_soun->i_bytes_per_packet  = 2;
1766                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1767                         p_soun->i_bytes_per_sample  = 2;
1768                         break;
1769                     case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1770                         p_soun->i_qt_version = 1;
1771                         p_soun->i_sample_per_packet = 12;
1772                         p_soun->i_bytes_per_packet  = 2;
1773                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1774                         p_soun->i_bytes_per_sample  = 2;
1775                         break;
1776                     case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1777                     case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1778                         p_soun->i_samplesize = 8;
1779                         p_track->i_sample_size = p_soun->i_channelcount;
1780                         break;
1781                     case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1782                     case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1783                     case VLC_FOURCC( 't', 'w', 'o', 's' ):
1784                     case VLC_FOURCC( 's', 'o', 'w', 't' ):
1785                         /* What would be the fun if you could trust the .mov */
1786                         p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1787                         break;
1788                     default:
1789                         break;
1790                 }
1791
1792             }
1793             else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1794             {
1795                 p_soun->i_qt_version = 0;
1796             }
1797         }
1798         else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1799         {
1800             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1801
1802             switch( p_sample->i_type )
1803             {
1804                 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1805                 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1806                     {
1807                         if( p_track->i_sample_size > 1 )
1808                             p_soun->i_qt_version = 0;
1809                         break;
1810                     }
1811                 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1812                 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1813                 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
1814                     p_soun->i_qt_version = 0;
1815                     break;
1816                 default:
1817                     break;
1818             }
1819         }
1820
1821         if( p_track->i_sample_size != 0 &&
1822                 p_sample->data.p_sample_soun->i_qt_version == 1 &&
1823                 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
1824         {
1825             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
1826             p_sample->data.p_sample_soun->i_qt_version = 0;
1827         }
1828         break;
1829
1830     default:
1831         break;
1832     }
1833
1834
1835     /* It's a little ugly but .. there are special cases */
1836     switch( p_sample->i_type )
1837     {
1838         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1839         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1840         {
1841             p_track->fmt.i_codec = VLC_CODEC_MPGA;
1842             break;
1843         }
1844         case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1845         {
1846             MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
1847
1848             p_track->fmt.i_codec = VLC_CODEC_A52;
1849             if( p_dac3_box )
1850             {
1851                 static const int pi_bitrate[] = {
1852                      32,  40,  48,  56,
1853                      64,  80,  96, 112,
1854                     128, 160, 192, 224,
1855                     256, 320, 384, 448,
1856                     512, 576, 640,
1857                 };
1858                 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
1859                 p_track->fmt.audio.i_channels = 0;
1860                 p_track->fmt.i_bitrate = 0;
1861                 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
1862                     p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
1863                 p_track->fmt.audio.i_bitspersample = 0;
1864             }
1865             break;
1866         }
1867         case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1868         {
1869             p_track->fmt.i_codec = VLC_CODEC_EAC3;
1870             break;
1871         }
1872
1873         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1874         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
1875         {
1876             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1877
1878             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
1879                 p_track->fmt.i_codec = VLC_FOURCC( 'u', '8', ' ', ' ' );
1880             else
1881                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1882
1883             /* Buggy files workaround */
1884             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
1885                 p_sample->data.p_sample_soun->i_sampleratehi) )
1886             {
1887                 MP4_Box_data_sample_soun_t *p_soun =
1888                     p_sample->data.p_sample_soun;
1889
1890                 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
1891                           "(%u), making both equal (report any problem).",
1892                           p_track->i_timescale, p_soun->i_sampleratehi );
1893
1894                 if( p_soun->i_sampleratehi != 0 )
1895                     p_track->i_timescale = p_soun->i_sampleratehi;
1896                 else
1897                     p_soun->i_sampleratehi = p_track->i_timescale;
1898             }
1899             break;
1900         }
1901
1902         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1903             p_track->fmt.i_codec = VLC_CODEC_H263;
1904             break;
1905
1906         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1907         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
1908             p_track->fmt.i_codec = VLC_CODEC_SUBT;
1909             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1910             /* FIXME UTF-8 doesn't work here ? */
1911             if( p_track->b_mac_encoding )
1912                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
1913             else
1914                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
1915             break;
1916
1917         case VLC_FOURCC('y','v','1','2'):
1918             p_track->fmt.i_codec = VLC_CODEC_YV12;
1919             break;
1920         case VLC_FOURCC('y','u','v','2'):
1921             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
1922             break;
1923
1924         case VLC_FOURCC('i','n','2','4'):
1925             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1926                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
1927             break;
1928         case VLC_FOURCC('f','l','3','2'):
1929             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1930                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
1931             break;
1932         case VLC_FOURCC('f','l','6','4'):
1933             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1934                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
1935             break;
1936         case VLC_FOURCC( 'l', 'p', 'c', 'm' ):
1937         {
1938             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1939             if( p_soun->i_qt_version == 2 &&
1940                 p_soun->i_qt_description > 20 + 28 )
1941             {
1942                 /* Flags:
1943                  *  0x01: IsFloat
1944                  *  0x02: IsBigEndian
1945                  *  0x04: IsSigned
1946                  */
1947                 static const struct {
1948                     unsigned     i_flags;
1949                     unsigned     i_mask;
1950                     unsigned     i_bits;
1951                     vlc_fourcc_t i_codec;
1952                 } p_formats[] = {
1953                     { 0x01,           0x03, 32, VLC_CODEC_F32L },
1954                     { 0x01,           0x03, 64, VLC_CODEC_F64L },
1955                     { 0x01|0x02,      0x03, 32, VLC_CODEC_F32B },
1956                     { 0x01|0x02,      0x03, 64, VLC_CODEC_F64B },
1957
1958                     { 0x00,           0x05,  8, VLC_CODEC_U8 },
1959                     { 0x00|     0x04, 0x05,  8, VLC_CODEC_S8 },
1960
1961                     { 0x00,           0x07, 16, VLC_CODEC_U16L },
1962                     { 0x00|0x02,      0x07, 16, VLC_CODEC_U16B },
1963                     { 0x00     |0x04, 0x07, 16, VLC_CODEC_S16L },
1964                     { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
1965
1966                     { 0x00,           0x07, 24, VLC_CODEC_U24L },
1967                     { 0x00|0x02,      0x07, 24, VLC_CODEC_U24B },
1968                     { 0x00     |0x04, 0x07, 24, VLC_CODEC_S24L },
1969                     { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
1970
1971                     { 0x00,           0x07, 32, VLC_CODEC_U32L },
1972                     { 0x00|0x02,      0x07, 32, VLC_CODEC_U32B },
1973                     { 0x00     |0x04, 0x07, 32, VLC_CODEC_S32L },
1974                     { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
1975
1976                     {0, 0, 0, 0}
1977                 };
1978                 uint32_t i_bits  = GetDWBE(&p_soun->p_qt_description[20 + 20]);
1979                 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
1980
1981                 for( int i = 0; p_formats[i].i_codec; i++ )
1982                 {
1983                     if( p_formats[i].i_bits == i_bits &&
1984                         (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
1985                     {
1986                         p_track->fmt.i_codec = p_formats[i].i_codec;
1987                         p_track->fmt.audio.i_bitspersample = i_bits;
1988                         p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
1989                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
1990
1991                         p_soun->i_qt_version = 0;
1992                         break;
1993                     }
1994                 }
1995             }
1996             break;
1997         }
1998         default:
1999             p_track->fmt.i_codec = p_sample->i_type;
2000             break;
2001     }
2002
2003     /* now see if esds is present and if so create a data packet
2004         with decoder_specific_info  */
2005 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2006     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2007           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2008         ( p_esds->data.p_esds )&&
2009         ( p_decconfig ) )
2010     {
2011         /* First update information based on i_objectTypeIndication */
2012         switch( p_decconfig->i_objectTypeIndication )
2013         {
2014             case( 0x20 ): /* MPEG4 VIDEO */
2015                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2016                 break;
2017             case( 0x21 ): /* H.264 */
2018                 p_track->fmt.i_codec = VLC_CODEC_H264;
2019                 break;
2020             case( 0x40):
2021                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2022                 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2023                      p_decconfig->p_decoder_specific_info[0]       == 0xF8 &&
2024                     (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2025                 {
2026                     p_track->fmt.i_codec = VLC_CODEC_ALS;
2027                 }
2028                 break;
2029             case( 0x60):
2030             case( 0x61):
2031             case( 0x62):
2032             case( 0x63):
2033             case( 0x64):
2034             case( 0x65): /* MPEG2 video */
2035                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2036                 break;
2037             /* Theses are MPEG2-AAC */
2038             case( 0x66): /* main profile */
2039             case( 0x67): /* Low complexity profile */
2040             case( 0x68): /* Scaleable Sampling rate profile */
2041                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2042                 break;
2043             /* True MPEG 2 audio */
2044             case( 0x69):
2045                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2046                 break;
2047             case( 0x6a): /* MPEG1 video */
2048                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2049                 break;
2050             case( 0x6b): /* MPEG1 audio */
2051                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2052                 break;
2053             case( 0x6c ): /* jpeg */
2054                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
2055                 break;
2056             case( 0x6d ): /* png */
2057                 p_track->fmt.i_codec = VLC_FOURCC( 'p','n','g',' ' );
2058                 break;
2059             case( 0x6e ): /* jpeg2000 */
2060                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2061                 break;
2062             case( 0xa3 ): /* vc1 */
2063                 p_track->fmt.i_codec = VLC_CODEC_VC1;
2064                 break;
2065             case( 0xa4 ):
2066                 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2067                 break;
2068             case( 0xa5 ):
2069                 p_track->fmt.i_codec = VLC_CODEC_A52;
2070                 break;
2071             case( 0xa6 ):
2072                 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2073                 break;
2074             case( 0xa9 ): /* dts */
2075             case( 0xaa ): /* DTS-HD HRA */
2076             case( 0xab ): /* DTS-HD Master Audio */
2077                 p_track->fmt.i_codec = VLC_CODEC_DTS;
2078                 break;
2079             case( 0xDD ):
2080                 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2081                 break;
2082
2083             /* Private ID */
2084             case( 0xe0 ): /* NeroDigital: dvd subs */
2085                 if( p_track->fmt.i_cat == SPU_ES )
2086                 {
2087                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
2088                     if( p_track->i_width > 0 )
2089                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2090                     if( p_track->i_height > 0 )
2091                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2092                     break;
2093                 }
2094             case( 0xe1 ): /* QCelp for 3gp */
2095                 if( p_track->fmt.i_cat == AUDIO_ES )
2096                 {
2097                     p_track->fmt.i_codec = VLC_FOURCC( 'Q','c','l','p' );
2098                 }
2099                 break;
2100
2101             /* Fallback */
2102             default:
2103                 /* Unknown entry, but don't touch i_fourcc */
2104                 msg_Warn( p_demux,
2105                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2106                           p_decconfig->i_objectTypeIndication,
2107                           p_track->i_track_ID );
2108                 break;
2109         }
2110         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2111         if( p_track->fmt.i_extra > 0 )
2112         {
2113             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2114             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2115                     p_track->fmt.i_extra );
2116         }
2117     }
2118     else
2119     {
2120         switch( p_sample->i_type )
2121         {
2122             /* qt decoder, send the complete chunk */
2123             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2124             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2125             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2126             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2127             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2128             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2129             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2130             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2131             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2132             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2133             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2134             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2135                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
2136                 break;
2137             /* qt decoder, send the complete chunk */
2138             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
2139             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
2140             case VLC_FOURCC( 'V', 'P', '3', '1' ):
2141             case VLC_FOURCC( '3', 'I', 'V', '1' ):
2142             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2143                 p_track->fmt.i_extra =
2144                     p_sample->data.p_sample_vide->i_qt_image_description;
2145                 if( p_track->fmt.i_extra > 0 )
2146                 {
2147                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2148                     memcpy( p_track->fmt.p_extra,
2149                             p_sample->data.p_sample_vide->p_qt_image_description,
2150                             p_track->fmt.i_extra);
2151                 }
2152                 break;
2153
2154             case VLC_CODEC_AMR_NB:
2155                 p_track->fmt.audio.i_rate = 8000;
2156                 break;
2157             case VLC_CODEC_AMR_WB:
2158                 p_track->fmt.audio.i_rate = 16000;
2159                 break;
2160             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2161             case VLC_CODEC_QDM2:
2162             case VLC_CODEC_ALAC:
2163                 p_track->fmt.i_extra =
2164                     p_sample->data.p_sample_soun->i_qt_description;
2165                 if( p_track->fmt.i_extra > 0 )
2166                 {
2167                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2168                     memcpy( p_track->fmt.p_extra,
2169                             p_sample->data.p_sample_soun->p_qt_description,
2170                             p_track->fmt.i_extra);
2171                 }
2172                 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2173                 {
2174                     p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2175                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2176                 }
2177                 break;
2178
2179             case VLC_FOURCC( 'v', 'c', '-', '1' ):
2180             {
2181                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2182                 if( p_dvc1 )
2183                 {
2184                     p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2185                     if( p_track->fmt.i_extra > 0 )
2186                     {
2187                         p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2188                         memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2189                                 p_track->fmt.i_extra );
2190                     }
2191                 }
2192                 else
2193                 {
2194                     msg_Err( p_demux, "missing dvc1" );
2195                 }
2196                 break;
2197             }
2198
2199             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2200             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2201             {
2202                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2203
2204                 if( p_avcC )
2205                 {
2206                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2207                     if( p_track->fmt.i_extra > 0 )
2208                     {
2209                         p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2210                         memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2211                                 p_track->fmt.i_extra );
2212                     }
2213                 }
2214                 else
2215                 {
2216                     msg_Err( p_demux, "missing avcC" );
2217                 }
2218                 break;
2219             }
2220             case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2221             {
2222                 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2223
2224                 if( p_hvcC )
2225                 {
2226                     p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2227                     if( p_track->fmt.i_extra > 0 )
2228                     {
2229                         p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2230                         memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2231                                 p_track->fmt.i_extra );
2232                     }
2233                     p_track->fmt.i_codec = VLC_CODEC_HEVC;
2234                 }
2235                 else
2236                 {
2237                     msg_Err( p_demux, "missing hvcC" );
2238                 }
2239                 break;
2240             }
2241
2242
2243             case VLC_CODEC_ADPCM_MS:
2244             case VLC_CODEC_ADPCM_IMA_WAV:
2245             case VLC_CODEC_QCELP:
2246                 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2247                 break;
2248
2249             default:
2250                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2251                 break;
2252         }
2253     }
2254
2255 #undef p_decconfig
2256
2257     if( pp_es )
2258         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2259
2260     return VLC_SUCCESS;
2261 }
2262
2263 /* given a time it return sample/chunk
2264  * it also update elst field of the track
2265  */
2266 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2267                                    int64_t i_start, uint32_t *pi_chunk,
2268                                    uint32_t *pi_sample )
2269 {
2270     demux_sys_t *p_sys = p_demux->p_sys;
2271     MP4_Box_t   *p_box_stss;
2272     uint64_t     i_dts;
2273     unsigned int i_sample;
2274     unsigned int i_chunk;
2275     int          i_index;
2276
2277     /* FIXME see if it's needed to check p_track->i_chunk_count */
2278     if( p_track->i_chunk_count == 0 )
2279         return( VLC_EGENERIC );
2280
2281     /* handle elst (find the correct one) */
2282     MP4_TrackSetELST( p_demux, p_track, i_start );
2283     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2284     {
2285         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2286         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
2287
2288         /* now calculate i_start for this elst */
2289         /* offset */
2290         i_start -= p_track->i_elst_time * INT64_C(1000000) / p_sys->i_timescale;
2291         if( i_start < 0 )
2292         {
2293             *pi_chunk = 0;
2294             *pi_sample= 0;
2295
2296             return VLC_SUCCESS;
2297         }
2298         /* to track time scale */
2299         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
2300         /* add elst offset */
2301         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2302              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2303             elst->i_media_time[p_track->i_elst] > 0 )
2304         {
2305             i_start += elst->i_media_time[p_track->i_elst];
2306         }
2307
2308         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2309                  "ms (track)", p_track->i_elst,
2310                  i_mvt * 1000 / p_sys->i_timescale,
2311                  i_start * 1000 / p_track->i_timescale );
2312     }
2313     else
2314     {
2315         /* convert absolute time to in timescale unit */
2316         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
2317     }
2318
2319     /* we start from sample 0/chunk 0, hope it won't take too much time */
2320     /* *** find good chunk *** */
2321     for( i_chunk = 0; ; i_chunk++ )
2322     {
2323         if( i_chunk + 1 >= p_track->i_chunk_count )
2324         {
2325             /* at the end and can't check if i_start in this chunk,
2326                it will be check while searching i_sample */
2327             i_chunk = p_track->i_chunk_count - 1;
2328             break;
2329         }
2330
2331         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2332             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
2333         {
2334             break;
2335         }
2336     }
2337
2338     /* *** find sample in the chunk *** */
2339     i_sample = p_track->chunk[i_chunk].i_sample_first;
2340     i_dts    = p_track->chunk[i_chunk].i_first_dts;
2341     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2342     {
2343         if( i_dts +
2344             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2345             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2346         {
2347             i_dts    +=
2348                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2349                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2350
2351             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2352             i_index++;
2353         }
2354         else
2355         {
2356             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2357             {
2358                 break;
2359             }
2360             i_sample += ( i_start - i_dts ) /
2361                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2362             break;
2363         }
2364     }
2365
2366     if( i_sample >= p_track->i_sample_count )
2367     {
2368         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2369                   "(seeking too far) chunk=%d sample=%d",
2370                   p_track->i_track_ID, i_chunk, i_sample );
2371         return( VLC_EGENERIC );
2372     }
2373
2374
2375     /* *** Try to find nearest sync points *** */
2376     if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2377     {
2378         MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2379         msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2380                  p_track->i_track_ID );
2381         for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2382         {
2383             if( i_index >= p_stss->i_entry_count - 1 ||
2384                 i_sample < p_stss->i_sample_number[i_index+1] )
2385             {
2386                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2387                 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2388                          i_sample, i_sync_sample );
2389
2390                 if( i_sync_sample <= i_sample )
2391                 {
2392                     while( i_chunk > 0 &&
2393                            i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2394                         i_chunk--;
2395                 }
2396                 else
2397                 {
2398                     while( i_chunk < p_track->i_chunk_count - 1 &&
2399                            i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2400                                             p_track->chunk[i_chunk].i_sample_count )
2401                         i_chunk++;
2402                 }
2403                 i_sample = i_sync_sample;
2404                 break;
2405             }
2406         }
2407     }
2408     else
2409     {
2410         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2411                  "Sample Box (stss)", p_track->i_track_ID );
2412     }
2413
2414     *pi_chunk  = i_chunk;
2415     *pi_sample = i_sample;
2416
2417     return VLC_SUCCESS;
2418 }
2419
2420 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2421                                  unsigned int i_chunk, unsigned int i_sample )
2422 {
2423     bool b_reselect = false;
2424
2425     /* now see if actual es is ok */
2426     if( p_track->i_chunk >= p_track->i_chunk_count ||
2427         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2428             p_track->chunk[i_chunk].i_sample_description_index )
2429     {
2430         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2431                   p_track->i_track_ID );
2432
2433         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2434                         p_track->p_es, &b_reselect );
2435
2436         es_out_Del( p_demux->out, p_track->p_es );
2437
2438         p_track->p_es = NULL;
2439
2440         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2441         {
2442             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2443                      p_track->i_track_ID );
2444
2445             p_track->b_ok       = false;
2446             p_track->b_selected = false;
2447             return VLC_EGENERIC;
2448         }
2449     }
2450
2451     /* select again the new decoder */
2452     if( b_reselect )
2453     {
2454         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2455     }
2456
2457     p_track->i_chunk    = i_chunk;
2458     p_track->i_sample   = i_sample;
2459
2460     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2461 }
2462
2463 /****************************************************************************
2464  * MP4_TrackCreate:
2465  ****************************************************************************
2466  * Parse track information and create all needed data to run a track
2467  * If it succeed b_ok is set to 1 else to 0
2468  ****************************************************************************/
2469 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2470                              MP4_Box_t *p_box_trak,
2471                              bool b_force_enable )
2472 {
2473     demux_sys_t *p_sys = p_demux->p_sys;
2474
2475     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2476     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2477     MP4_Box_t *p_elst;
2478
2479     MP4_Box_t *p_mdhd;
2480     MP4_Box_t *p_udta;
2481     MP4_Box_t *p_hdlr;
2482
2483     MP4_Box_t *p_vmhd;
2484     MP4_Box_t *p_smhd;
2485
2486     char language[4] = { '\0' };
2487
2488     /* hint track unsupported */
2489
2490     /* set default value (-> track unusable) */
2491     p_track->b_ok       = false;
2492     p_track->b_enable   = false;
2493     p_track->b_selected = false;
2494     p_track->b_chapter  = false;
2495     p_track->b_mac_encoding = false;
2496
2497     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2498
2499     if( !p_tkhd )
2500     {
2501         return;
2502     }
2503
2504     /* do we launch this track by default ? */
2505     p_track->b_enable =
2506         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2507     if( !p_track->b_enable )
2508         p_track->fmt.i_priority = -1;
2509
2510     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2511
2512     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
2513     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
2514     p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2515
2516     if( p_tref )
2517     {
2518 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2519     }
2520
2521     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2522     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2523
2524     if( ( !p_mdhd )||( !p_hdlr ) )
2525     {
2526         return;
2527     }
2528
2529     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2530     if( p_track->i_timescale == 0 )
2531         return;
2532
2533     if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2534     {
2535         strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2536         p_track->b_mac_encoding = true;
2537     }
2538     else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2539         p_track->b_mac_encoding = true;
2540     else
2541     {
2542         for( unsigned i = 0; i < 3; i++ )
2543             language[i] = p_mdhd->data.p_mdhd->i_language[i];
2544         language[3] = '\0';
2545     }
2546
2547     switch( p_hdlr->data.p_hdlr->i_handler_type )
2548     {
2549         case( ATOM_soun ):
2550             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2551             {
2552                 return;
2553             }
2554             p_track->fmt.i_cat = AUDIO_ES;
2555             break;
2556
2557         case( ATOM_vide ):
2558             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2559             {
2560                 return;
2561             }
2562             p_track->fmt.i_cat = VIDEO_ES;
2563             break;
2564
2565         case( ATOM_text ):
2566         case( ATOM_subp ):
2567         case( ATOM_tx3g ):
2568         case( ATOM_sbtl ):
2569             p_track->fmt.i_cat = SPU_ES;
2570             break;
2571
2572         default:
2573             return;
2574     }
2575
2576     p_track->i_elst = 0;
2577     p_track->i_elst_time = 0;
2578     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2579     {
2580         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2581         unsigned int i;
2582
2583         msg_Warn( p_demux, "elst box found" );
2584         for( i = 0; i < elst->i_entry_count; i++ )
2585         {
2586             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
2587                      "ms) rate=%d.%d", i,
2588                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2589                      elst->i_media_time[i] >= 0 ?
2590                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2591                      INT64_C(-1),
2592                      elst->i_media_rate_integer[i],
2593                      elst->i_media_rate_fraction[i] );
2594         }
2595     }
2596
2597
2598 /*  TODO
2599     add support for:
2600     p_dinf = MP4_BoxGet( p_minf, "dinf" );
2601 */
2602     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2603         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2604     {
2605         return;
2606     }
2607
2608     /* Set language */
2609     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2610     {
2611         p_track->fmt.psz_language = strdup( language );
2612     }
2613
2614     p_udta = MP4_BoxGet( p_box_trak, "udta" );
2615     if( p_udta )
2616     {
2617         MP4_Box_t *p_box_iter;
2618         for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2619                  p_box_iter = p_box_iter->p_next )
2620         {
2621             switch( p_box_iter->i_type )
2622             {
2623                 case ATOM_0xa9nam:
2624                     p_track->fmt.psz_description =
2625                         strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2626                     break;
2627                 case ATOM_name:
2628                     p_track->fmt.psz_description =
2629                         strdup( p_box_iter->data.p_name->psz_text );
2630                     break;
2631             }
2632         }
2633     }
2634
2635     /* Create chunk index table and sample index table */
2636     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
2637         TrackCreateSamplesIndex( p_demux, p_track ) )
2638     {
2639         return; /* cannot create chunks index */
2640     }
2641
2642     p_track->i_chunk  = 0;
2643     p_track->i_sample = 0;
2644
2645     /* Mark chapter only track */
2646     if( p_sys->p_tref_chap )
2647     {
2648         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2649         unsigned int i;
2650
2651         for( i = 0; i < p_chap->i_entry_count; i++ )
2652         {
2653             if( p_track->i_track_ID == p_chap->i_track_ID[i] )
2654             {
2655                 p_track->b_chapter = true;
2656                 p_track->b_enable = false;
2657                 break;
2658             }
2659         }
2660     }
2661
2662     /* now create es */
2663     if( b_force_enable &&
2664         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2665     {
2666         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2667                   p_track->i_track_ID );
2668         p_track->b_enable = true;
2669         p_track->fmt.i_priority = 0;
2670     }
2671
2672     p_track->p_es = NULL;
2673     if( TrackCreateES( p_demux,
2674                        p_track, p_track->i_chunk,
2675                        p_track->b_chapter ? NULL : &p_track->p_es ) )
2676     {
2677         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2678                  p_track->i_track_ID );
2679         return;
2680     }
2681     p_track->b_ok = true;
2682 #if 0
2683     {
2684         int i;
2685         for( i = 0; i < p_track->i_chunk_count; i++ )
2686         {
2687             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2688                      i, p_track->chunk[i].i_sample_count,
2689                      p_track->chunk[i].i_first_dts );
2690
2691         }
2692     }
2693 #endif
2694 }
2695
2696 static void FreeAndResetChunk( mp4_chunk_t *ck )
2697 {
2698     free( ck->p_sample_count_dts );
2699     free( ck->p_sample_delta_dts );
2700     free( ck->p_sample_count_pts );
2701     free( ck->p_sample_offset_pts );
2702     free( ck->p_sample_size );
2703     for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2704         free( ck->p_sample_data[i] );
2705     free( ck->p_sample_data );
2706     memset( ck, 0, sizeof( mp4_chunk_t ) );
2707 }
2708
2709 /****************************************************************************
2710  * MP4_TrackDestroy:
2711  ****************************************************************************
2712  * Destroy a track created by MP4_TrackCreate.
2713  ****************************************************************************/
2714 static void MP4_TrackDestroy( mp4_track_t *p_track )
2715 {
2716     unsigned int i_chunk;
2717
2718     p_track->b_ok = false;
2719     p_track->b_enable   = false;
2720     p_track->b_selected = false;
2721
2722     es_format_Clean( &p_track->fmt );
2723
2724     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2725     {
2726         if( p_track->chunk )
2727         {
2728            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2729            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2730
2731            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2732            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2733         }
2734     }
2735     FREENULL( p_track->chunk );
2736     if( p_track->cchunk ) {
2737         FreeAndResetChunk( p_track->cchunk );
2738         FREENULL( p_track->cchunk );
2739     }
2740
2741     if( !p_track->i_sample_size )
2742     {
2743         FREENULL( p_track->p_sample_size );
2744     }
2745 }
2746
2747 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2748                             mtime_t i_start )
2749 {
2750     if( !p_track->b_ok || p_track->b_chapter )
2751     {
2752         return VLC_EGENERIC;
2753     }
2754
2755     if( p_track->b_selected )
2756     {
2757         msg_Warn( p_demux, "track[Id 0x%x] already selected",
2758                   p_track->i_track_ID );
2759         return VLC_SUCCESS;
2760     }
2761
2762     return MP4_TrackSeek( p_demux, p_track, i_start );
2763 }
2764
2765 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2766 {
2767     if( !p_track->b_ok || p_track->b_chapter )
2768     {
2769         return;
2770     }
2771
2772     if( !p_track->b_selected )
2773     {
2774         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2775                   p_track->i_track_ID );
2776         return;
2777     }
2778     if( p_track->p_es )
2779     {
2780         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2781                         p_track->p_es, false );
2782     }
2783
2784     p_track->b_selected = false;
2785 }
2786
2787 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2788                           mtime_t i_start )
2789 {
2790     uint32_t i_chunk;
2791     uint32_t i_sample;
2792
2793     if( !p_track->b_ok || p_track->b_chapter )
2794         return VLC_EGENERIC;
2795
2796     p_track->b_selected = false;
2797
2798     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2799                                 &i_chunk, &i_sample ) )
2800     {
2801         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2802                   p_track->i_track_ID );
2803         return VLC_EGENERIC;
2804     }
2805
2806     p_track->b_selected = true;
2807
2808     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
2809         p_track->b_selected = true;
2810
2811     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2812 }
2813
2814
2815 /*
2816  * 3 types: for audio
2817  *
2818  */
2819 #define QT_V0_MAX_SAMPLES 1024
2820 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2821 {
2822     int i_size;
2823     MP4_Box_data_sample_soun_t *p_soun;
2824
2825     if( p_track->i_sample_size == 0 )
2826     {
2827         /* most simple case */
2828         return p_track->p_sample_size[p_track->i_sample];
2829     }
2830     if( p_track->fmt.i_cat != AUDIO_ES )
2831     {
2832         return p_track->i_sample_size;
2833     }
2834
2835     p_soun = p_track->p_sample->data.p_sample_soun;
2836
2837     if( p_soun->i_qt_version == 1 )
2838     {
2839         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
2840         if( p_track->fmt.audio.i_blockalign > 1 )
2841             i_samples = p_soun->i_sample_per_packet;
2842
2843         i_size = i_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2844     }
2845     else if( p_track->i_sample_size > 256 )
2846     {
2847         /* We do that so we don't read too much data
2848          * (in this case we are likely dealing with compressed data) */
2849         i_size = p_track->i_sample_size;
2850     }
2851     else
2852     {
2853         /* Read a bunch of samples at once */
2854         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2855             ( p_track->i_sample -
2856               p_track->chunk[p_track->i_chunk].i_sample_first );
2857
2858         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2859         i_size = i_samples * p_track->i_sample_size;
2860     }
2861
2862     //fprintf( stderr, "size=%d\n", i_size );
2863     return i_size;
2864 }
2865
2866 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2867 {
2868     unsigned int i_sample;
2869     uint64_t i_pos;
2870
2871     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2872
2873     if( p_track->i_sample_size )
2874     {
2875         MP4_Box_data_sample_soun_t *p_soun =
2876             p_track->p_sample->data.p_sample_soun;
2877
2878         if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
2879         {
2880             i_pos += ( p_track->i_sample -
2881                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2882                      p_track->i_sample_size;
2883         }
2884         else
2885         {
2886             /* we read chunk by chunk unless a blockalign is requested */
2887             if( p_track->fmt.audio.i_blockalign > 1 )
2888                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
2889                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2890         }
2891     }
2892     else
2893     {
2894         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2895              i_sample < p_track->i_sample; i_sample++ )
2896         {
2897             i_pos += p_track->p_sample_size[i_sample];
2898         }
2899     }
2900
2901     return i_pos;
2902 }
2903
2904 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2905 {
2906     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2907     {
2908         MP4_Box_data_sample_soun_t *p_soun;
2909
2910         p_soun = p_track->p_sample->data.p_sample_soun;
2911
2912         if( p_soun->i_qt_version == 1 )
2913         {
2914             /* we read chunk by chunk unless a blockalign is requested */
2915             if( p_track->fmt.audio.i_blockalign > 1 )
2916                 p_track->i_sample += p_soun->i_sample_per_packet;
2917             else
2918                 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
2919         }
2920         else if( p_track->i_sample_size > 256 )
2921         {
2922             /* We do that so we don't read too much data
2923              * (in this case we are likely dealing with compressed data) */
2924             p_track->i_sample += 1;
2925         }
2926         else
2927         {
2928             /* FIXME */
2929             p_track->i_sample += QT_V0_MAX_SAMPLES;
2930             if( p_track->i_sample >
2931                 p_track->chunk[p_track->i_chunk].i_sample_first +
2932                 p_track->chunk[p_track->i_chunk].i_sample_count )
2933             {
2934                 p_track->i_sample =
2935                     p_track->chunk[p_track->i_chunk].i_sample_first +
2936                     p_track->chunk[p_track->i_chunk].i_sample_count;
2937             }
2938         }
2939     }
2940     else
2941     {
2942         p_track->i_sample++;
2943     }
2944
2945     if( p_track->i_sample >= p_track->i_sample_count )
2946         return VLC_EGENERIC;
2947
2948     /* Have we changed chunk ? */
2949     if( p_track->i_sample >=
2950             p_track->chunk[p_track->i_chunk].i_sample_first +
2951             p_track->chunk[p_track->i_chunk].i_sample_count )
2952     {
2953         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2954                                   p_track->i_sample ) )
2955         {
2956             msg_Warn( p_demux, "track[0x%x] will be disabled "
2957                       "(cannot restart decoder)", p_track->i_track_ID );
2958             MP4_TrackUnselect( p_demux, p_track );
2959             return VLC_EGENERIC;
2960         }
2961     }
2962
2963     /* Have we changed elst */
2964     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2965     {
2966         demux_sys_t *p_sys = p_demux->p_sys;
2967         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2968         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2969                         p_sys->i_timescale / (int64_t)1000000;
2970
2971         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
2972             i_mvt >= p_track->i_elst_time +
2973                      elst->i_segment_duration[p_track->i_elst] )
2974         {
2975             MP4_TrackSetELST( p_demux, p_track,
2976                               MP4_TrackGetDTS( p_demux, p_track ) );
2977         }
2978     }
2979
2980     return VLC_SUCCESS;
2981 }
2982
2983 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2984                               int64_t i_time )
2985 {
2986     demux_sys_t *p_sys = p_demux->p_sys;
2987     int         i_elst_last = tk->i_elst;
2988
2989     /* handle elst (find the correct one) */
2990     tk->i_elst      = 0;
2991     tk->i_elst_time = 0;
2992     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2993     {
2994         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2995         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2996
2997         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2998         {
2999             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3000
3001             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3002             {
3003                 break;
3004             }
3005             tk->i_elst_time += i_dur;
3006         }
3007
3008         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3009         {
3010             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3011             tk->i_elst = elst->i_entry_count - 1;
3012             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3013         }
3014
3015         if( elst->i_media_time[tk->i_elst] < 0 )
3016         {
3017             /* track offset */
3018             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3019         }
3020     }
3021     if( i_elst_last != tk->i_elst )
3022     {
3023         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3024     }
3025 }
3026
3027 /* */
3028 static const char *MP4_ConvertMacCode( uint16_t i_code )
3029 {
3030     static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3031         { "en",   0 }, { "fr",   1 }, { "de",   2 }, { "it",   3 }, { "nl",   4 },
3032         { "sv",   5 }, { "es",   6 }, { "da",   7 }, { "pt",   8 }, { "no",   9 },
3033         { "he",  10 }, { "ja",  11 }, { "ar",  12 }, { "fi",  13 }, { "el",  14 },
3034         { "is",  15 }, { "mt",  16 }, { "tr",  17 }, { "hr",  18 }, { "zh",  19 },
3035         { "ur",  20 }, { "hi",  21 }, { "th",  22 }, { "ko",  23 }, { "lt",  24 },
3036         { "pl",  25 }, { "hu",  26 }, { "et",  27 }, { "lv",  28 }, //{ "??",  29 },
3037         { "fo",  30 }, { "fa",  31 }, { "ru",  32 }, { "zh",  33 }, { "nl",  34 },
3038         { "ga",  35 }, { "sq",  36 }, { "ro",  37 }, { "cs",  38 }, { "sk",  39 },
3039         { "sl",  40 }, { "yi",  41 }, { "sr",  42 }, { "mk",  43 }, { "bg",  44 },
3040         { "uk",  45 }, { "be",  46 }, { "uz",  47 }, { "az",  48 }, { "kk",  48 },
3041         { "az",  50 }, { "hy",  51 }, { "ka",  52 }, { "mo",  53 }, { "ky",  54 },
3042         { "tg",  55 }, { "tk",  56 }, { "mn",  57 }, { "mn",  58 }, { "ps",  59 },
3043         { "ku",  60 }, { "ks",  61 }, { "sd",  62 }, { "bo",  63 }, { "ne",  64 },
3044         { "sa",  65 }, { "mr",  66 }, { "bn",  67 }, { "as",  68 }, { "gu",  69 },
3045         { "pa",  70 }, { "or",  71 }, { "ml",  72 }, { "kn",  73 }, { "ta",  74 },
3046         { "te",  75 }, { "si",  76 }, { "my",  77 }, { "km",  78 }, { "lo",  79 },
3047         { "vi",  80 }, { "id",  81 }, { "tl",  82 }, { "ms",  83 }, { "ms",  84 },
3048         { "am",  85 }, { "ti",  86 }, { "om",  87 }, { "so",  88 }, { "sw",  89 },
3049         { "rw",  90 }, { "rn",  91 }, { "ny",  92 }, { "mg",  93 }, { "eo",  94 },
3050
3051                                                      { "cy", 128 }, { "eu", 129 },
3052         { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3053         { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3054         { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3055         { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3056         /* */
3057         { "", 0 }
3058     };
3059     int i;
3060     for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3061     {
3062         if( p_cvt[i].i_code == i_code )
3063             return p_cvt[i].psz_iso639_1;
3064     }
3065     return "";
3066 }
3067
3068 /******************************************************************************
3069  *     Here are the functions used for fragmented MP4
3070  *****************************************************************************/
3071
3072 /**
3073  * It computes the sample rate for a video track using current video chunk
3074  */
3075 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3076                                   const mp4_track_t *p_track )
3077 {
3078     if( p_track->cchunk->i_last_dts == 0 )
3079         return;
3080
3081     *pi_num = 0;
3082     *pi_den = 0;
3083
3084     /* */
3085     const mp4_chunk_t *p_chunk = p_track->cchunk;
3086
3087     uint32_t i_sample = p_chunk->i_sample_count;
3088     uint64_t i_first_dts = p_chunk->i_first_dts;
3089     uint64_t i_last_dts =  p_chunk->i_last_dts;
3090
3091     if( i_sample > 1 && i_first_dts < i_last_dts )
3092         vlc_ureduce( pi_num, pi_den,
3093                      ( i_sample - 1) *  p_track->i_timescale,
3094                      i_last_dts - i_first_dts,
3095                      UINT16_MAX);
3096 }
3097
3098 /**
3099  * Build raw avcC box (without the 8 bytes header)
3100  * \return The size of the box.
3101  */
3102 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3103                                                        const unsigned cpd_len )
3104 {
3105     uint8_t *avcC;
3106     unsigned sps_len = 0, pps_len = 0;
3107     const uint32_t mark = 0x00000001;
3108
3109     assert( CodecPrivateData[0] == 0 );
3110     assert( CodecPrivateData[1] == 0 );
3111     assert( CodecPrivateData[2] == 0 );
3112     assert( CodecPrivateData[3] == 1 );
3113
3114     uint32_t length = cpd_len + 3;
3115     avcC = calloc( length, 1 );
3116     if( unlikely( avcC == NULL ) )
3117         return 0;
3118
3119     uint8_t *sps = avcC + 8;
3120
3121     uint32_t candidate = ~mark;
3122     CodecPrivateData += 4;
3123     for( unsigned i = 0; i < cpd_len - 4; i++ )
3124     {
3125         sps[i] = CodecPrivateData[i];
3126         candidate = (candidate << 8) | CodecPrivateData[i];
3127         if( candidate == mark )
3128         {
3129             sps_len = i - 3;
3130             break;
3131         }
3132     }
3133     if( sps_len == 0 )
3134         return 0;
3135     uint8_t *pps = sps + sps_len + 3;
3136     pps_len = cpd_len - sps_len - 4 * 2;
3137     memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3138
3139     /* XXX */
3140     uint8_t AVCProfileIndication = 0x64;
3141     uint8_t profile_compatibility = 0x40;
3142     uint8_t AVCLevelIndication = 0x1f;
3143     uint8_t lengthSizeMinusOne = 0x03;
3144
3145     avcC[0] = 1;
3146     avcC[1] = AVCProfileIndication;
3147     avcC[2] = profile_compatibility;
3148     avcC[3] = AVCLevelIndication;
3149     avcC[4] = 0xfc + lengthSizeMinusOne;
3150     avcC[5] = 0xe0 + 1;
3151     avcC[6] = (sps_len & 0xff00)>>8;
3152     avcC[7] = sps_len & 0xff;
3153
3154     avcC[8+sps_len] = 1;
3155     avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3156     avcC[10+sps_len] = pps_len & 0xff;
3157
3158     *p_extra = avcC;
3159     return length;
3160 }
3161
3162 /**
3163  * Build a mp4_track_t from a StraBox
3164  */
3165
3166 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3167 {
3168     fmt->i_extra = p_data->cpd_len;
3169     fmt->p_extra = malloc( p_data->cpd_len );
3170     if( unlikely( !fmt->p_extra ) )
3171         return VLC_ENOMEM;
3172     memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3173     return VLC_SUCCESS;
3174   }
3175
3176 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3177 {
3178     demux_sys_t *p_sys = p_demux->p_sys;
3179     int ret;
3180     MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3181     if( !p_data )
3182         return VLC_EGENERIC;
3183
3184     p_track->b_ok       = true;
3185     p_track->b_selected = false;
3186     p_track->i_sample_count = UINT32_MAX;
3187
3188     p_track->i_timescale = p_sys->i_timescale;
3189     p_track->i_width = p_data->MaxWidth;
3190     p_track->i_height = p_data->MaxHeight;
3191     p_track->i_track_ID = p_data->i_track_ID;
3192
3193     es_format_t *fmt = &p_track->fmt;
3194     if( fmt == NULL )
3195         return VLC_EGENERIC;
3196
3197     es_format_Init( fmt, p_data->i_es_cat, 0 );
3198
3199     /* Set language FIXME */
3200     fmt->psz_language = strdup( "en" );
3201
3202     fmt->i_original_fourcc = p_data->FourCC;
3203     fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3204
3205     uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3206     /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3207      * for MS weird use of FourCC*/
3208     switch( fmt->i_cat )
3209     {
3210         case VIDEO_ES:
3211             if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3212                 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3213                 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3214             {
3215                 fmt->i_extra = build_raw_avcC( p_extra,
3216                         p_data->CodecPrivateData, p_data->cpd_len );
3217             }
3218             else
3219             {
3220                 ret = MP4_SetCodecExtraData( fmt, p_data );
3221                 if( ret != VLC_SUCCESS )
3222                     return ret;
3223             }
3224
3225             fmt->video.i_width = p_data->MaxWidth;
3226             fmt->video.i_height = p_data->MaxHeight;
3227             fmt->video.i_bits_per_pixel = 0x18;
3228             fmt->video.i_visible_width = p_data->MaxWidth;
3229             fmt->video.i_visible_height = p_data->MaxHeight;
3230
3231             /* Frame rate */
3232             ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3233                                   &fmt->video.i_frame_rate_base, p_track );
3234
3235             if( fmt->video.i_frame_rate_base != 0 )
3236             {
3237                 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3238                                         (float)fmt->video.i_frame_rate_base;
3239             }
3240             else
3241                 p_demux->p_sys->f_fps = 24;
3242
3243             break;
3244
3245         case AUDIO_ES:
3246             fmt->audio.i_channels = p_data->Channels;
3247             fmt->audio.i_rate = p_data->SamplingRate;
3248             fmt->audio.i_bitspersample = p_data->BitsPerSample;
3249             fmt->audio.i_blockalign = p_data->nBlockAlign;
3250
3251             fmt->i_bitrate = p_data->Bitrate;
3252
3253             ret = MP4_SetCodecExtraData( fmt, p_data );
3254             if( ret != VLC_SUCCESS )
3255                 return ret;
3256
3257             break;
3258
3259         default:
3260             break;
3261     }
3262
3263     return VLC_SUCCESS;
3264 }
3265
3266 /**
3267  * Return the track identified by tid
3268  */
3269 static mp4_track_t *MP4_frg_GetTrack( demux_t *p_demux, const uint32_t tid )
3270 {
3271     demux_sys_t *p_sys = p_demux->p_sys;
3272
3273     mp4_track_t *ret = NULL;
3274     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3275     {
3276         ret = &p_sys->track[i];
3277         if( !ret )
3278             return NULL;
3279         if( ret->i_track_ID == tid )
3280             return ret;
3281     }
3282     msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3283     return NULL;
3284 }
3285
3286 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3287 {
3288     msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3289     mp4_chunk_t *ck = tk->cchunk;
3290     while( ck->i_sample < ck->i_sample_count )
3291     {
3292         block_t *p_block;
3293         int64_t i_delta;
3294
3295         if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3296             return;
3297
3298         uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3299         assert( sample_size > 0 );
3300         p_block = block_Alloc( sample_size );
3301         if( unlikely( !p_block ) )
3302             return;
3303
3304         uint8_t *src = ck->p_sample_data[ck->i_sample];
3305         memcpy( p_block->p_buffer, src, sample_size );
3306         ck->i_sample++;
3307
3308         /* dts */
3309         p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3310         /* pts */
3311         i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3312         if( i_delta != -1 )
3313             p_block->i_pts = p_block->i_dts + i_delta;
3314         else if( tk->fmt.i_cat != VIDEO_ES )
3315             p_block->i_pts = p_block->i_dts;
3316         else
3317             p_block->i_pts = VLC_TS_INVALID;
3318
3319         es_out_Send( p_demux->out, tk->p_es, p_block );
3320
3321         tk->i_sample++;
3322     }
3323 }
3324
3325 /**
3326  * Re-init decoder.
3327  * \Note If we call that function too soon,
3328  * before the track has been selected by MP4_TrackSelect
3329  * (during the first execution of Demux), then the track gets disabled
3330  */
3331 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3332 {
3333     demux_sys_t *p_sys = p_demux->p_sys;
3334
3335     uint32_t i_sample = 0;
3336     bool b_smooth = false;
3337     MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3338
3339     if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3340         b_smooth = true;
3341
3342     if( b_smooth )
3343     {
3344         p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3345         if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3346             return VLC_EGENERIC;
3347     }
3348     else /* DASH */
3349     {
3350         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3351         if( !p_trak )
3352             return VLC_EGENERIC;
3353     }
3354
3355     i_sample = p_track->i_sample;
3356     es_out_Del( p_demux->out, p_track->p_es );
3357     es_format_Clean( &p_track->fmt );
3358
3359     if( b_smooth )
3360         MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3361     else /* DASH */
3362         MP4_TrackCreate( p_demux, p_track, p_trak, true );
3363
3364     p_track->i_sample = i_sample;
3365
3366     /* Temporary hack until we support track selection */
3367     p_track->b_selected = true;
3368     p_track->b_ok = true;
3369     p_track->b_enable = true;
3370
3371     p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3372     p_track->b_codec_need_restart = false;
3373
3374     return VLC_SUCCESS;
3375 }
3376
3377 /**
3378  * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3379  * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3380  * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3381  * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3382  */
3383 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3384 {
3385     MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3386     MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3387     if( p_moof == NULL)
3388     {
3389         msg_Warn( p_demux, "no moof box found!" );
3390         return VLC_EGENERIC;
3391     }
3392
3393     MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3394     if( p_traf == NULL)
3395     {
3396         msg_Warn( p_demux, "no traf box found!" );
3397         return VLC_EGENERIC;
3398     }
3399
3400     MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3401     if( p_tfhd == NULL)
3402     {
3403         msg_Warn( p_demux, "no tfhd box found!" );
3404         return VLC_EGENERIC;
3405     }
3406
3407     uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3408     *i_tk_id = i_track_ID;
3409     assert( i_track_ID > 0 );
3410     msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3411
3412     mp4_track_t *p_track = MP4_frg_GetTrack( p_demux, i_track_ID );
3413     if( !p_track )
3414         return VLC_EGENERIC;
3415
3416     mp4_chunk_t *ret = p_track->cchunk;
3417
3418     if( p_tfhd->data.p_tfhd->b_empty )
3419         msg_Warn( p_demux, "No samples in this chunk!" );
3420
3421     /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3422      * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3423      * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3424      * and so on. Finally, suppose that we get the chunks the other way around,
3425      * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3426      * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3427      * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3428      * flush it, i.e. send to the decoder the samples not yet sent.
3429      * Note that all the samples to be flushed should worth less than 100 ms,
3430      * (though I did not do the formal proof) and thus this flushing mechanism
3431      * should not cause A/V sync issues, or delays or whatever.
3432      */
3433     if( ret->i_sample < ret->i_sample_count )
3434         FlushChunk( p_demux, p_track );
3435
3436     if( ret->i_sample_count )
3437         FreeAndResetChunk( ret );
3438
3439     uint32_t default_duration = 0;
3440     if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3441         default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3442
3443     uint32_t default_size = 0;
3444     if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3445         default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3446
3447     MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3448     if( p_trun == NULL)
3449     {
3450         msg_Warn( p_demux, "no trun box found!" );
3451         return VLC_EGENERIC;
3452     }
3453     MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3454
3455     ret->i_sample_count = p_trun_data->i_sample_count;
3456     assert( ret->i_sample_count > 0 );
3457     ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3458     ret->i_sample_first = p_track->i_sample_first;
3459     p_track->i_sample_first += ret->i_sample_count;
3460
3461     ret->i_first_dts = p_track->i_first_dts;
3462
3463     /* XXX I already saw DASH content with no default_duration and no
3464      * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3465      * This chunk of code might be buggy with segments having
3466      * more than one subsegment. */
3467     if( !default_duration )
3468     {
3469         if( p_sidx )
3470         {
3471             MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3472             assert( p_sidx_data->i_reference_count == 1 );
3473
3474             if( p_sidx_data->i_timescale == 0 )
3475                 return VLC_EGENERIC;
3476
3477             unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3478                                         p_sidx_data->i_timescale;
3479             default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3480
3481         }
3482     }
3483
3484     msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3485
3486     ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3487     ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3488
3489     if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3490         return VLC_ENOMEM;
3491
3492     ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3493     if( !ret->p_sample_count_pts )
3494         return VLC_ENOMEM;
3495
3496     if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3497     {
3498         ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3499         if( !ret->p_sample_offset_pts )
3500             return VLC_ENOMEM;
3501     }
3502
3503     ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3504     if( !ret->p_sample_size )
3505         return VLC_ENOMEM;
3506
3507     ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3508     if( !ret->p_sample_data )
3509         return VLC_ENOMEM;
3510
3511     uint32_t dur = 0, len;
3512     uint32_t chunk_duration = 0, chunk_size = 0;
3513
3514     /* Skip header of mdat */
3515     stream_Read( p_demux->s, NULL, 8 );
3516
3517     for( uint32_t i = 0; i < ret->i_sample_count; i++)
3518     {
3519         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3520             dur = p_trun_data->p_samples[i].i_duration;
3521         else
3522             dur = default_duration;
3523         ret->p_sample_delta_dts[i] = dur;
3524         chunk_duration += dur;
3525
3526         ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3527
3528         if( ret->p_sample_offset_pts )
3529         {
3530             ret->p_sample_offset_pts[i] =
3531                         p_trun_data->p_samples[i].i_composition_time_offset;
3532         }
3533
3534         if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3535             len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3536         else
3537             len = ret->p_sample_size[i] = default_size;
3538
3539         ret->p_sample_data[i] = malloc( len );
3540         if( ret->p_sample_data[i] == NULL )
3541             return VLC_ENOMEM;
3542         int read = stream_Read( p_demux->s, ret->p_sample_data[i], len );
3543         if( read < (int)len )
3544             return VLC_EGENERIC;
3545         chunk_size += len;
3546     }
3547     ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3548     p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3549
3550     if( p_track->b_codec_need_restart &&
3551             p_track->fmt.i_cat == VIDEO_ES )
3552         ReInitDecoder( p_demux, p_track );
3553
3554     p_track->b_has_non_empty_cchunk = true;
3555     return VLC_SUCCESS;
3556 }
3557
3558 /**
3559  * Get the next chunk of the track identified by i_tk_id.
3560  * \Note We don't want to seek all the time, so if the first chunk given by the
3561  * input method doesn't belong to the right track, we don't throw it away,
3562  * and so, in general, this function fetch more than one chunk.
3563  * Not to mention that a new init segment might be put everywhere
3564  * between two chunks by the input method.
3565  */
3566 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3567 {
3568     demux_sys_t *p_sys = p_demux->p_sys;
3569     mp4_track_t *p_track;
3570
3571     for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3572     {
3573         MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3574         if( !p_chunk )
3575             return VLC_EGENERIC;
3576
3577         if( !p_chunk->p_first )
3578             goto MP4_frg_GetChunks_Error;
3579         uint32_t i_type = p_chunk->p_first->i_type;
3580         uint32_t tid = 0;
3581         if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3582         {
3583             MP4_BoxFree( p_demux->s, p_sys->p_root );
3584             p_sys->p_root = p_chunk;
3585
3586             if( i_type == ATOM_ftyp ) /* DASH */
3587             {
3588                 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3589                 if( !p_tkhd )
3590                 {
3591                     msg_Warn( p_demux, "No tkhd found!" );
3592                     goto MP4_frg_GetChunks_Error;
3593                 }
3594                 tid = p_tkhd->data.p_tkhd->i_track_ID;
3595             }
3596             else                      /* Smooth Streaming */
3597             {
3598                 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3599                 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3600                 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3601                 {
3602                     msg_Warn( p_demux, "No StraBox found!" );
3603                     goto MP4_frg_GetChunks_Error;
3604                 }
3605                 tid = p_stra->data.p_stra->i_track_ID;
3606             }
3607
3608             p_track = MP4_frg_GetTrack( p_demux, tid );
3609             if( !p_track )
3610                 goto MP4_frg_GetChunks_Error;
3611             p_track->b_codec_need_restart = true;
3612
3613             return MP4_frg_GetChunks( p_demux, i_tk_id );
3614         }
3615
3616         if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3617             goto MP4_frg_GetChunks_Error;
3618
3619         MP4_BoxFree( p_demux->s, p_chunk );
3620
3621         if( tid == i_tk_id )
3622             break;
3623         else
3624             continue;
3625
3626 MP4_frg_GetChunks_Error:
3627         MP4_BoxFree( p_demux->s, p_chunk );
3628         return VLC_EGENERIC;
3629     }
3630
3631     return VLC_SUCCESS;
3632 }
3633
3634 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3635 {
3636     if( !p_track->b_ok || p_track->b_chapter )
3637     {
3638         return VLC_EGENERIC;
3639     }
3640
3641     if( p_track->b_selected )
3642     {
3643         msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3644         return VLC_SUCCESS;
3645     }
3646
3647     msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3648     p_track->b_selected = true;
3649     return VLC_SUCCESS;
3650 }
3651
3652 /**
3653  * DemuxFrg: read packet and send them to decoders
3654  * \return 1 on success, 0 on error.
3655  * TODO check for newly selected track
3656  */
3657 int DemuxFrg( demux_t *p_demux )
3658 {
3659     demux_sys_t *p_sys = p_demux->p_sys;
3660     unsigned i_track;
3661     unsigned i_track_selected;
3662
3663     /* check for newly selected/unselected track */
3664     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3665     {
3666         mp4_track_t *tk = &p_sys->track[i_track];
3667         bool b;
3668
3669         if( !tk->b_ok || tk->b_chapter )
3670             continue;
3671
3672         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3673         msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3674
3675         if( tk->b_selected && !b )
3676         {
3677             MP4_TrackUnselect( p_demux, tk );
3678         }
3679         else if( !tk->b_selected && b)
3680         {
3681             MP4_frg_TrackSelect( p_demux, tk );
3682         }
3683
3684         if( tk->b_selected )
3685             i_track_selected++;
3686     }
3687
3688     if( i_track_selected <= 0 )
3689     {
3690         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3691         if( p_sys->i_timescale > 0 )
3692         {
3693             int64_t i_length = (mtime_t)1000000 *
3694                                (mtime_t)p_sys->i_duration /
3695                                (mtime_t)p_sys->i_timescale;
3696             if( MP4_GetMoviePTS( p_sys ) >= i_length )
3697                 return 0;
3698             return 1;
3699         }
3700
3701         msg_Warn( p_demux, "no track selected, exiting..." );
3702         return 0;
3703     }
3704
3705     /* first wait for the good time to read a packet */
3706     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3707
3708     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3709
3710     /* we will read 100ms for each stream so ...*/
3711     p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3712
3713     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3714     {
3715         mp4_track_t *tk = &p_sys->track[i_track];
3716
3717         if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3718         {
3719             msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3720             continue;
3721         }
3722
3723         if( !tk->b_has_non_empty_cchunk )
3724         {
3725             if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
3726             {
3727                 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
3728                 return 0;
3729             }
3730         }
3731
3732         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
3733         {
3734             block_t *p_block;
3735             int64_t i_delta;
3736
3737             mp4_chunk_t *ck = tk->cchunk;
3738             if( ck->i_sample >= ck->i_sample_count )
3739             {
3740                 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
3741                                     ck->i_sample, ck->i_sample_count );
3742                 return 0;
3743             }
3744
3745             uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3746             p_block = block_Alloc( sample_size );
3747             uint8_t *src = ck->p_sample_data[ck->i_sample];
3748             memcpy( p_block->p_buffer, src, sample_size );
3749
3750             ck->i_sample++;
3751             if( ck->i_sample == ck->i_sample_count )
3752                 tk->b_has_non_empty_cchunk = false;
3753
3754             /* dts */
3755             p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3756             /* pts */
3757             i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3758             if( i_delta != -1 )
3759                 p_block->i_pts = p_block->i_dts + i_delta;
3760             else if( tk->fmt.i_cat != VIDEO_ES )
3761                 p_block->i_pts = p_block->i_dts;
3762             else
3763                 p_block->i_pts = VLC_TS_INVALID;
3764
3765             es_out_Send( p_demux->out, tk->p_es, p_block );
3766
3767             tk->i_sample++;
3768
3769             if( !tk->b_has_non_empty_cchunk )
3770                 break;
3771         }
3772     }
3773     return 1;
3774 }