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