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