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