]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
mp4: fix flawed logic (close #7058)
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004, 2010 the VideoLAN team
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33
34 #include <vlc_demux.h>
35 #include <vlc_charset.h>                           /* EnsureUTF8 */
36 #include <vlc_meta.h>                              /* vlc_meta_t, vlc_meta_ */
37 #include <vlc_input.h>
38
39 #include "libmp4.h"
40 #include "id3genres.h"                             /* for ATOM_gnre */
41
42 /*****************************************************************************
43  * Module descriptor
44  *****************************************************************************/
45 static int  Open ( vlc_object_t * );
46 static void Close( vlc_object_t * );
47
48 vlc_module_begin ()
49     set_category( CAT_INPUT )
50     set_subcategory( SUBCAT_INPUT_DEMUX )
51     set_description( N_("MP4 stream demuxer") )
52     set_shortname( N_("MP4") )
53     set_capability( "demux", 240 )
54     set_callbacks( Open, Close )
55 vlc_module_end ()
56
57 /*****************************************************************************
58  * Local prototypes
59  *****************************************************************************/
60 static int   Demux   ( demux_t * );
61 static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
62 static int   Seek    ( demux_t *, mtime_t );
63 static int   Control ( demux_t *, int, va_list );
64
65 struct demux_sys_t
66 {
67     MP4_Box_t    *p_root;      /* container for the whole file */
68
69     mtime_t      i_pcr;
70
71     uint64_t     i_time;         /* time position of the presentation
72                                   * in movie timescale */
73     uint64_t     i_timescale;    /* movie time scale */
74     uint64_t     i_duration;     /* movie duration */
75     unsigned int i_tracks;       /* number of tracks */
76     mp4_track_t  *track;         /* array of track */
77     float        f_fps;          /* number of frame per seconds */
78
79     /* */
80     MP4_Box_t    *p_tref_chap;
81
82     /* */
83     input_title_t *p_title;
84 };
85
86 /*****************************************************************************
87  * Declaration of local function
88  *****************************************************************************/
89 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *, bool b_force_enable );
90 static void MP4_TrackDestroy(  mp4_track_t * );
91
92 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
93 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
94
95 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
96
97 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
98 static int      MP4_TrackSampleSize( mp4_track_t * );
99 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
100 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
101
102 static void     MP4_UpdateSeekpoint( demux_t * );
103 static const char *MP4_ConvertMacCode( uint16_t );
104
105 /* Return time in s of a track */
106 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
107 {
108 #define chunk p_track->chunk[p_track->i_chunk]
109
110     unsigned int i_index = 0;
111     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
112     int64_t i_dts = chunk.i_first_dts;
113
114     while( i_sample > 0 )
115     {
116         if( i_sample > chunk.p_sample_count_dts[i_index] )
117         {
118             i_dts += chunk.p_sample_count_dts[i_index] *
119                 chunk.p_sample_delta_dts[i_index];
120             i_sample -= chunk.p_sample_count_dts[i_index];
121             i_index++;
122         }
123         else
124         {
125             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
126             break;
127         }
128     }
129
130 #undef chunk
131
132     /* now handle elst */
133     if( p_track->p_elst )
134     {
135         demux_sys_t         *p_sys = p_demux->p_sys;
136         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
137
138         /* convert to offset */
139         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
140               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
141             elst->i_media_time[p_track->i_elst] > 0 )
142         {
143             i_dts -= elst->i_media_time[p_track->i_elst];
144         }
145
146         /* add i_elst_time */
147         i_dts += p_track->i_elst_time * p_track->i_timescale /
148             p_sys->i_timescale;
149
150         if( i_dts < 0 ) i_dts = 0;
151     }
152
153     return INT64_C(1000000) * i_dts / p_track->i_timescale;
154 }
155
156 static inline int64_t MP4_TrackGetPTSDelta( mp4_track_t *p_track )
157 {
158     mp4_chunk_t *ck = &p_track->chunk[p_track->i_chunk];
159     unsigned int i_index = 0;
160     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
161
162     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
163         return -1;
164
165     for( i_index = 0;; i_index++ )
166     {
167         if( i_sample < ck->p_sample_count_pts[i_index] )
168             return ck->p_sample_offset_pts[i_index] * INT64_C(1000000) /
169                    (int64_t)p_track->i_timescale;
170
171         i_sample -= ck->p_sample_count_pts[i_index];
172     }
173 }
174
175 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
176 {
177     return INT64_C(1000000) * p_sys->i_time / p_sys->i_timescale;
178 }
179
180 static void LoadChapter( demux_t  *p_demux );
181
182 /*****************************************************************************
183  * Open: check file and initializes MP4 structures
184  *****************************************************************************/
185 static int Open( vlc_object_t * p_this )
186 {
187     demux_t  *p_demux = (demux_t *)p_this;
188     demux_sys_t     *p_sys;
189
190     const uint8_t   *p_peek;
191
192     MP4_Box_t       *p_ftyp;
193     MP4_Box_t       *p_rmra;
194     MP4_Box_t       *p_mvhd;
195     MP4_Box_t       *p_trak;
196
197     unsigned int    i;
198     bool      b_seekable;
199     bool      b_enabled_es;
200
201     /* A little test to see if it could be a mp4 */
202     if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
203
204     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
205     {
206         case ATOM_moov:
207         case ATOM_foov:
208         case ATOM_moof:
209         case ATOM_mdat:
210         case ATOM_udta:
211         case ATOM_free:
212         case ATOM_skip:
213         case ATOM_wide:
214         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
215             break;
216         case ATOM_ftyp:
217             /* We don't yet support f4v, but avformat does. */
218             if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
219                 return VLC_EGENERIC;
220             break;
221          default:
222             return VLC_EGENERIC;
223     }
224
225     /* I need to seek */
226     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
227     if( !b_seekable )
228     {
229         msg_Warn( p_demux, "MP4 plugin discarded (not fastseekable)" );
230         return VLC_EGENERIC;
231     }
232
233     /*Set exported functions */
234     p_demux->pf_demux = Demux;
235     p_demux->pf_control = Control;
236
237     /* create our structure that will contains all data */
238     p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
239
240     /* Now load all boxes ( except raw data ) */
241     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
242     {
243         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
244         goto error;
245     }
246
247     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
248
249     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
250     {
251         switch( p_ftyp->data.p_ftyp->i_major_brand )
252         {
253             case( ATOM_isom ):
254                 msg_Dbg( p_demux,
255                          "ISO Media file (isom) version %d.",
256                          p_ftyp->data.p_ftyp->i_minor_version );
257                 break;
258             case( ATOM_3gp4 ):
259             case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
260             case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
261             case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
262                 msg_Dbg( p_demux, "3GPP Media file Release: %c",
263 #ifdef WORDS_BIGENDIAN
264                         p_ftyp->data.p_ftyp->i_major_brand
265 #else
266                         p_ftyp->data.p_ftyp->i_major_brand >> 24
267 #endif
268                         );
269                 break;
270             case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
271                 msg_Dbg( p_demux, "Apple QuickTime file" );
272                 break;
273             case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
274                 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
275                 break;
276             default:
277                 msg_Dbg( p_demux,
278                          "unrecognized major file specification (%4.4s).",
279                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
280                 break;
281         }
282     }
283     else
284     {
285         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
286     }
287
288     /* the file need to have one moov box */
289     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
290     {
291         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
292
293         if( !p_foov )
294         {
295             /* search also for moof box used by smoothstreaming */
296             p_foov = MP4_BoxGet( p_sys->p_root, "/moof" );
297             if( !p_foov )
298             {
299                 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
300                 goto error;
301             }
302         }
303         /* we have a free box as a moov, rename it */
304         p_foov->i_type = ATOM_moov;
305     }
306
307     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
308     {
309         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
310         int        i;
311
312         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
313
314         input_thread_t *p_input = demux_GetParentInput( p_demux );
315         input_item_t *p_current = input_GetItem( p_input );
316
317         input_item_node_t *p_subitems = input_item_node_Create( p_current );
318
319         for( i = 0; i < i_count; i++ )
320         {
321             MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
322             char      *psz_ref;
323             uint32_t  i_ref_type;
324
325             if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
326             {
327                 continue;
328             }
329             i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
330
331             msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
332                      psz_ref, (char*)&i_ref_type );
333
334             if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
335             {
336                 if( strstr( psz_ref, "qt5gateQT" ) )
337                 {
338                     msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
339                     continue;
340                 }
341                 if( !strncmp( psz_ref, "http://", 7 ) ||
342                     !strncmp( psz_ref, "rtsp://", 7 ) )
343                 {
344                     ;
345                 }
346                 else
347                 {
348                     char *psz_absolute;
349                     char *psz_path = strdup( p_demux->psz_location );
350                     char *end = strrchr( psz_path, '/' );
351                     if( end ) end[1] = '\0';
352                     else *psz_path = '\0';
353
354                     if( asprintf( &psz_absolute, "%s://%s%s",
355                                   p_demux->psz_access, psz_path, psz_ref ) < 0 )
356                     {
357                         free( psz_ref );
358                         free( psz_path );
359                         vlc_object_release( p_input) ;
360                         return VLC_ENOMEM;
361                     }
362
363                     free( psz_ref );
364                     psz_ref = psz_absolute;
365                     free( psz_path );
366                 }
367                 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
368                 input_item_t *p_item = input_item_New( psz_ref, NULL );
369                 input_item_CopyOptions( p_current, p_item );
370                 input_item_node_AppendItem( p_subitems, p_item );
371                 vlc_gc_decref( p_item );
372             }
373             else
374             {
375                 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
376                          (char*)&p_rdrf->data.p_rdrf->i_ref_type );
377             }
378             free( psz_ref );
379         }
380         input_item_node_PostAndDelete( p_subitems );
381         vlc_object_release( p_input );
382     }
383
384     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
385     {
386         if( !p_rmra )
387         {
388             msg_Err( p_demux, "cannot find /moov/mvhd" );
389             goto error;
390         }
391         else
392         {
393             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
394             p_demux->pf_demux = DemuxRef;
395             return VLC_SUCCESS;
396         }
397     }
398     else
399     {
400         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
401         if( p_sys->i_timescale == 0 )
402         {
403             msg_Err( p_this, "bad timescale" );
404             goto error;
405         }
406         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
407     }
408
409     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
410     {
411         msg_Err( p_demux, "cannot find any /moov/trak" );
412         goto error;
413     }
414     msg_Dbg( p_demux, "found %d track%c",
415                         p_sys->i_tracks,
416                         p_sys->i_tracks ? 's':' ' );
417
418     /* allocate memory */
419     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
420     if( p_sys->track == NULL )
421         goto error;
422
423     /* Search the first chap reference (like quicktime) and
424      * check that at least 1 stream is enabled */
425     p_sys->p_tref_chap = NULL;
426     b_enabled_es = false;
427     for( i = 0; i < p_sys->i_tracks; i++ )
428     {
429         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
430
431
432         MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
433         if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
434             b_enabled_es = true;
435
436         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
437         if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
438             p_sys->p_tref_chap = p_chap;
439     }
440
441     /* now process each track and extract all useful information */
442     for( i = 0; i < p_sys->i_tracks; i++ )
443     {
444         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
445         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
446
447         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
448         {
449             const char *psz_cat;
450             switch( p_sys->track[i].fmt.i_cat )
451             {
452                 case( VIDEO_ES ):
453                     psz_cat = "video";
454                     break;
455                 case( AUDIO_ES ):
456                     psz_cat = "audio";
457                     break;
458                 case( SPU_ES ):
459                     psz_cat = "subtitle";
460                     break;
461
462                 default:
463                     psz_cat = "unknown";
464                     break;
465             }
466
467             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
468                      p_sys->track[i].i_track_ID, psz_cat,
469                      p_sys->track[i].b_enable ? "enable":"disable",
470                      p_sys->track[i].fmt.psz_language ?
471                      p_sys->track[i].fmt.psz_language : "undef" );
472         }
473         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
474         {
475             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
476                      p_sys->track[i].i_track_ID,
477                      p_sys->track[i].fmt.psz_language ?
478                      p_sys->track[i].fmt.psz_language : "undef" );
479         }
480         else
481         {
482             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
483                      p_sys->track[i].i_track_ID );
484         }
485     }
486
487     /* */
488     LoadChapter( p_demux );
489
490     return VLC_SUCCESS;
491
492 error:
493     if( p_sys->p_root )
494     {
495         MP4_BoxFree( p_demux->s, p_sys->p_root );
496     }
497     free( p_sys );
498     return VLC_EGENERIC;
499 }
500
501 /*****************************************************************************
502  * Demux: read packet and send them to decoders
503  *****************************************************************************
504  * TODO check for newly selected track (ie audio upt to now )
505  *****************************************************************************/
506 static int Demux( demux_t *p_demux )
507 {
508     demux_sys_t *p_sys = p_demux->p_sys;
509     unsigned int i_track;
510
511
512     unsigned int i_track_selected;
513
514     /* check for newly selected/unselected track */
515     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
516          i_track++ )
517     {
518         mp4_track_t *tk = &p_sys->track[i_track];
519         bool b;
520
521         if( !tk->b_ok || tk->b_chapter ||
522             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
523         {
524             continue;
525         }
526
527         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
528
529         if( tk->b_selected && !b )
530         {
531             MP4_TrackUnselect( p_demux, tk );
532         }
533         else if( !tk->b_selected && b)
534         {
535             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
536         }
537
538         if( tk->b_selected )
539         {
540             i_track_selected++;
541         }
542     }
543
544     if( i_track_selected <= 0 )
545     {
546         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
547         if( p_sys->i_timescale > 0 )
548         {
549             int64_t i_length = (mtime_t)1000000 *
550                                (mtime_t)p_sys->i_duration /
551                                (mtime_t)p_sys->i_timescale;
552             if( MP4_GetMoviePTS( p_sys ) >= i_length )
553                 return 0;
554             return 1;
555         }
556
557         msg_Warn( p_demux, "no track selected, exiting..." );
558         return 0;
559     }
560
561     /* */
562     MP4_UpdateSeekpoint( p_demux );
563
564     /* first wait for the good time to read a packet */
565     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
566
567     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
568
569     /* we will read 100ms for each stream so ...*/
570     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
571
572     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
573     {
574         mp4_track_t *tk = &p_sys->track[i_track];
575
576         if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
577             continue;
578
579         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
580         {
581 #if 0
582             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
583                      MP4_TrackGetDTS( p_demux, tk ),
584                      MP4_GetMoviePTS( p_sys ) );
585 #endif
586
587             if( MP4_TrackSampleSize( tk ) > 0 )
588             {
589                 block_t *p_block;
590                 int64_t i_delta;
591
592                 /* go,go go ! */
593                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
594                 {
595                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
596                               tk->i_track_ID );
597                     MP4_TrackUnselect( p_demux, tk );
598                     break;
599                 }
600
601                 /* now read pes */
602                 if( !(p_block =
603                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
604                 {
605                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
606                               tk->i_track_ID );
607                     MP4_TrackUnselect( p_demux, tk );
608                     break;
609                 }
610
611                 else if( tk->fmt.i_cat == SPU_ES )
612                 {
613                     if( tk->fmt.i_codec == VLC_CODEC_SUBT &&
614                         p_block->i_buffer >= 2 )
615                     {
616                         size_t i_size = GetWBE( p_block->p_buffer );
617
618                         if( i_size + 2 <= p_block->i_buffer )
619                         {
620                             char *p;
621                             /* remove the length field, and append a '\0' */
622                             memmove( &p_block->p_buffer[0],
623                                      &p_block->p_buffer[2], i_size );
624                             p_block->p_buffer[i_size] = '\0';
625                             p_block->i_buffer = i_size + 1;
626
627                             /* convert \r -> \n */
628                             while( ( p = strchr((char *) p_block->p_buffer, '\r' ) ) )
629                             {
630                                 *p = '\n';
631                             }
632                         }
633                         else
634                         {
635                             /* Invalid */
636                             p_block->i_buffer = 0;
637                         }
638                     }
639                 }
640                 /* dts */
641                 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
642                 /* pts */
643                 i_delta = MP4_TrackGetPTSDelta( tk );
644                 if( i_delta != -1 )
645                     p_block->i_pts = p_block->i_dts + i_delta;
646                 else if( tk->fmt.i_cat != VIDEO_ES )
647                     p_block->i_pts = p_block->i_dts;
648                 else
649                     p_block->i_pts = VLC_TS_INVALID;
650
651                 es_out_Send( p_demux->out, tk->p_es, p_block );
652             }
653
654             /* Next sample */
655             if( MP4_TrackNextSample( p_demux, tk ) )
656                 break;
657         }
658     }
659
660     return 1;
661 }
662
663 static void MP4_UpdateSeekpoint( demux_t *p_demux )
664 {
665     demux_sys_t *p_sys = p_demux->p_sys;
666     int64_t i_time;
667     int i;
668     if( !p_sys->p_title )
669         return;
670     i_time = MP4_GetMoviePTS( p_sys );
671     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
672     {
673         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
674             break;
675     }
676     i--;
677
678     if( i != p_demux->info.i_seekpoint && i >= 0 )
679     {
680         p_demux->info.i_seekpoint = i;
681         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
682     }
683 }
684 /*****************************************************************************
685  * Seek: Go to i_date
686 ******************************************************************************/
687 static int Seek( demux_t *p_demux, mtime_t i_date )
688 {
689     demux_sys_t *p_sys = p_demux->p_sys;
690     unsigned int i_track;
691
692     /* First update global time */
693     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
694     p_sys->i_pcr  = i_date;
695
696     /* Now for each stream try to go to this time */
697     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
698     {
699         mp4_track_t *tk = &p_sys->track[i_track];
700         MP4_TrackSeek( p_demux, tk, i_date );
701     }
702     MP4_UpdateSeekpoint( p_demux );
703
704     es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
705
706     return VLC_SUCCESS;
707 }
708
709 /*****************************************************************************
710  * Control:
711  *****************************************************************************/
712 static int Control( demux_t *p_demux, int i_query, va_list args )
713 {
714     demux_sys_t *p_sys = p_demux->p_sys;
715
716     double f, *pf;
717     int64_t i64, *pi64;
718
719     switch( i_query )
720     {
721         case DEMUX_GET_POSITION:
722             pf = (double*)va_arg( args, double * );
723             if( p_sys->i_duration > 0 )
724             {
725                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
726             }
727             else
728             {
729                 *pf = 0.0;
730             }
731             return VLC_SUCCESS;
732
733         case DEMUX_SET_POSITION:
734             f = (double)va_arg( args, double );
735             if( p_sys->i_timescale > 0 )
736             {
737                 i64 = (int64_t)( f * (double)1000000 *
738                                  (double)p_sys->i_duration /
739                                  (double)p_sys->i_timescale );
740                 return Seek( p_demux, i64 );
741             }
742             else return VLC_SUCCESS;
743
744         case DEMUX_GET_TIME:
745             pi64 = (int64_t*)va_arg( args, int64_t * );
746             if( p_sys->i_timescale > 0 )
747             {
748                 *pi64 = (mtime_t)1000000 *
749                         (mtime_t)p_sys->i_time /
750                         (mtime_t)p_sys->i_timescale;
751             }
752             else *pi64 = 0;
753             return VLC_SUCCESS;
754
755         case DEMUX_SET_TIME:
756             i64 = (int64_t)va_arg( args, int64_t );
757             return Seek( p_demux, i64 );
758
759         case DEMUX_GET_LENGTH:
760             pi64 = (int64_t*)va_arg( args, int64_t * );
761             if( p_sys->i_timescale > 0 )
762             {
763                 *pi64 = (mtime_t)1000000 *
764                         (mtime_t)p_sys->i_duration /
765                         (mtime_t)p_sys->i_timescale;
766             }
767             else *pi64 = 0;
768             return VLC_SUCCESS;
769
770         case DEMUX_GET_FPS:
771             pf = (double*)va_arg( args, double* );
772             *pf = p_sys->f_fps;
773             return VLC_SUCCESS;
774
775         case DEMUX_GET_META:
776         {
777             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
778             MP4_Box_t  *p_0xa9xxx;
779
780             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
781             if( p_udta == NULL )
782             {
783                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
784                 if( p_udta == NULL )
785                 {
786                     return VLC_EGENERIC;
787                 }
788             }
789
790             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
791                  p_0xa9xxx = p_0xa9xxx->p_next )
792             {
793
794                 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
795                     continue;
796
797                 /* FIXME FIXME: should convert from whatever the character
798                  * encoding of MP4 meta data is to UTF-8. */
799 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
800     if( psz_utf ) { EnsureUTF8( psz_utf );  \
801                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
802
803                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
804                 switch( p_0xa9xxx->i_type )
805                 {
806                 case ATOM_0xa9nam: /* Full name */
807                     SET( vlc_meta_SetTitle );
808                     break;
809                 case ATOM_0xa9aut:
810                     SET( vlc_meta_SetArtist );
811                     break;
812                 case ATOM_0xa9ART:
813                     SET( vlc_meta_SetArtist );
814                     break;
815                 case ATOM_0xa9cpy:
816                     SET( vlc_meta_SetCopyright );
817                     break;
818                 case ATOM_0xa9day: /* Creation Date */
819                     SET( vlc_meta_SetDate );
820                     break;
821                 case ATOM_0xa9des: /* Description */
822                     SET( vlc_meta_SetDescription );
823                     break;
824                 case ATOM_0xa9gen: /* Genre */
825                     SET( vlc_meta_SetGenre );
826                     break;
827
828                 case ATOM_gnre:
829                     if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
830                         vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
831                     break;
832
833                 case ATOM_0xa9alb: /* Album */
834                     SET( vlc_meta_SetAlbum );
835                     break;
836
837                 case ATOM_0xa9trk: /* Track */
838                     SET( vlc_meta_SetTrackNum );
839                     break;
840                 case ATOM_trkn:
841                 {
842                     char psz_trck[11];
843                     snprintf( psz_trck, sizeof( psz_trck ), "%i",
844                               p_0xa9xxx->data.p_trkn->i_track_number );
845                     vlc_meta_SetTrackNum( p_meta, psz_trck );
846                     snprintf( psz_trck, sizeof( psz_trck ), "%i",
847                               p_0xa9xxx->data.p_trkn->i_track_total );
848                     vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
849                     break;
850                 }
851                 case ATOM_0xa9cmt: /* Commment */
852                     SET( vlc_meta_SetDescription );
853                     break;
854
855                 case ATOM_0xa9url: /* URL */
856                     SET( vlc_meta_SetURL );
857                     break;
858
859                 case ATOM_0xa9too: /* Encoder Tool */
860                 case ATOM_0xa9enc: /* Encoded By */
861                     SET( vlc_meta_SetEncodedBy );
862                     break;
863
864                 case ATOM_0xa9pub:
865                     SET( vlc_meta_SetPublisher );
866                     break;
867
868                 default:
869                     break;
870                 }
871 #undef SET
872                 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
873                 {
874                     { ATOM_0xa9wrt, N_("Writer") },
875                     { ATOM_0xa9com, N_("Composer") },
876                     { ATOM_0xa9prd, N_("Producer") },
877                     { ATOM_0xa9inf, N_("Information") },
878                     { ATOM_0xa9dir, N_("Director") },
879                     { ATOM_0xa9dis, N_("Disclaimer") },
880                     { ATOM_0xa9req, N_("Requirements") },
881                     { ATOM_0xa9fmt, N_("Original Format") },
882                     { ATOM_0xa9dsa, N_("Display Source As") },
883                     { ATOM_0xa9hst, N_("Host Computer") },
884                     { ATOM_0xa9prf, N_("Performers") },
885                     { ATOM_0xa9ope, N_("Original Performer") },
886                     { ATOM_0xa9src, N_("Providers Source Content") },
887                     { ATOM_0xa9wrn, N_("Warning") },
888                     { ATOM_0xa9swr, N_("Software") },
889                     { ATOM_0xa9lyr, N_("Lyrics") },
890                     { ATOM_0xa9mak, N_("Record Company") },
891                     { ATOM_0xa9mod, N_("Model") },
892                     { ATOM_0xa9PRD, N_("Product") },
893                     { ATOM_0xa9grp, N_("Grouping") },
894                     { ATOM_0xa9gen, N_("Genre") },
895                     { ATOM_0xa9st3, N_("Sub-Title") },
896                     { ATOM_0xa9arg, N_("Arranger") },
897                     { ATOM_0xa9ard, N_("Art Director") },
898                     { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
899                     { ATOM_0xa9con, N_("Conductor") },
900                     { ATOM_0xa9des, N_("Song Description") },
901                     { ATOM_0xa9lnt, N_("Liner Notes") },
902                     { ATOM_0xa9phg, N_("Phonogram Rights") },
903                     { ATOM_0xa9pub, N_("Publisher") },
904                     { ATOM_0xa9sne, N_("Sound Engineer") },
905                     { ATOM_0xa9sol, N_("Soloist") },
906                     { ATOM_0xa9thx, N_("Thanks") },
907                     { ATOM_0xa9xpd, N_("Executive Producer") },
908                     { 0, "" },
909                 };
910                 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
911                 {
912                     if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
913                     {
914                         char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
915                         if( psz_utf )
916                         {
917                              EnsureUTF8( psz_utf );
918                              vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
919                              free( psz_utf );
920                         }
921                         break;
922                     }
923                 }
924             }
925             return VLC_SUCCESS;
926         }
927
928         case DEMUX_GET_TITLE_INFO:
929         {
930             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
931             int *pi_int    = (int*)va_arg( args, int* );
932             int *pi_title_offset = (int*)va_arg( args, int* );
933             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
934
935             if( !p_sys->p_title )
936                 return VLC_EGENERIC;
937
938             *pi_int = 1;
939             *ppp_title = malloc( sizeof( input_title_t**) );
940             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
941             *pi_title_offset = 0;
942             *pi_seekpoint_offset = 0;
943             return VLC_SUCCESS;
944         }
945         case DEMUX_SET_TITLE:
946         {
947             const int i_title = (int)va_arg( args, int );
948             if( !p_sys->p_title || i_title != 0 )
949                 return VLC_EGENERIC;
950             return VLC_SUCCESS;
951         }
952         case DEMUX_SET_SEEKPOINT:
953         {
954             const int i_seekpoint = (int)va_arg( args, int );
955             if( !p_sys->p_title )
956                 return VLC_EGENERIC;
957             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
958         }
959
960         case DEMUX_SET_NEXT_DEMUX_TIME:
961         case DEMUX_SET_GROUP:
962         case DEMUX_HAS_UNSUPPORTED_META:
963         case DEMUX_GET_ATTACHMENTS:
964         case DEMUX_GET_PTS_DELAY:
965         case DEMUX_CAN_RECORD:
966             return VLC_EGENERIC;
967
968         default:
969             msg_Warn( p_demux, "control query %u unimplemented", i_query );
970             return VLC_EGENERIC;
971     }
972 }
973
974 /*****************************************************************************
975  * Close: frees unused data
976  *****************************************************************************/
977 static void Close ( vlc_object_t * p_this )
978 {
979     demux_t *  p_demux = (demux_t *)p_this;
980     demux_sys_t *p_sys = p_demux->p_sys;
981     unsigned int i_track;
982
983     msg_Dbg( p_demux, "freeing all memory" );
984
985     MP4_BoxFree( p_demux->s, p_sys->p_root );
986     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
987     {
988         MP4_TrackDestroy(  &p_sys->track[i_track] );
989     }
990     FREENULL( p_sys->track );
991
992     if( p_sys->p_title )
993         vlc_input_title_Delete( p_sys->p_title );
994
995     free( p_sys );
996 }
997
998
999
1000 /****************************************************************************
1001  * Local functions, specific to vlc
1002  ****************************************************************************/
1003 /* Chapters */
1004 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
1005 {
1006     demux_sys_t *p_sys = p_demux->p_sys;
1007     int i;
1008
1009     p_sys->p_title = vlc_input_title_New();
1010     for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1011     {
1012         seekpoint_t *s = vlc_seekpoint_New();
1013
1014         s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1015         EnsureUTF8( s->psz_name );
1016         s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1017         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1018     }
1019 }
1020 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1021 {
1022     demux_sys_t *p_sys = p_demux->p_sys;
1023
1024     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1025     {
1026         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1027         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( tk );
1028         const unsigned int i_size = MP4_TrackSampleSize( tk );
1029
1030         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1031         {
1032             char p_buffer[256];
1033             const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1034             const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1035
1036             if( i_len > 0 )
1037             {
1038                 seekpoint_t *s = vlc_seekpoint_New();
1039
1040                 s->psz_name = strndup( &p_buffer[2], i_len );
1041                 EnsureUTF8( s->psz_name );
1042
1043                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1044
1045                 if( !p_sys->p_title )
1046                     p_sys->p_title = vlc_input_title_New();
1047                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1048             }
1049         }
1050         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1051                               tk->chunk[tk->i_chunk].i_sample_count )
1052             tk->i_chunk++;
1053     }
1054 }
1055 static void LoadChapter( demux_t  *p_demux )
1056 {
1057     demux_sys_t *p_sys = p_demux->p_sys;
1058     MP4_Box_t *p_chpl;
1059
1060     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1061     {
1062         LoadChapterGpac( p_demux, p_chpl );
1063     }
1064     else if( p_sys->p_tref_chap )
1065     {
1066         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1067         unsigned int i, j;
1068
1069         /* Load the first subtitle track like quicktime */
1070         for( i = 0; i < p_chap->i_entry_count; i++ )
1071         {
1072             for( j = 0; j < p_sys->i_tracks; j++ )
1073             {
1074                 mp4_track_t *tk = &p_sys->track[j];
1075                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1076                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1077                     break;
1078             }
1079             if( j < p_sys->i_tracks )
1080             {
1081                 LoadChapterApple( p_demux, &p_sys->track[j] );
1082                 break;
1083             }
1084         }
1085     }
1086
1087     /* Add duration if titles are enabled */
1088     if( p_sys->p_title )
1089     {
1090         p_sys->p_title->i_length = (uint64_t)1000000 *
1091                        (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1092     }
1093 }
1094
1095 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1096 static int TrackCreateChunksIndex( demux_t *p_demux,
1097                                    mp4_track_t *p_demux_track )
1098 {
1099     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1100     MP4_Box_t *p_stsc;
1101
1102     unsigned int i_chunk;
1103     unsigned int i_index, i_last;
1104
1105     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1106           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1107         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1108     {
1109         return( VLC_EGENERIC );
1110     }
1111
1112     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1113     if( !p_demux_track->i_chunk_count )
1114     {
1115         msg_Warn( p_demux, "no chunk defined" );
1116         return( VLC_EGENERIC );
1117     }
1118     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1119                                    sizeof( mp4_chunk_t ) );
1120     if( p_demux_track->chunk == NULL )
1121     {
1122         return VLC_ENOMEM;
1123     }
1124
1125     /* first we read chunk offset */
1126     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1127     {
1128         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1129
1130         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1131
1132         ck->i_first_dts = 0;
1133         ck->p_sample_count_dts = NULL;
1134         ck->p_sample_delta_dts = NULL;
1135         ck->p_sample_count_pts = NULL;
1136         ck->p_sample_offset_pts = NULL;
1137     }
1138
1139     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1140         to be used for the sample XXX begin to 1
1141         We construct it begining at the end */
1142     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1143     i_index = p_stsc->data.p_stsc->i_entry_count;
1144     if( !i_index )
1145     {
1146         msg_Warn( p_demux, "cannot read chunk table or table empty" );
1147         return( VLC_EGENERIC );
1148     }
1149
1150     while( i_index-- )
1151     {
1152         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1153              i_chunk < i_last; i_chunk++ )
1154         {
1155             if( i_chunk >= p_demux_track->i_chunk_count )
1156             {
1157                 msg_Warn( p_demux, "corrupted chunk table" );
1158                 return VLC_EGENERIC;
1159             }
1160
1161             p_demux_track->chunk[i_chunk].i_sample_description_index =
1162                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
1163             p_demux_track->chunk[i_chunk].i_sample_count =
1164                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1165         }
1166         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1167     }
1168
1169     p_demux_track->chunk[0].i_sample_first = 0;
1170     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1171     {
1172         p_demux_track->chunk[i_chunk].i_sample_first =
1173             p_demux_track->chunk[i_chunk-1].i_sample_first +
1174                 p_demux_track->chunk[i_chunk-1].i_sample_count;
1175     }
1176
1177     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1178              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1179
1180     return VLC_SUCCESS;
1181 }
1182
1183 static int TrackCreateSamplesIndex( demux_t *p_demux,
1184                                     mp4_track_t *p_demux_track )
1185 {
1186     MP4_Box_t *p_box;
1187     MP4_Box_data_stsz_t *stsz;
1188     MP4_Box_data_stts_t *stts;
1189     /* TODO use also stss and stsh table for seeking */
1190     /* FIXME use edit table */
1191     int64_t i_sample;
1192     int64_t i_chunk;
1193
1194     int64_t i_index;
1195     int64_t i_index_sample_used;
1196
1197     int64_t i_next_dts;
1198
1199     /* Find stsz
1200      *  Gives the sample size for each samples. There is also a stz2 table
1201      *  (compressed form) that we need to implement TODO */
1202     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1203     if( !p_box )
1204     {
1205         /* FIXME and stz2 */
1206         msg_Warn( p_demux, "cannot find STSZ box" );
1207         return VLC_EGENERIC;
1208     }
1209     stsz = p_box->data.p_stsz;
1210
1211     /* Find stts
1212      *  Gives mapping between sample and decoding time
1213      */
1214     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1215     if( !p_box )
1216     {
1217         msg_Warn( p_demux, "cannot find STTS box" );
1218         return VLC_EGENERIC;
1219     }
1220     stts = p_box->data.p_stts;
1221
1222     /* Use stsz table to create a sample number -> sample size table */
1223     p_demux_track->i_sample_count = stsz->i_sample_count;
1224     if( stsz->i_sample_size )
1225     {
1226         /* 1: all sample have the same size, so no need to construct a table */
1227         p_demux_track->i_sample_size = stsz->i_sample_size;
1228         p_demux_track->p_sample_size = NULL;
1229     }
1230     else
1231     {
1232         /* 2: each sample can have a different size */
1233         p_demux_track->i_sample_size = 0;
1234         p_demux_track->p_sample_size =
1235             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1236         if( p_demux_track->p_sample_size == NULL )
1237             return VLC_ENOMEM;
1238
1239         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1240         {
1241             p_demux_track->p_sample_size[i_sample] =
1242                     stsz->i_entry_size[i_sample];
1243         }
1244     }
1245
1246     /* Use stts table to create a sample number -> dts table.
1247      * XXX: if we don't want to waste too much memory, we can't expand
1248      *  the box! so each chunk will contain an "extract" of this table
1249      *  for fast research (problem with raw stream where a sample is sometime
1250      *  just channels*bits_per_sample/8 */
1251
1252     i_next_dts = 0;
1253     i_index = 0; i_index_sample_used = 0;
1254     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1255     {
1256         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1257         int64_t i_entry, i_sample_count, i;
1258
1259         /* save first dts */
1260         ck->i_first_dts = i_next_dts;
1261         ck->i_last_dts  = i_next_dts;
1262
1263         /* count how many entries are needed for this chunk
1264          * for p_sample_delta_dts and p_sample_count_dts */
1265         i_sample_count = ck->i_sample_count;
1266
1267         i_entry = 0;
1268         while( i_sample_count > 0 )
1269         {
1270             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1271             /* don't count already used sample in this entry */
1272             if( i_entry == 0 )
1273                 i_sample_count += i_index_sample_used;
1274
1275             i_entry++;
1276         }
1277
1278         /* allocate them */
1279         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1280         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1281
1282         if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1283             return VLC_ENOMEM;
1284
1285         /* now copy */
1286         i_sample_count = ck->i_sample_count;
1287         for( i = 0; i < i_entry; i++ )
1288         {
1289             int64_t i_used;
1290             int64_t i_rest;
1291
1292             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1293
1294             i_used = __MIN( i_rest, i_sample_count );
1295
1296             i_index_sample_used += i_used;
1297             i_sample_count -= i_used;
1298             i_next_dts += i_used * stts->i_sample_delta[i_index];
1299
1300             ck->p_sample_count_dts[i] = i_used;
1301             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1302             if( i_used > 0 )
1303                 ck->i_last_dts = i_next_dts - ck->p_sample_delta_dts[i];
1304
1305             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1306             {
1307                 i_index++;
1308                 i_index_sample_used = 0;
1309             }
1310         }
1311     }
1312
1313     /* Find ctts
1314      *  Gives the delta between decoding time (dts) and composition table (pts)
1315      */
1316     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1317     if( p_box )
1318     {
1319         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1320
1321         msg_Warn( p_demux, "CTTS table" );
1322
1323         /* Create pts-dts table per chunk */
1324         i_index = 0; i_index_sample_used = 0;
1325         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1326         {
1327             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1328             int64_t i_entry, i_sample_count, i;
1329
1330             /* count how many entries are needed for this chunk
1331              * for p_sample_delta_dts and p_sample_count_dts */
1332             i_sample_count = ck->i_sample_count;
1333
1334             i_entry = 0;
1335             while( i_sample_count > 0 )
1336             {
1337                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1338
1339                 /* don't count already used sample in this entry */
1340                 if( i_entry == 0 )
1341                     i_sample_count += i_index_sample_used;
1342
1343                 i_entry++;
1344             }
1345
1346             /* allocate them */
1347             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1348             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1349             if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1350                 return VLC_ENOMEM;
1351
1352             /* now copy */
1353             i_sample_count = ck->i_sample_count;
1354             for( i = 0; i < i_entry; i++ )
1355             {
1356                 int64_t i_used;
1357                 int64_t i_rest;
1358
1359                 i_rest = ctts->i_sample_count[i_index] -
1360                     i_index_sample_used;
1361
1362                 i_used = __MIN( i_rest, i_sample_count );
1363
1364                 i_index_sample_used += i_used;
1365                 i_sample_count -= i_used;
1366
1367                 ck->p_sample_count_pts[i] = i_used;
1368                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1369
1370                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1371                 {
1372                     i_index++;
1373                     i_index_sample_used = 0;
1374                 }
1375             }
1376         }
1377     }
1378
1379     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:%"PRId64"s",
1380              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1381              i_next_dts / p_demux_track->i_timescale );
1382
1383     return VLC_SUCCESS;
1384 }
1385
1386 /**
1387  * It computes the sample rate for a video track using the given sample
1388  * description index
1389  */
1390 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1391                                   const mp4_track_t *p_track,
1392                                   unsigned i_sd_index,
1393                                   unsigned i_chunk )
1394 {
1395     *pi_num = 0;
1396     *pi_den = 0;
1397
1398     if( p_track->i_chunk_count <= 0 )
1399         return;
1400
1401     /* */
1402     const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1403     while( p_chunk > &p_track->chunk[0] &&
1404            p_chunk[-1].i_sample_description_index == i_sd_index )
1405     {
1406         p_chunk--;
1407     }
1408
1409     uint64_t i_sample = 0;
1410     uint64_t i_first_dts = p_chunk->i_first_dts;
1411     uint64_t i_last_dts;
1412     do
1413     {
1414         i_sample += p_chunk->i_sample_count;
1415         i_last_dts = p_chunk->i_last_dts;
1416         p_chunk++;
1417     }
1418     while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1419            p_chunk->i_sample_description_index == i_sd_index );
1420
1421     if( i_sample > 1 && i_first_dts < i_last_dts )
1422         vlc_ureduce( pi_num, pi_den,
1423                      ( i_sample - 1) *  p_track->i_timescale,
1424                      i_last_dts - i_first_dts,
1425                      UINT16_MAX);
1426 }
1427
1428 /*
1429  * TrackCreateES:
1430  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1431  */
1432 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1433                           unsigned int i_chunk, es_out_id_t **pp_es )
1434 {
1435     const unsigned i_sample_description_index =
1436         p_track->chunk[i_chunk].i_sample_description_index;
1437     MP4_Box_t   *p_sample;
1438     MP4_Box_t   *p_esds;
1439     MP4_Box_t   *p_frma;
1440     MP4_Box_t   *p_enda;
1441     MP4_Box_t   *p_pasp;
1442
1443     if( pp_es )
1444         *pp_es = NULL;
1445
1446     if( !i_sample_description_index )
1447     {
1448         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1449                   p_track->i_track_ID );
1450         return VLC_EGENERIC;
1451     }
1452
1453     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1454                             i_sample_description_index - 1 );
1455
1456     if( !p_sample ||
1457         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1458     {
1459         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1460                   p_track->i_track_ID );
1461         return VLC_EGENERIC;
1462     }
1463
1464     p_track->p_sample = p_sample;
1465
1466     if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1467     {
1468         msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1469
1470         p_sample->i_type = p_frma->data.p_frma->i_type;
1471     }
1472
1473     p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1474     if( !p_enda )
1475         p_enda = MP4_BoxGet( p_sample, "enda" );
1476
1477     p_pasp = MP4_BoxGet( p_sample, "pasp" );
1478
1479     /* */
1480     switch( p_track->fmt.i_cat )
1481     {
1482     case VIDEO_ES:
1483         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1484         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1485         p_track->fmt.video.i_bits_per_pixel =
1486             p_sample->data.p_sample_vide->i_depth;
1487
1488         /* fall on display size */
1489         if( p_track->fmt.video.i_width <= 0 )
1490             p_track->fmt.video.i_width = p_track->i_width;
1491         if( p_track->fmt.video.i_height <= 0 )
1492             p_track->fmt.video.i_height = p_track->i_height;
1493
1494         /* Find out apect ratio from display size */
1495         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1496             /* Work-around buggy muxed files */
1497             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1498         {
1499             p_track->fmt.video.i_sar_num = p_track->i_width  * p_track->fmt.video.i_height;
1500             p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1501         }
1502         if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1503                       p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1504         {
1505             p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1506             p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1507         }
1508
1509         /* Support for cropping (eg. in H263 files) */
1510         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1511         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1512
1513         /* Frame rate */
1514         TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1515                               &p_track->fmt.video.i_frame_rate_base,
1516                               p_track, i_sample_description_index, i_chunk );
1517         p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1518                                 (float)p_track->fmt.video.i_frame_rate_base;
1519
1520         /* Rotation */
1521         switch( (int)p_track->f_rotation ) {
1522             case 90:
1523                 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1524                 break;
1525             case 180:
1526                 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1527                 break;
1528             case 270:
1529                 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1530                 break;
1531         }
1532
1533         break;
1534
1535     case AUDIO_ES:
1536         p_track->fmt.audio.i_channels =
1537             p_sample->data.p_sample_soun->i_channelcount;
1538         p_track->fmt.audio.i_rate =
1539             p_sample->data.p_sample_soun->i_sampleratehi;
1540         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1541             p_sample->data.p_sample_soun->i_sampleratehi *
1542                 p_sample->data.p_sample_soun->i_samplesize;
1543         p_track->fmt.audio.i_bitspersample =
1544             p_sample->data.p_sample_soun->i_samplesize;
1545
1546         if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1547         {
1548             MP4_Box_data_sample_soun_t *p_soun;
1549             p_soun = p_sample->data.p_sample_soun;
1550
1551             if( p_soun->i_qt_version == 0 )
1552             {
1553                 switch( p_sample->i_type )
1554                 {
1555                     case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1556                         p_soun->i_qt_version = 1;
1557                         p_soun->i_sample_per_packet = 64;
1558                         p_soun->i_bytes_per_packet  = 34;
1559                         p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1560                         p_soun->i_bytes_per_sample  = 2;
1561                         break;
1562                     case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1563                         p_soun->i_qt_version = 1;
1564                         p_soun->i_sample_per_packet = 6;
1565                         p_soun->i_bytes_per_packet  = 2;
1566                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1567                         p_soun->i_bytes_per_sample  = 2;
1568                         break;
1569                     case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1570                         p_soun->i_qt_version = 1;
1571                         p_soun->i_sample_per_packet = 12;
1572                         p_soun->i_bytes_per_packet  = 2;
1573                         p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1574                         p_soun->i_bytes_per_sample  = 2;
1575                         break;
1576                     case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1577                     case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1578                         p_soun->i_samplesize = 8;
1579                         p_track->i_sample_size = p_soun->i_channelcount;
1580                         break;
1581                     case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1582                     case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1583                     case VLC_FOURCC( 't', 'w', 'o', 's' ):
1584                     case VLC_FOURCC( 's', 'o', 'w', 't' ):
1585                         /* What would be the fun if you could trust the .mov */
1586                         p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1587                         break;
1588                     default:
1589                         break;
1590                 }
1591
1592             }
1593             else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1594             {
1595                 p_soun->i_qt_version = 0;
1596             }
1597         }
1598         else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1599         {
1600             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1601
1602             switch( p_sample->i_type )
1603             {
1604                 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1605                 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1606                     {
1607                         if( p_track->i_sample_size > 1 )
1608                             p_soun->i_qt_version = 0;
1609                         break;
1610                     }
1611                 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1612                 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1613                 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
1614                     p_soun->i_qt_version = 0;
1615                     break;
1616                 default:
1617                     break;
1618             }
1619         }
1620
1621         if( p_track->i_sample_size != 0 &&
1622                 p_sample->data.p_sample_soun->i_qt_version == 1 &&
1623                 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
1624         {
1625             msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
1626             p_sample->data.p_sample_soun->i_qt_version = 0;
1627         }
1628         break;
1629
1630     default:
1631         break;
1632     }
1633
1634
1635     /* It's a little ugly but .. there are special cases */
1636     switch( p_sample->i_type )
1637     {
1638         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1639         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1640         {
1641             p_track->fmt.i_codec = VLC_CODEC_MPGA;
1642             break;
1643         }
1644         case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1645         {
1646             MP4_Box_t *p_dac3_box = MP4_BoxGet(  p_sample, "dac3", 0 );
1647
1648             p_track->fmt.i_codec = VLC_CODEC_A52;
1649             if( p_dac3_box )
1650             {
1651                 static const int pi_bitrate[] = {
1652                      32,  40,  48,  56,
1653                      64,  80,  96, 112,
1654                     128, 160, 192, 224,
1655                     256, 320, 384, 448,
1656                     512, 576, 640,
1657                 };
1658                 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
1659                 p_track->fmt.audio.i_channels = 0;
1660                 p_track->fmt.i_bitrate = 0;
1661                 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
1662                     p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
1663                 p_track->fmt.audio.i_bitspersample = 0;
1664             }
1665             break;
1666         }
1667         case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1668         {
1669             p_track->fmt.i_codec = VLC_CODEC_EAC3;
1670             break;
1671         }
1672
1673         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1674         case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
1675         {
1676             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1677
1678             if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
1679                 p_track->fmt.i_codec = VLC_FOURCC( 'u', '8', ' ', ' ' );
1680             else
1681                 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1682
1683             /* Buggy files workaround */
1684             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
1685                 p_sample->data.p_sample_soun->i_sampleratehi) )
1686             {
1687                 MP4_Box_data_sample_soun_t *p_soun =
1688                     p_sample->data.p_sample_soun;
1689
1690                 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
1691                           "(%u), making both equal (report any problem).",
1692                           p_track->i_timescale, p_soun->i_sampleratehi );
1693
1694                 if( p_soun->i_sampleratehi )
1695                     p_track->i_timescale = p_soun->i_sampleratehi;
1696                 else
1697                     p_soun->i_sampleratehi = p_track->i_timescale;
1698             }
1699             break;
1700         }
1701
1702         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1703             p_track->fmt.i_codec = VLC_CODEC_H263;
1704             break;
1705
1706         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1707         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
1708             p_track->fmt.i_codec = VLC_CODEC_SUBT;
1709             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1710             /* FIXME UTF-8 doesn't work here ? */
1711             if( p_track->b_mac_encoding )
1712                 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
1713             else
1714                 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
1715             break;
1716
1717         case VLC_FOURCC('y','v','1','2'):
1718             p_track->fmt.i_codec = VLC_CODEC_YV12;
1719             break;
1720         case VLC_FOURCC('y','u','v','2'):
1721             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
1722             break;
1723
1724         case VLC_FOURCC('i','n','2','4'):
1725             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1726                                     VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
1727             break;
1728         case VLC_FOURCC('f','l','3','2'):
1729             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1730                                     VLC_CODEC_F32L : VLC_CODEC_F32B;
1731             break;
1732         case VLC_FOURCC('f','l','6','4'):
1733             p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
1734                                     VLC_CODEC_F64L : VLC_CODEC_F64B;
1735             break;
1736         case VLC_FOURCC( 'l', 'p', 'c', 'm' ):
1737         {
1738             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1739             if( p_soun->i_qt_version == 2 &&
1740                 p_soun->i_qt_description > 20 + 28 )
1741             {
1742                 /* Flags:
1743                  *  0x01: IsFloat
1744                  *  0x02: IsBigEndian
1745                  *  0x04: IsSigned
1746                  */
1747                 static const struct {
1748                     unsigned     i_flags;
1749                     unsigned     i_mask;
1750                     unsigned     i_bits;
1751                     vlc_fourcc_t i_codec;
1752                 } p_formats[] = {
1753                     { 0x01,           0x03, 32, VLC_CODEC_F32L },
1754                     { 0x01,           0x03, 64, VLC_CODEC_F64L },
1755                     { 0x01|0x02,      0x03, 32, VLC_CODEC_F32B },
1756                     { 0x01|0x02,      0x03, 64, VLC_CODEC_F64B },
1757
1758                     { 0x00,           0x05,  8, VLC_CODEC_U8 },
1759                     { 0x00|     0x04, 0x05,  8, VLC_CODEC_S8 },
1760
1761                     { 0x00,           0x07, 16, VLC_CODEC_U16L },
1762                     { 0x00|0x02,      0x07, 16, VLC_CODEC_U16B },
1763                     { 0x00     |0x04, 0x07, 16, VLC_CODEC_S16L },
1764                     { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
1765
1766                     { 0x00,           0x07, 24, VLC_CODEC_U24L },
1767                     { 0x00|0x02,      0x07, 24, VLC_CODEC_U24B },
1768                     { 0x00     |0x04, 0x07, 24, VLC_CODEC_S24L },
1769                     { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
1770
1771                     { 0x00,           0x07, 32, VLC_CODEC_U32L },
1772                     { 0x00|0x02,      0x07, 32, VLC_CODEC_U32B },
1773                     { 0x00     |0x04, 0x07, 32, VLC_CODEC_S32L },
1774                     { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
1775
1776                     {0, 0, 0, 0}
1777                 };
1778                 uint32_t i_bits  = GetDWBE(&p_soun->p_qt_description[20 + 20]);
1779                 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
1780
1781                 for( int i = 0; p_formats[i].i_codec; i++ )
1782                 {
1783                     if( p_formats[i].i_bits == i_bits &&
1784                         (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
1785                     {
1786                         p_track->fmt.i_codec = p_formats[i].i_codec;
1787                         p_track->fmt.audio.i_bitspersample = i_bits;
1788                         p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
1789                         p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
1790
1791                         p_soun->i_qt_version = 0;
1792                         break;
1793                     }
1794                 }
1795             }
1796             break;
1797         }
1798         default:
1799             p_track->fmt.i_codec = p_sample->i_type;
1800             break;
1801     }
1802
1803     /* now see if esds is present and if so create a data packet
1804         with decoder_specific_info  */
1805 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1806     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1807           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1808         ( p_esds->data.p_esds )&&
1809         ( p_decconfig ) )
1810     {
1811         /* First update information based on i_objectTypeIndication */
1812         switch( p_decconfig->i_objectTypeIndication )
1813         {
1814             case( 0x20 ): /* MPEG4 VIDEO */
1815                 p_track->fmt.i_codec = VLC_CODEC_MP4V;
1816                 break;
1817             case( 0x21 ): /* H.264 */
1818                 p_track->fmt.i_codec = VLC_CODEC_H264;
1819                 break;
1820             case( 0x40):
1821                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
1822                 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
1823                      p_decconfig->p_decoder_specific_info[0]       == 0xF8 &&
1824                     (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
1825                 {
1826                     p_track->fmt.i_codec = VLC_CODEC_ALS;
1827                 }
1828                 break;
1829             case( 0x60):
1830             case( 0x61):
1831             case( 0x62):
1832             case( 0x63):
1833             case( 0x64):
1834             case( 0x65): /* MPEG2 video */
1835                 p_track->fmt.i_codec = VLC_CODEC_MPGV;
1836                 break;
1837             /* Theses are MPEG2-AAC */
1838             case( 0x66): /* main profile */
1839             case( 0x67): /* Low complexity profile */
1840             case( 0x68): /* Scaleable Sampling rate profile */
1841                 p_track->fmt.i_codec = VLC_CODEC_MP4A;
1842                 break;
1843             /* True MPEG 2 audio */
1844             case( 0x69):
1845                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
1846                 break;
1847             case( 0x6a): /* MPEG1 video */
1848                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1849                 break;
1850             case( 0x6b): /* MPEG1 audio */
1851                 p_track->fmt.i_codec = VLC_CODEC_MPGA;
1852                 break;
1853             case( 0x6c ): /* jpeg */
1854                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1855                 break;
1856             case( 0x6d ): /* png */
1857                 p_track->fmt.i_codec = VLC_FOURCC( 'p','n','g',' ' );
1858                 break;
1859             case( 0x6e ): /* jpeg2000 */
1860                 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
1861                 break;
1862             case( 0xa3 ): /* vc1 */
1863                 p_track->fmt.i_codec = VLC_CODEC_VC1;
1864                 break;
1865             case( 0xa4 ):
1866                 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
1867                 break;
1868             case( 0xa5 ):
1869                 p_track->fmt.i_codec = VLC_CODEC_A52;
1870                 break;
1871             case( 0xa6 ):
1872                 p_track->fmt.i_codec = VLC_CODEC_EAC3;
1873                 break;
1874             case( 0xa9 ): /* dts */
1875             case( 0xaa ): /* DTS-HD HRA */
1876             case( 0xab ): /* DTS-HD Master Audio */
1877                 p_track->fmt.i_codec = VLC_CODEC_DTS;
1878                 break;
1879             case( 0xDD ):
1880                 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
1881                 break;
1882
1883             /* Private ID */
1884             case( 0xe0 ): /* NeroDigital: dvd subs */
1885                 if( p_track->fmt.i_cat == SPU_ES )
1886                 {
1887                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1888                     if( p_track->i_width > 0 )
1889                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
1890                     if( p_track->i_height > 0 )
1891                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
1892                     break;
1893                 }
1894             case( 0xe1 ): /* QCelp for 3gp */
1895                 if( p_track->fmt.i_cat == AUDIO_ES )
1896                 {
1897                     p_track->fmt.i_codec = VLC_FOURCC( 'Q','c','l','p' );
1898                 }
1899                 break;
1900
1901             /* Fallback */
1902             default:
1903                 /* Unknown entry, but don't touch i_fourcc */
1904                 msg_Warn( p_demux,
1905                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1906                           p_decconfig->i_objectTypeIndication,
1907                           p_track->i_track_ID );
1908                 break;
1909         }
1910         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1911         if( p_track->fmt.i_extra > 0 )
1912         {
1913             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1914             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1915                     p_track->fmt.i_extra );
1916         }
1917     }
1918     else
1919     {
1920         switch( p_sample->i_type )
1921         {
1922             /* qt decoder, send the complete chunk */
1923             case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
1924             case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
1925             case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
1926             case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
1927             case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
1928             case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
1929             case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
1930             case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
1931             case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
1932             case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
1933             case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
1934             case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
1935                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1936                 break;
1937             /* qt decoder, send the complete chunk */
1938             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1939             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1940             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1941             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1942             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1943                 p_track->fmt.i_extra =
1944                     p_sample->data.p_sample_vide->i_qt_image_description;
1945                 if( p_track->fmt.i_extra > 0 )
1946                 {
1947                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1948                     memcpy( p_track->fmt.p_extra,
1949                             p_sample->data.p_sample_vide->p_qt_image_description,
1950                             p_track->fmt.i_extra);
1951                 }
1952                 break;
1953
1954             case VLC_CODEC_AMR_NB:
1955                 p_track->fmt.audio.i_rate = 8000;
1956                 break;
1957             case VLC_CODEC_AMR_WB:
1958                 p_track->fmt.audio.i_rate = 16000;
1959                 break;
1960             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1961             case VLC_CODEC_QDM2:
1962             case VLC_CODEC_ALAC:
1963                 p_track->fmt.i_extra =
1964                     p_sample->data.p_sample_soun->i_qt_description;
1965                 if( p_track->fmt.i_extra > 0 )
1966                 {
1967                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1968                     memcpy( p_track->fmt.p_extra,
1969                             p_sample->data.p_sample_soun->p_qt_description,
1970                             p_track->fmt.i_extra);
1971                 }
1972                 if( p_track->fmt.i_extra >= 56 && p_sample->i_type == VLC_CODEC_ALAC )
1973                 {
1974                     p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
1975                     p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
1976                 }
1977                 break;
1978
1979             case VLC_FOURCC( 'v', 'c', '-', '1' ):
1980             {
1981                 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
1982                 if( p_dvc1 )
1983                 {
1984                     p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
1985                     if( p_track->fmt.i_extra > 0 )
1986                     {
1987                         p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
1988                         memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
1989                                 p_track->fmt.i_extra );
1990                     }
1991                 }
1992                 else
1993                 {
1994                     msg_Err( p_demux, "missing dvc1" );
1995                 }
1996                 break;
1997             }
1998
1999             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2000             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2001             {
2002                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2003
2004                 if( p_avcC )
2005                 {
2006                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2007                     if( p_track->fmt.i_extra > 0 )
2008                     {
2009                         p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2010                         memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2011                                 p_track->fmt.i_extra );
2012                     }
2013                 }
2014                 else
2015                 {
2016                     msg_Err( p_demux, "missing avcC" );
2017                 }
2018                 break;
2019             }
2020
2021             case VLC_CODEC_ADPCM_MS:
2022             case VLC_CODEC_ADPCM_IMA_WAV:
2023             case VLC_CODEC_QCELP:
2024                 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2025                 break;
2026
2027             default:
2028                 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2029                 break;
2030         }
2031     }
2032
2033 #undef p_decconfig
2034
2035     if( pp_es )
2036         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2037
2038     return VLC_SUCCESS;
2039 }
2040
2041 /* given a time it return sample/chunk
2042  * it also update elst field of the track
2043  */
2044 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2045                                    int64_t i_start, uint32_t *pi_chunk,
2046                                    uint32_t *pi_sample )
2047 {
2048     demux_sys_t *p_sys = p_demux->p_sys;
2049     MP4_Box_t   *p_box_stss;
2050     uint64_t     i_dts;
2051     unsigned int i_sample;
2052     unsigned int i_chunk;
2053     int          i_index;
2054
2055     /* FIXME see if it's needed to check p_track->i_chunk_count */
2056     if( p_track->i_chunk_count == 0 )
2057         return( VLC_EGENERIC );
2058
2059     /* handle elst (find the correct one) */
2060     MP4_TrackSetELST( p_demux, p_track, i_start );
2061     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2062     {
2063         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2064         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
2065
2066         /* now calculate i_start for this elst */
2067         /* offset */
2068         i_start -= p_track->i_elst_time * INT64_C(1000000) / p_sys->i_timescale;
2069         if( i_start < 0 )
2070         {
2071             *pi_chunk = 0;
2072             *pi_sample= 0;
2073
2074             return VLC_SUCCESS;
2075         }
2076         /* to track time scale */
2077         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
2078         /* add elst offset */
2079         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2080              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2081             elst->i_media_time[p_track->i_elst] > 0 )
2082         {
2083             i_start += elst->i_media_time[p_track->i_elst];
2084         }
2085
2086         msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2087                  "ms (track)", p_track->i_elst,
2088                  i_mvt * 1000 / p_sys->i_timescale,
2089                  i_start * 1000 / p_track->i_timescale );
2090     }
2091     else
2092     {
2093         /* convert absolute time to in timescale unit */
2094         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
2095     }
2096
2097     /* we start from sample 0/chunk 0, hope it won't take too much time */
2098     /* *** find good chunk *** */
2099     for( i_chunk = 0; ; i_chunk++ )
2100     {
2101         if( i_chunk + 1 >= p_track->i_chunk_count )
2102         {
2103             /* at the end and can't check if i_start in this chunk,
2104                it will be check while searching i_sample */
2105             i_chunk = p_track->i_chunk_count - 1;
2106             break;
2107         }
2108
2109         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2110             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
2111         {
2112             break;
2113         }
2114     }
2115
2116     /* *** find sample in the chunk *** */
2117     i_sample = p_track->chunk[i_chunk].i_sample_first;
2118     i_dts    = p_track->chunk[i_chunk].i_first_dts;
2119     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2120     {
2121         if( i_dts +
2122             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2123             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2124         {
2125             i_dts    +=
2126                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2127                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2128
2129             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2130             i_index++;
2131         }
2132         else
2133         {
2134             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2135             {
2136                 break;
2137             }
2138             i_sample += ( i_start - i_dts ) /
2139                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2140             break;
2141         }
2142     }
2143
2144     if( i_sample >= p_track->i_sample_count )
2145     {
2146         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2147                   "(seeking too far) chunk=%d sample=%d",
2148                   p_track->i_track_ID, i_chunk, i_sample );
2149         return( VLC_EGENERIC );
2150     }
2151
2152
2153     /* *** Try to find nearest sync points *** */
2154     if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2155     {
2156         MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2157         msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2158                  p_track->i_track_ID );
2159         for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2160         {
2161             if( i_index >= p_stss->i_entry_count - 1 ||
2162                 i_sample < p_stss->i_sample_number[i_index+1] )
2163             {
2164                 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2165                 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2166                          i_sample, i_sync_sample );
2167
2168                 if( i_sync_sample <= i_sample )
2169                 {
2170                     while( i_chunk > 0 &&
2171                            i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2172                         i_chunk--;
2173                 }
2174                 else
2175                 {
2176                     while( i_chunk < p_track->i_chunk_count - 1 &&
2177                            i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2178                                             p_track->chunk[i_chunk].i_sample_count )
2179                         i_chunk++;
2180                 }
2181                 i_sample = i_sync_sample;
2182                 break;
2183             }
2184         }
2185     }
2186     else
2187     {
2188         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2189                  "Sample Box (stss)", p_track->i_track_ID );
2190     }
2191
2192     *pi_chunk  = i_chunk;
2193     *pi_sample = i_sample;
2194
2195     return VLC_SUCCESS;
2196 }
2197
2198 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2199                                  unsigned int i_chunk, unsigned int i_sample )
2200 {
2201     bool b_reselect = false;
2202
2203     /* now see if actual es is ok */
2204     if( p_track->i_chunk >= p_track->i_chunk_count ||
2205         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2206             p_track->chunk[i_chunk].i_sample_description_index )
2207     {
2208         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2209                   p_track->i_track_ID );
2210
2211         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2212                         p_track->p_es, &b_reselect );
2213
2214         es_out_Del( p_demux->out, p_track->p_es );
2215
2216         p_track->p_es = NULL;
2217
2218         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2219         {
2220             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2221                      p_track->i_track_ID );
2222
2223             p_track->b_ok       = false;
2224             p_track->b_selected = false;
2225             return VLC_EGENERIC;
2226         }
2227     }
2228
2229     /* select again the new decoder */
2230     if( b_reselect )
2231     {
2232         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2233     }
2234
2235     p_track->i_chunk    = i_chunk;
2236     p_track->i_sample   = i_sample;
2237
2238     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2239 }
2240
2241 /****************************************************************************
2242  * MP4_TrackCreate:
2243  ****************************************************************************
2244  * Parse track information and create all needed data to run a track
2245  * If it succeed b_ok is set to 1 else to 0
2246  ****************************************************************************/
2247 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2248                              MP4_Box_t *p_box_trak,
2249                              bool b_force_enable )
2250 {
2251     demux_sys_t *p_sys = p_demux->p_sys;
2252
2253     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2254     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2255     MP4_Box_t *p_elst;
2256
2257     MP4_Box_t *p_mdhd;
2258     MP4_Box_t *p_udta;
2259     MP4_Box_t *p_hdlr;
2260
2261     MP4_Box_t *p_vmhd;
2262     MP4_Box_t *p_smhd;
2263
2264     char language[4];
2265
2266     /* hint track unsupported */
2267
2268     /* set default value (-> track unusable) */
2269     p_track->b_ok       = false;
2270     p_track->b_enable   = false;
2271     p_track->b_selected = false;
2272     p_track->b_chapter  = false;
2273     p_track->b_mac_encoding = false;
2274
2275     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2276
2277     if( !p_tkhd )
2278     {
2279         return;
2280     }
2281
2282     /* do we launch this track by default ? */
2283     p_track->b_enable =
2284         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2285     if( !p_track->b_enable )
2286         p_track->fmt.i_priority = -1;
2287
2288     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2289
2290     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
2291     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
2292     p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2293
2294     if( p_tref )
2295     {
2296 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2297     }
2298
2299     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2300     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2301
2302     if( ( !p_mdhd )||( !p_hdlr ) )
2303     {
2304         return;
2305     }
2306
2307     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2308     if( !p_track->i_timescale )
2309         return;
2310
2311     if( p_mdhd->data.p_mdhd->i_language_code < 0x800 )
2312     {
2313         /* We can convert i_language_code into iso 639 code,
2314          * I won't */
2315         strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2316         p_track->b_mac_encoding = true;
2317     }
2318     else
2319     {
2320         for( unsigned i = 0; i < 3; i++ )
2321             language[i] = p_mdhd->data.p_mdhd->i_language[i];
2322         language[3] = '\0';
2323     }
2324
2325     switch( p_hdlr->data.p_hdlr->i_handler_type )
2326     {
2327         case( ATOM_soun ):
2328             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2329             {
2330                 return;
2331             }
2332             p_track->fmt.i_cat = AUDIO_ES;
2333             break;
2334
2335         case( ATOM_vide ):
2336             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2337             {
2338                 return;
2339             }
2340             p_track->fmt.i_cat = VIDEO_ES;
2341             break;
2342
2343         case( ATOM_text ):
2344         case( ATOM_subp ):
2345         case( ATOM_tx3g ):
2346         case( ATOM_sbtl ):
2347             p_track->fmt.i_cat = SPU_ES;
2348             break;
2349
2350         default:
2351             return;
2352     }
2353
2354     p_track->i_elst = 0;
2355     p_track->i_elst_time = 0;
2356     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2357     {
2358         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2359         unsigned int i;
2360
2361         msg_Warn( p_demux, "elst box found" );
2362         for( i = 0; i < elst->i_entry_count; i++ )
2363         {
2364             msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
2365                      "ms) rate=%d.%d", i,
2366                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2367                      elst->i_media_time[i] >= 0 ?
2368                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2369                      INT64_C(-1),
2370                      elst->i_media_rate_integer[i],
2371                      elst->i_media_rate_fraction[i] );
2372         }
2373     }
2374
2375
2376 /*  TODO
2377     add support for:
2378     p_dinf = MP4_BoxGet( p_minf, "dinf" );
2379 */
2380     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2381         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2382     {
2383         return;
2384     }
2385
2386     /* Set language */
2387     if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2388     {
2389         p_track->fmt.psz_language = strdup( language );
2390     }
2391
2392     p_udta = MP4_BoxGet( p_box_trak, "udta" );
2393     if( p_udta )
2394     {
2395         MP4_Box_t *p_box_iter;
2396         for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2397                  p_box_iter = p_box_iter->p_next )
2398         {
2399             switch( p_box_iter->i_type )
2400             {
2401                 case ATOM_0xa9nam:
2402                     p_track->fmt.psz_description =
2403                         strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2404                     break;
2405                 case ATOM_name:
2406                     p_track->fmt.psz_description =
2407                         strdup( p_box_iter->data.p_name->psz_text );
2408                     break;
2409             }
2410         }
2411     }
2412
2413     /* Create chunk index table and sample index table */
2414     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
2415         TrackCreateSamplesIndex( p_demux, p_track ) )
2416     {
2417         return; /* cannot create chunks index */
2418     }
2419
2420     p_track->i_chunk  = 0;
2421     p_track->i_sample = 0;
2422
2423     /* Mark chapter only track */
2424     if( p_sys->p_tref_chap )
2425     {
2426         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2427         unsigned int i;
2428
2429         for( i = 0; i < p_chap->i_entry_count; i++ )
2430         {
2431             if( p_track->i_track_ID == p_chap->i_track_ID[i] )
2432             {
2433                 p_track->b_chapter = true;
2434                 p_track->b_enable = false;
2435                 break;
2436             }
2437         }
2438     }
2439
2440     /* now create es */
2441     if( b_force_enable &&
2442         ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2443     {
2444         msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2445                   p_track->i_track_ID );
2446         p_track->b_enable = true;
2447         p_track->fmt.i_priority = 0;
2448     }
2449
2450     p_track->p_es = NULL;
2451     if( TrackCreateES( p_demux,
2452                        p_track, p_track->i_chunk,
2453                        p_track->b_chapter ? NULL : &p_track->p_es ) )
2454     {
2455         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2456                  p_track->i_track_ID );
2457         return;
2458     }
2459     p_track->b_ok = true;
2460 #if 0
2461     {
2462         int i;
2463         for( i = 0; i < p_track->i_chunk_count; i++ )
2464         {
2465             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2466                      i, p_track->chunk[i].i_sample_count,
2467                      p_track->chunk[i].i_first_dts );
2468
2469         }
2470     }
2471 #endif
2472 }
2473
2474 /****************************************************************************
2475  * MP4_TrackDestroy:
2476  ****************************************************************************
2477  * Destroy a track created by MP4_TrackCreate.
2478  ****************************************************************************/
2479 static void MP4_TrackDestroy( mp4_track_t *p_track )
2480 {
2481     unsigned int i_chunk;
2482
2483     p_track->b_ok = false;
2484     p_track->b_enable   = false;
2485     p_track->b_selected = false;
2486
2487     es_format_Clean( &p_track->fmt );
2488
2489     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2490     {
2491         if( p_track->chunk )
2492         {
2493            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2494            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2495
2496            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2497            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2498         }
2499     }
2500     FREENULL( p_track->chunk );
2501
2502     if( !p_track->i_sample_size )
2503     {
2504         FREENULL( p_track->p_sample_size );
2505     }
2506 }
2507
2508 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2509                             mtime_t i_start )
2510 {
2511     if( !p_track->b_ok || p_track->b_chapter )
2512     {
2513         return VLC_EGENERIC;
2514     }
2515
2516     if( p_track->b_selected )
2517     {
2518         msg_Warn( p_demux, "track[Id 0x%x] already selected",
2519                   p_track->i_track_ID );
2520         return VLC_SUCCESS;
2521     }
2522
2523     return MP4_TrackSeek( p_demux, p_track, i_start );
2524 }
2525
2526 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2527 {
2528     if( !p_track->b_ok || p_track->b_chapter )
2529     {
2530         return;
2531     }
2532
2533     if( !p_track->b_selected )
2534     {
2535         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2536                   p_track->i_track_ID );
2537         return;
2538     }
2539     if( p_track->p_es )
2540     {
2541         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2542                         p_track->p_es, false );
2543     }
2544
2545     p_track->b_selected = false;
2546 }
2547
2548 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2549                           mtime_t i_start )
2550 {
2551     uint32_t i_chunk;
2552     uint32_t i_sample;
2553
2554     if( !p_track->b_ok || p_track->b_chapter )
2555         return VLC_EGENERIC;
2556
2557     p_track->b_selected = false;
2558
2559     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2560                                 &i_chunk, &i_sample ) )
2561     {
2562         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2563                   p_track->i_track_ID );
2564         return VLC_EGENERIC;
2565     }
2566
2567     p_track->b_selected = true;
2568
2569     if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
2570         p_track->b_selected = true;
2571
2572     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2573 }
2574
2575
2576 /*
2577  * 3 types: for audio
2578  *
2579  */
2580 #define QT_V0_MAX_SAMPLES 1024
2581 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2582 {
2583     int i_size;
2584     MP4_Box_data_sample_soun_t *p_soun;
2585
2586     if( p_track->i_sample_size == 0 )
2587     {
2588         /* most simple case */
2589         return p_track->p_sample_size[p_track->i_sample];
2590     }
2591     if( p_track->fmt.i_cat != AUDIO_ES )
2592     {
2593         return p_track->i_sample_size;
2594     }
2595
2596     p_soun = p_track->p_sample->data.p_sample_soun;
2597
2598     if( p_soun->i_qt_version == 1 )
2599     {
2600         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
2601         if( p_track->fmt.audio.i_blockalign > 1 )
2602             i_samples = p_soun->i_sample_per_packet;
2603
2604         i_size = i_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2605     }
2606     else if( p_track->i_sample_size > 256 )
2607     {
2608         /* We do that so we don't read too much data
2609          * (in this case we are likely dealing with compressed data) */
2610         i_size = p_track->i_sample_size;
2611     }
2612     else
2613     {
2614         /* Read a bunch of samples at once */
2615         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2616             ( p_track->i_sample -
2617               p_track->chunk[p_track->i_chunk].i_sample_first );
2618
2619         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2620         i_size = i_samples * p_track->i_sample_size;
2621     }
2622
2623     //fprintf( stderr, "size=%d\n", i_size );
2624     return i_size;
2625 }
2626
2627 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2628 {
2629     unsigned int i_sample;
2630     uint64_t i_pos;
2631
2632     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2633
2634     if( p_track->i_sample_size )
2635     {
2636         MP4_Box_data_sample_soun_t *p_soun =
2637             p_track->p_sample->data.p_sample_soun;
2638
2639         if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
2640         {
2641             i_pos += ( p_track->i_sample -
2642                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2643                      p_track->i_sample_size;
2644         }
2645         else
2646         {
2647             /* we read chunk by chunk unless a blockalign is requested */
2648             if( p_track->fmt.audio.i_blockalign > 1 )
2649                 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
2650                                 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2651         }
2652     }
2653     else
2654     {
2655         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2656              i_sample < p_track->i_sample; i_sample++ )
2657         {
2658             i_pos += p_track->p_sample_size[i_sample];
2659         }
2660     }
2661
2662     return i_pos;
2663 }
2664
2665 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2666 {
2667     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2668     {
2669         MP4_Box_data_sample_soun_t *p_soun;
2670
2671         p_soun = p_track->p_sample->data.p_sample_soun;
2672
2673         if( p_soun->i_qt_version == 1 )
2674         {
2675             /* we read chunk by chunk unless a blockalign is requested */
2676             if( p_track->fmt.audio.i_blockalign > 1 )
2677                 p_track->i_sample += p_soun->i_sample_per_packet;
2678             else
2679                 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
2680         }
2681         else if( p_track->i_sample_size > 256 )
2682         {
2683             /* We do that so we don't read too much data
2684              * (in this case we are likely dealing with compressed data) */
2685             p_track->i_sample += 1;
2686         }
2687         else
2688         {
2689             /* FIXME */
2690             p_track->i_sample += QT_V0_MAX_SAMPLES;
2691             if( p_track->i_sample >
2692                 p_track->chunk[p_track->i_chunk].i_sample_first +
2693                 p_track->chunk[p_track->i_chunk].i_sample_count )
2694             {
2695                 p_track->i_sample =
2696                     p_track->chunk[p_track->i_chunk].i_sample_first +
2697                     p_track->chunk[p_track->i_chunk].i_sample_count;
2698             }
2699         }
2700     }
2701     else
2702     {
2703         p_track->i_sample++;
2704     }
2705
2706     if( p_track->i_sample >= p_track->i_sample_count )
2707         return VLC_EGENERIC;
2708
2709     /* Have we changed chunk ? */
2710     if( p_track->i_sample >=
2711             p_track->chunk[p_track->i_chunk].i_sample_first +
2712             p_track->chunk[p_track->i_chunk].i_sample_count )
2713     {
2714         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2715                                   p_track->i_sample ) )
2716         {
2717             msg_Warn( p_demux, "track[0x%x] will be disabled "
2718                       "(cannot restart decoder)", p_track->i_track_ID );
2719             MP4_TrackUnselect( p_demux, p_track );
2720             return VLC_EGENERIC;
2721         }
2722     }
2723
2724     /* Have we changed elst */
2725     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2726     {
2727         demux_sys_t *p_sys = p_demux->p_sys;
2728         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2729         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2730                         p_sys->i_timescale / (int64_t)1000000;
2731
2732         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
2733             i_mvt >= p_track->i_elst_time +
2734                      elst->i_segment_duration[p_track->i_elst] )
2735         {
2736             MP4_TrackSetELST( p_demux, p_track,
2737                               MP4_TrackGetDTS( p_demux, p_track ) );
2738         }
2739     }
2740
2741     return VLC_SUCCESS;
2742 }
2743
2744 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2745                               int64_t i_time )
2746 {
2747     demux_sys_t *p_sys = p_demux->p_sys;
2748     int         i_elst_last = tk->i_elst;
2749
2750     /* handle elst (find the correct one) */
2751     tk->i_elst      = 0;
2752     tk->i_elst_time = 0;
2753     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2754     {
2755         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2756         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2757
2758         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2759         {
2760             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2761
2762             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2763             {
2764                 break;
2765             }
2766             tk->i_elst_time += i_dur;
2767         }
2768
2769         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
2770         {
2771             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2772             tk->i_elst = elst->i_entry_count - 1;
2773             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2774         }
2775
2776         if( elst->i_media_time[tk->i_elst] < 0 )
2777         {
2778             /* track offset */
2779             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2780         }
2781     }
2782     if( i_elst_last != tk->i_elst )
2783     {
2784         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2785     }
2786 }
2787
2788 /* */
2789 static const char *MP4_ConvertMacCode( uint16_t i_code )
2790 {
2791     static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
2792         { "en",   0 }, { "fr",   1 }, { "de",   2 }, { "it",   3 }, { "nl",   4 },
2793         { "sv",   5 }, { "es",   6 }, { "da",   7 }, { "pt",   8 }, { "no",   9 },
2794         { "he",  10 }, { "ja",  11 }, { "ar",  12 }, { "fi",  13 }, { "el",  14 },
2795         { "is",  15 }, { "mt",  16 }, { "tr",  17 }, { "hr",  18 }, { "zh",  19 },
2796         { "ur",  20 }, { "hi",  21 }, { "th",  22 }, { "ko",  23 }, { "lt",  24 },
2797         { "pl",  25 }, { "hu",  26 }, { "et",  27 }, { "lv",  28 }, //{ "??",  29 },
2798         { "fo",  30 }, { "fa",  31 }, { "ru",  32 }, { "zh",  33 }, { "nl",  34 },
2799         { "ga",  35 }, { "sq",  36 }, { "ro",  37 }, { "cs",  38 }, { "sk",  39 },
2800         { "sl",  40 }, { "yi",  41 }, { "sr",  42 }, { "mk",  43 }, { "bg",  44 },
2801         { "uk",  45 }, { "be",  46 }, { "uz",  47 }, { "az",  48 }, { "kk",  48 },
2802         { "az",  50 }, { "hy",  51 }, { "ka",  52 }, { "mo",  53 }, { "ky",  54 },
2803         { "tg",  55 }, { "tk",  56 }, { "mn",  57 }, { "mn",  58 }, { "ps",  59 },
2804         { "ku",  60 }, { "ks",  61 }, { "sd",  62 }, { "bo",  63 }, { "ne",  64 },
2805         { "sa",  65 }, { "mr",  66 }, { "bn",  67 }, { "as",  68 }, { "gu",  69 },
2806         { "pa",  70 }, { "or",  71 }, { "ml",  72 }, { "kn",  73 }, { "ta",  74 },
2807         { "te",  75 }, { "si",  76 }, { "my",  77 }, { "km",  78 }, { "lo",  79 },
2808         { "vi",  80 }, { "id",  81 }, { "tl",  82 }, { "ms",  83 }, { "ms",  84 },
2809         { "am",  85 }, { "ti",  86 }, { "om",  87 }, { "so",  88 }, { "sw",  89 },
2810         { "rw",  90 }, { "rn",  91 }, { "ny",  92 }, { "mg",  93 }, { "eo",  94 },
2811
2812                                                      { "cy", 128 }, { "eu", 129 },
2813         { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
2814         { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
2815         { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
2816         { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
2817         /* */
2818         { "", 0 }
2819     };
2820     int i;
2821     for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
2822     {
2823         if( p_cvt[i].i_code == i_code )
2824             return p_cvt[i].psz_iso639_1;
2825     }
2826     return "";
2827 }