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