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