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