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