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