]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
Copyright fixes
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 VideoLAN (Centrale Réseaux) and its contributors
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #include <stdlib.h>                                      /* malloc(), free() */
27
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30 #include <vlc_playlist.h>
31 #include "iso_lang.h"
32 #include "vlc_meta.h"
33
34 #include "libmp4.h"
35 #include "drms.h"
36
37 #ifdef UNDER_CE
38 #define uint64_t int64_t
39 #endif
40
41 /*****************************************************************************
42  * Module descriptor
43  *****************************************************************************/
44 static int  Open ( vlc_object_t * );
45 static void Close( vlc_object_t * );
46
47 vlc_module_begin();
48     set_category( CAT_INPUT );
49     set_subcategory( SUBCAT_INPUT_DEMUX );
50     set_description( _("MP4 stream demuxer") );
51     set_capability( "demux2", 242 );
52     set_callbacks( Open, Close );
53 vlc_module_end();
54
55 /*****************************************************************************
56  * Local prototypes
57  *****************************************************************************/
58 static int   Demux   ( demux_t * );
59 static int   DemuxRef( demux_t *p_demux ){ return 0;}
60 static int   Seek    ( demux_t *, mtime_t );
61 static int   Control ( demux_t *, int, va_list );
62
63 /* Contain all information about a chunk */
64 typedef struct
65 {
66     uint64_t     i_offset; /* absolute position of this chunk in the file */
67     uint32_t     i_sample_description_index; /* index for SampleEntry to use */
68     uint32_t     i_sample_count; /* how many samples in this chunk */
69     uint32_t     i_sample_first; /* index of the first sample in this chunk */
70
71     /* now provide way to calculate pts, dts, and offset without to
72         much memory and with fast acces */
73
74     /* with this we can calculate dts/pts without waste memory */
75     uint64_t     i_first_dts;
76     uint32_t     *p_sample_count_dts;
77     uint32_t     *p_sample_delta_dts;   /* dts delta */
78
79     uint32_t     *p_sample_count_pts;
80     int32_t      *p_sample_offset_pts;  /* pts-dts */
81
82     /* TODO if needed add pts
83         but quickly *add* support for edts and seeking */
84
85 } mp4_chunk_t;
86
87  /* Contain all needed information for read all track with vlc */
88 typedef struct
89 {
90     int i_track_ID;     /* this should be unique */
91
92     int b_ok;           /* The track is usable */
93     int b_enable;       /* is the trak enable by default */
94     vlc_bool_t b_selected;     /* is the trak being played */
95
96     es_format_t fmt;
97     es_out_id_t *p_es;
98
99     /* display size only ! */
100     int i_width;
101     int i_height;
102
103     /* more internal data */
104     uint64_t        i_timescale;    /* time scale for this track only */
105
106     /* elst */
107     int             i_elst;         /* current elst */
108     int64_t         i_elst_time;    /* current elst start time (in movie time scale)*/
109     MP4_Box_t       *p_elst;        /* elst (could be NULL) */
110
111     /* give the next sample to read, i_chunk is to find quickly where
112       the sample is located */
113     uint32_t         i_sample;       /* next sample to read */
114     uint32_t         i_chunk;        /* chunk where next sample is stored */
115     /* total count of chunk and sample */
116     uint32_t         i_chunk_count;
117     uint32_t         i_sample_count;
118
119     mp4_chunk_t    *chunk; /* always defined  for each chunk */
120
121     /* sample size, p_sample_size defined only if i_sample_size == 0
122         else i_sample_size is size for all sample */
123     uint32_t         i_sample_size;
124     uint32_t         *p_sample_size; /* XXX perhaps add file offset if take
125                                     too much time to do sumations each time*/
126
127     MP4_Box_t *p_stbl;  /* will contain all timing information */
128     MP4_Box_t *p_stsd;  /* will contain all data to initialize decoder */
129     MP4_Box_t *p_sample;/* point on actual sdsd */
130
131     vlc_bool_t b_drms;
132     void      *p_drms;
133
134 } mp4_track_t;
135
136
137 struct demux_sys_t
138 {
139     MP4_Box_t    *p_root;      /* container for the whole file */
140
141     mtime_t      i_pcr;
142
143     uint64_t     i_time;        /* time position of the presentation
144                                  * in movie timescale */
145     uint64_t     i_timescale;   /* movie time scale */
146     uint64_t     i_duration;    /* movie duration */
147     unsigned int i_tracks;      /* number of tracks */
148     mp4_track_t *track;    /* array of track */
149 };
150
151 /*****************************************************************************
152  * Declaration of local function
153  *****************************************************************************/
154 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *);
155 static void MP4_TrackDestroy( demux_t *, mp4_track_t * );
156
157 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
158 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
159
160 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
161
162 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
163 static int      MP4_TrackSampleSize( mp4_track_t * );
164 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
165 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
166
167 /* Return time in µs of a track */
168 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
169 {
170 #define chunk p_track->chunk[p_track->i_chunk]
171
172     unsigned int i_index = 0;
173     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
174     int64_t i_dts = chunk.i_first_dts;
175
176     while( i_sample > 0 )
177     {
178         if( i_sample > chunk.p_sample_count_dts[i_index] )
179         {
180             i_dts += chunk.p_sample_count_dts[i_index] *
181                 chunk.p_sample_delta_dts[i_index];
182             i_sample -= chunk.p_sample_count_dts[i_index];
183             i_index++;
184         }
185         else
186         {
187             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
188             i_sample = 0;
189             break;
190         }
191     }
192
193 #undef chunk
194
195     /* now handle elst */
196     if( p_track->p_elst )
197     {
198         demux_sys_t         *p_sys = p_demux->p_sys;
199         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
200
201         /* convert to offset */
202         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
203               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
204             elst->i_media_time[p_track->i_elst] > 0 )
205         {
206             i_dts -= elst->i_media_time[p_track->i_elst];
207         }
208
209         /* add i_elst_time */
210         i_dts += p_track->i_elst_time * p_track->i_timescale /
211             p_sys->i_timescale;
212
213         if( i_dts < 0 ) i_dts = 0;
214     }
215
216     return I64C(1000000) * i_dts / p_track->i_timescale;
217 }
218
219 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
220 {
221     mp4_chunk_t *ck = &p_track->chunk[p_track->i_chunk];
222     unsigned int i_index = 0;
223     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
224
225     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
226         return -1;
227
228     for( i_index = 0;; i_index++ )
229     {
230         if( i_sample < ck->p_sample_count_pts[i_index] )
231             return ck->p_sample_offset_pts[i_index] * I64C(1000000) /
232                    (int64_t)p_track->i_timescale;
233
234         i_sample -= ck->p_sample_count_pts[i_index];
235     }
236 }
237
238 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
239 {
240     return I64C(1000000) * p_sys->i_time / p_sys->i_timescale;
241 }
242
243 #define FREE( p ) if( p ) { free( p ); (p) = NULL;}
244
245 /*****************************************************************************
246  * Open: check file and initializes MP4 structures
247  *****************************************************************************/
248 static int Open( vlc_object_t * p_this )
249 {
250     demux_t  *p_demux = (demux_t *)p_this;
251     demux_sys_t     *p_sys;
252
253     uint8_t         *p_peek;
254
255     MP4_Box_t       *p_ftyp;
256     MP4_Box_t       *p_rmra;
257     MP4_Box_t       *p_mvhd;
258     MP4_Box_t       *p_trak;
259
260     unsigned int    i;
261     vlc_bool_t      b_seekable;
262
263     /* A little test to see if it could be a mp4 */
264     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 ) return VLC_EGENERIC;
265
266     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
267     {
268         case FOURCC_ftyp:
269         case FOURCC_moov:
270         case FOURCC_foov:
271         case FOURCC_moof:
272         case FOURCC_mdat:
273         case FOURCC_udta:
274         case FOURCC_free:
275         case FOURCC_skip:
276         case FOURCC_wide:
277         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
278             break;
279          default:
280             return VLC_EGENERIC;
281     }
282
283     /* I need to seek */
284     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
285     if( !b_seekable )
286     {
287         msg_Warn( p_demux, "MP4 plugin discarded (unseekable)" );
288         return VLC_EGENERIC;
289     }
290
291     /*Set exported functions */
292     p_demux->pf_demux = Demux;
293     p_demux->pf_control = Control;
294
295     /* create our structure that will contains all data */
296     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
297     memset( p_sys, 0, sizeof( demux_sys_t ) );
298
299     /* Now load all boxes ( except raw data ) */
300     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
301     {
302         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
303         goto error;
304     }
305
306     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
307
308     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
309     {
310         switch( p_ftyp->data.p_ftyp->i_major_brand )
311         {
312             case( FOURCC_isom ):
313                 msg_Dbg( p_demux,
314                          "ISO Media file (isom) version %d.",
315                          p_ftyp->data.p_ftyp->i_minor_version );
316                 break;
317             default:
318                 msg_Dbg( p_demux,
319                          "unrecognized major file specification (%4.4s).",
320                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
321                 break;
322         }
323     }
324     else
325     {
326         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
327     }
328
329     /* the file need to have one moov box */
330     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
331     {
332         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
333
334         if( !p_foov )
335         {
336             msg_Err( p_demux, "MP4 plugin discarded (no moov box)" );
337             goto error;
338         }
339         /* we have a free box as a moov, rename it */
340         p_foov->i_type = FOURCC_moov;
341     }
342
343     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
344     {
345         playlist_t *p_playlist;
346         playlist_item_t *p_item;
347         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
348         int        i;
349         vlc_bool_t b_play = VLC_FALSE;
350
351         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
352
353         p_playlist =
354             (playlist_t *)vlc_object_find( p_demux,
355                                            VLC_OBJECT_PLAYLIST,
356                                            FIND_ANYWHERE );
357         if( p_playlist )
358         {
359             p_item = playlist_LockItemGetByInput( p_playlist,
360                       ((input_thread_t *)p_demux->p_parent)->input.p_item );
361             playlist_ItemToNode( p_playlist, p_item );
362
363             for( i = 0; i < i_count; i++ )
364             {
365                 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
366                 char      *psz_ref;
367                 uint32_t  i_ref_type;
368
369                 if( !p_rdrf || !( psz_ref = p_rdrf->data.p_rdrf->psz_ref ) )
370                 {
371                     continue;
372                 }
373                 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
374
375                 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
376                          psz_ref, (char*)&i_ref_type );
377
378                 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
379                 {
380                     if( strstr( psz_ref, "qt5gateQT" ) )
381                     {
382                         msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
383                         continue;
384                     }
385                     if( !strncmp( psz_ref, "http://", 7 ) ||
386                         !strncmp( psz_ref, "rtsp://", 7 ) )
387                     {
388                         msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
389                         if( p_item )
390                         {
391                             playlist_item_t *p_child =
392                                         playlist_ItemNew( p_playlist,
393                                                           psz_ref, psz_ref );
394                             if( p_child )
395                             {
396                                 playlist_NodeAddItem( p_playlist, p_child,
397                                                  p_item->pp_parents[0]->i_view,
398                                                  p_item, PLAYLIST_APPEND,
399                                                  PLAYLIST_END );
400                                 playlist_CopyParents( p_item, p_child );
401                                 b_play = VLC_TRUE;
402                             }
403                         }
404                     }
405                     else
406                     {
407                         /* msg dbg relative ? */
408                         char *psz_absolute = alloca( strlen( p_demux->psz_access ) + 3 + strlen( p_demux->psz_path ) + strlen( psz_ref ) + 1);
409                         char *end = strrchr( p_demux->psz_path, '/' );
410
411                         if( end )
412                         {
413                             int i_len = end + 1 - p_demux->psz_path;
414
415                             strcpy( psz_absolute, p_demux->psz_access );
416                             strcat( psz_absolute, "://" );
417                             strncat( psz_absolute, p_demux->psz_path, i_len);
418                         }
419                         else
420                         {
421                             strcpy( psz_absolute, "" );
422                         }
423                         strcat( psz_absolute, psz_ref );
424                         msg_Dbg( p_demux, "adding ref = `%s'", psz_absolute );
425                         if( p_item )
426                         {
427                             playlist_item_t *p_child =
428                                         playlist_ItemNew( p_playlist,
429                                                           psz_absolute,
430                                                           psz_absolute );
431                             if( p_child )
432                             {
433                                 playlist_NodeAddItem( p_playlist, p_child,
434                                                  p_item->pp_parents[0]->i_view,
435                                                  p_item, PLAYLIST_APPEND,
436                                                  PLAYLIST_END );
437                                 playlist_CopyParents( p_item, p_child );
438                                 b_play = VLC_TRUE;
439                             }
440                         }
441                     }
442                 }
443                 else
444                 {
445                     msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
446                              (char*)&p_rdrf->data.p_rdrf->i_ref_type );
447                 }
448             }
449             if( b_play == VLC_TRUE )
450             {
451                  playlist_Control( p_playlist, PLAYLIST_VIEWPLAY,
452                                    p_playlist->status.i_view,
453                                    p_playlist->status.p_item, NULL );
454             }
455             vlc_object_release( p_playlist );
456         }
457         else
458         {
459             msg_Err( p_demux, "can't find playlist" );
460         }
461     }
462
463     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
464     {
465         if( !p_rmra )
466         {
467             msg_Err( p_demux, "cannot find /moov/mvhd" );
468             goto error;
469         }
470         else
471         {
472             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
473             p_demux->pf_demux = DemuxRef;
474             return VLC_SUCCESS;
475         }
476     }
477     else
478     {
479         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
480         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
481     }
482
483     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
484     {
485         msg_Err( p_demux, "cannot find any /moov/trak" );
486         goto error;
487     }
488     msg_Dbg( p_demux, "find %d track%c",
489                         p_sys->i_tracks,
490                         p_sys->i_tracks ? 's':' ' );
491
492     /* allocate memory */
493     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
494     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( mp4_track_t ) );
495
496     /* now process each track and extract all usefull information */
497     for( i = 0; i < p_sys->i_tracks; i++ )
498     {
499         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
500         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak );
501
502         if( p_sys->track[i].b_ok )
503         {
504             char *psz_cat;
505             switch( p_sys->track[i].fmt.i_cat )
506             {
507                 case( VIDEO_ES ):
508                     psz_cat = "video";
509                     break;
510                 case( AUDIO_ES ):
511                     psz_cat = "audio";
512                     break;
513                 case( SPU_ES ):
514                     psz_cat = "subtitle";
515                     break;
516
517                 default:
518                     psz_cat = "unknown";
519                     break;
520             }
521
522             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
523                      p_sys->track[i].i_track_ID, psz_cat,
524                      p_sys->track[i].b_enable ? "enable":"disable",
525                      p_sys->track[i].fmt.psz_language ?
526                      p_sys->track[i].fmt.psz_language : "undef" );
527         }
528         else
529         {
530             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
531                      p_sys->track[i].i_track_ID );
532         }
533
534     }
535     return VLC_SUCCESS;
536
537 error:
538     if( p_sys->p_root )
539     {
540         MP4_BoxFree( p_demux->s, p_sys->p_root );
541     }
542     free( p_sys );
543     return VLC_EGENERIC;
544 }
545
546 /*****************************************************************************
547  * Demux: read packet and send them to decoders
548  *****************************************************************************
549  * TODO check for newly selected track (ie audio upt to now )
550  *****************************************************************************/
551 static int Demux( demux_t *p_demux )
552 {
553     demux_sys_t *p_sys = p_demux->p_sys;
554     unsigned int i_track;
555
556
557     unsigned int i_track_selected;
558
559     /* check for newly selected/unselected track */
560     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
561          i_track++ )
562     {
563         mp4_track_t *tk = &p_sys->track[i_track];
564         vlc_bool_t b;
565
566         if( !tk->b_ok ||
567             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
568         {
569             continue;
570         }
571
572         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
573
574         if( tk->b_selected && !b )
575         {
576             MP4_TrackUnselect( p_demux, tk );
577         }
578         else if( !tk->b_selected && b)
579         {
580             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
581         }
582
583         if( tk->b_selected )
584         {
585             i_track_selected++;
586         }
587     }
588
589     if( i_track_selected <= 0 )
590     {
591         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
592         if( p_sys->i_timescale > 0 )
593         {
594             int64_t i_length = (mtime_t)1000000 *
595                                (mtime_t)p_sys->i_duration /
596                                (mtime_t)p_sys->i_timescale;
597             if( MP4_GetMoviePTS( p_sys ) >= i_length )
598                 return 0;
599             return 1;
600         }
601
602         msg_Warn( p_demux, "no track selected, exiting..." );
603         return 0;
604     }
605
606     /* first wait for the good time to read a packet */
607     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr + 1 );
608
609     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
610
611     /* we will read 100ms for each stream so ...*/
612     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
613
614     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
615     {
616         mp4_track_t *tk = &p_sys->track[i_track];
617
618         if( !tk->b_ok || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
619         {
620             continue;
621         }
622
623         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
624         {
625 #if 0
626             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
627                      MP4_TrackGetDTS( p_demux, tk ),
628                      MP4_GetMoviePTS( p_sys ) );
629 #endif
630
631             if( MP4_TrackSampleSize( tk ) > 0 )
632             {
633                 block_t *p_block;
634                 int64_t i_delta;
635
636                 /* go,go go ! */
637                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
638                 {
639                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
640                               tk->i_track_ID );
641                     MP4_TrackUnselect( p_demux, tk );
642                     break;
643                 }
644
645                 /* now read pes */
646                 if( !(p_block =
647                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
648                 {
649                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
650                               tk->i_track_ID );
651                     MP4_TrackUnselect( p_demux, tk );
652                     break;
653                 }
654
655                 if( tk->b_drms && tk->p_drms )
656                 {
657                     drms_decrypt( tk->p_drms, (uint32_t*)p_block->p_buffer,
658                                   p_block->i_buffer );
659                 }
660                 else if( tk->fmt.i_cat == SPU_ES )
661                 {
662                     if( tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
663                         p_block->i_buffer >= 2 )
664                     {
665                         uint16_t i_size = GetWBE( p_block->p_buffer );
666
667                         if( i_size + 2 <= p_block->i_buffer )
668                         {
669                             char *p;
670                             /* remove the length field, and append a '\0' */
671                             memmove( &p_block->p_buffer[0],
672                                      &p_block->p_buffer[2], i_size );
673                             p_block->p_buffer[i_size] = '\0';
674                             p_block->i_buffer = i_size + 1;
675
676                             /* convert \r -> \n */
677                             while( ( p = strchr( p_block->p_buffer, '\r' ) ) )
678                             {
679                                 *p = '\n';
680                             }
681                         }
682                         else
683                         {
684                             /* Invalid */
685                             p_block->i_buffer = 0;
686                         }
687                     }
688                 }
689                 /* dts */
690                 p_block->i_dts = MP4_TrackGetDTS( p_demux, tk ) + 1;
691                 /* pts */
692                 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
693                 if( i_delta != -1 )
694                     p_block->i_pts = p_block->i_dts + i_delta;
695                 else if( tk->fmt.i_cat != VIDEO_ES )
696                     p_block->i_pts = p_block->i_dts;
697                 else
698                     p_block->i_pts = 0;
699
700                 if( !tk->b_drms || ( tk->b_drms && tk->p_drms ) )
701                     es_out_Send( p_demux->out, tk->p_es, p_block );
702             }
703
704             /* Next sample */
705             if( MP4_TrackNextSample( p_demux, tk ) )
706             {
707                 break;
708             }
709         }
710     }
711
712     return 1;
713 }
714 /*****************************************************************************
715  * Seek: Got to i_date
716 ******************************************************************************/
717 static int Seek( demux_t *p_demux, mtime_t i_date )
718 {
719     demux_sys_t *p_sys = p_demux->p_sys;
720     unsigned int i_track;
721
722     /* First update update global time */
723     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
724     p_sys->i_pcr  = i_date;
725
726     /* Now for each stream try to go to this time */
727     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
728     {
729         mp4_track_t *tk = &p_sys->track[i_track];
730         MP4_TrackSeek( p_demux, tk, i_date );
731     }
732     return VLC_SUCCESS;
733 }
734
735 /*****************************************************************************
736  * Control:
737  *****************************************************************************/
738 static int Control( demux_t *p_demux, int i_query, va_list args )
739 {
740     demux_sys_t *p_sys = p_demux->p_sys;
741
742     double f, *pf;
743     int64_t i64, *pi64;
744
745     switch( i_query )
746     {
747         case DEMUX_GET_POSITION:
748             pf = (double*)va_arg( args, double * );
749             if( p_sys->i_duration > 0 )
750             {
751                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
752             }
753             else
754             {
755                 *pf = 0.0;
756             }
757             return VLC_SUCCESS;
758
759         case DEMUX_SET_POSITION:
760             f = (double)va_arg( args, double );
761             if( p_sys->i_timescale > 0 )
762             {
763                 i64 = (int64_t)( f * (double)1000000 *
764                                  (double)p_sys->i_duration /
765                                  (double)p_sys->i_timescale );
766                 return Seek( p_demux, i64 );
767             }
768             else return VLC_SUCCESS;
769
770         case DEMUX_GET_TIME:
771             pi64 = (int64_t*)va_arg( args, int64_t * );
772             if( p_sys->i_timescale > 0 )
773             {
774                 *pi64 = (mtime_t)1000000 *
775                         (mtime_t)p_sys->i_time /
776                         (mtime_t)p_sys->i_timescale;
777             }
778             else *pi64 = 0;
779             return VLC_SUCCESS;
780
781         case DEMUX_SET_TIME:
782             i64 = (int64_t)va_arg( args, int64_t );
783             return Seek( p_demux, i64 );
784
785         case DEMUX_GET_LENGTH:
786             pi64 = (int64_t*)va_arg( args, int64_t * );
787             if( p_sys->i_timescale > 0 )
788             {
789                 *pi64 = (mtime_t)1000000 *
790                         (mtime_t)p_sys->i_duration /
791                         (mtime_t)p_sys->i_timescale;
792             }
793             else *pi64 = 0;
794             return VLC_SUCCESS;
795
796         case DEMUX_GET_FPS:
797             msg_Warn( p_demux, "DEMUX_GET_FPS unimplemented !!" );
798             return VLC_EGENERIC;
799
800         case DEMUX_GET_META:
801         {
802             vlc_meta_t **pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
803             vlc_meta_t *meta;
804             MP4_Box_t  *p_udta   = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
805             MP4_Box_t  *p_0xa9xxx;
806             if( p_udta == NULL )
807             {
808                 return VLC_EGENERIC;
809             }
810             *pp_meta = meta = vlc_meta_New();
811             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
812                  p_0xa9xxx = p_0xa9xxx->p_next )
813             {
814                 switch( p_0xa9xxx->i_type )
815                 {
816                 case FOURCC_0xa9nam: /* Full name */
817                     vlc_meta_Add( meta, VLC_META_TITLE,
818                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
819                     break;
820                 case FOURCC_0xa9aut:
821                     vlc_meta_Add( meta, VLC_META_AUTHOR,
822                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
823                     break;
824                 case FOURCC_0xa9ART:
825                     vlc_meta_Add( meta, VLC_META_ARTIST,
826                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
827                     break;
828                 case FOURCC_0xa9cpy:
829                     vlc_meta_Add( meta, VLC_META_COPYRIGHT,
830                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
831                     break;
832                 case FOURCC_0xa9day: /* Creation Date */
833                     vlc_meta_Add( meta, VLC_META_DATE,
834                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
835                     break;
836                 case FOURCC_0xa9des: /* Description */
837                     vlc_meta_Add( meta, VLC_META_DESCRIPTION,
838                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
839                     break;
840                 case FOURCC_0xa9gen: /* Genre */
841                     vlc_meta_Add( meta, VLC_META_GENRE,
842                                   p_0xa9xxx->data.p_0xa9xxx->psz_text );
843                     break;
844
845                 case FOURCC_0xa9swr:
846                 case FOURCC_0xa9inf: /* Information */
847                 case FOURCC_0xa9alb: /* Album */
848                 case FOURCC_0xa9dir: /* Director */
849                 case FOURCC_0xa9dis: /* Disclaimer */
850                 case FOURCC_0xa9enc: /* Encoded By */
851                 case FOURCC_0xa9trk: /* Track */
852                 case FOURCC_0xa9cmt: /* Commment */
853                 case FOURCC_0xa9url: /* URL */
854                 case FOURCC_0xa9req: /* Requirements */
855                 case FOURCC_0xa9fmt: /* Original Format */
856                 case FOURCC_0xa9dsa: /* Display Source As */
857                 case FOURCC_0xa9hst: /* Host Computer */
858                 case FOURCC_0xa9prd: /* Producer */
859                 case FOURCC_0xa9prf: /* Performers */
860                 case FOURCC_0xa9ope: /* Original Performer */
861                 case FOURCC_0xa9src: /* Providers Source Content */
862                 case FOURCC_0xa9wrt: /* Writer */
863                 case FOURCC_0xa9com: /* Composer */
864                 case FOURCC_WLOC:    /* Window Location */
865                     /* TODO one day, but they aren't really meaningfull */
866                     break;
867
868                 default:
869                     break;
870                 }
871             }
872             return VLC_SUCCESS;
873         }
874
875         case DEMUX_GET_TITLE_INFO:
876         case DEMUX_SET_NEXT_DEMUX_TIME:
877         case DEMUX_SET_GROUP:
878             return VLC_EGENERIC;
879
880         default:
881             msg_Warn( p_demux, "control query unimplemented !!!" );
882             return VLC_EGENERIC;
883     }
884 }
885
886 /*****************************************************************************
887  * Close: frees unused data
888  *****************************************************************************/
889 static void Close ( vlc_object_t * p_this )
890 {
891     unsigned int i_track;
892     demux_t *  p_demux = (demux_t *)p_this;
893     demux_sys_t *p_sys = p_demux->p_sys;
894
895     msg_Dbg( p_demux, "freeing all memory" );
896
897     MP4_BoxFree( p_demux->s, p_sys->p_root );
898     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
899     {
900         MP4_TrackDestroy( p_demux, &p_sys->track[i_track] );
901     }
902     FREE( p_sys->track );
903
904     free( p_sys );
905 }
906
907
908
909 /****************************************************************************
910  * Local functions, specific to vlc
911  ****************************************************************************/
912
913 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
914 static int TrackCreateChunksIndex( demux_t *p_demux,
915                                    mp4_track_t *p_demux_track )
916 {
917     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
918     MP4_Box_t *p_stsc;
919
920     unsigned int i_chunk;
921     unsigned int i_index, i_last;
922
923     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
924           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
925         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
926     {
927         return( VLC_EGENERIC );
928     }
929
930     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
931     if( !p_demux_track->i_chunk_count )
932     {
933         msg_Warn( p_demux, "no chunk defined" );
934         return( VLC_EGENERIC );
935     }
936     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
937                                    sizeof( mp4_chunk_t ) );
938
939     /* first we read chunk offset */
940     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
941     {
942         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
943
944         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
945
946         ck->i_first_dts = 0;
947         ck->p_sample_count_dts = NULL;
948         ck->p_sample_delta_dts = NULL;
949         ck->p_sample_count_pts = NULL;
950         ck->p_sample_offset_pts = NULL;
951     }
952
953     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
954         to be used for the sample XXX begin to 1
955         We construct it begining at the end */
956     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
957     i_index = p_stsc->data.p_stsc->i_entry_count;
958     if( !i_index )
959     {
960         msg_Warn( p_demux, "cannot read chunk table or table empty" );
961         return( VLC_EGENERIC );
962     }
963
964     while( i_index-- )
965     {
966         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
967              i_chunk < i_last; i_chunk++ )
968         {
969             p_demux_track->chunk[i_chunk].i_sample_description_index =
970                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
971             p_demux_track->chunk[i_chunk].i_sample_count =
972                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
973         }
974         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
975     }
976
977     p_demux_track->chunk[0].i_sample_first = 0;
978     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
979     {
980         p_demux_track->chunk[i_chunk].i_sample_first =
981             p_demux_track->chunk[i_chunk-1].i_sample_first +
982                 p_demux_track->chunk[i_chunk-1].i_sample_count;
983     }
984
985     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
986              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
987
988     return VLC_SUCCESS;
989 }
990
991 static int TrackCreateSamplesIndex( demux_t *p_demux,
992                                     mp4_track_t *p_demux_track )
993 {
994     MP4_Box_t *p_box;
995     MP4_Box_data_stsz_t *stsz;
996     MP4_Box_data_stts_t *stts;
997     /* TODO use also stss and stsh table for seeking */
998     /* FIXME use edit table */
999     int64_t i_sample;
1000     int64_t i_chunk;
1001
1002     int64_t i_index;
1003     int64_t i_index_sample_used;
1004
1005     int64_t i_last_dts;
1006
1007     /* Find stsz
1008      *  Gives the sample size for each samples. There is also a stz2 table
1009      *  (compressed form) that we need to implement TODO */
1010     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1011     if( !p_box )
1012     {
1013         /* FIXME and stz2 */
1014         msg_Warn( p_demux, "cannot find STSZ box" );
1015         return VLC_EGENERIC;
1016     }
1017     stsz = p_box->data.p_stsz;
1018
1019     /* Find stts
1020      *  Gives mapping between sample and decoding time
1021      */
1022     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1023     if( !p_box )
1024     {
1025         msg_Warn( p_demux, "cannot find STTS box" );
1026         return VLC_EGENERIC;
1027     }
1028     stts = p_box->data.p_stts;
1029
1030     /* Use stsz table to create a sample number -> sample size table */
1031     p_demux_track->i_sample_count = stsz->i_sample_count;
1032     if( stsz->i_sample_size )
1033     {
1034         /* 1: all sample have the same size, so no need to construct a table */
1035         p_demux_track->i_sample_size = stsz->i_sample_size;
1036         p_demux_track->p_sample_size = NULL;
1037     }
1038     else
1039     {
1040         /* 2: each sample can have a different size */
1041         p_demux_track->i_sample_size = 0;
1042         p_demux_track->p_sample_size =
1043             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1044
1045         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1046         {
1047             p_demux_track->p_sample_size[i_sample] =
1048                     stsz->i_entry_size[i_sample];
1049         }
1050     }
1051
1052     /* Use stts table to create a sample number -> dts table.
1053      * XXX: if we don't want to waste too much memory, we can't expand
1054      *  the box! so each chunk will contain an "extract" of this table
1055      *  for fast research (problem with raw stream where a sample is sometime
1056      *  just channels*bits_per_sample/8 */
1057
1058     i_last_dts = 0;
1059     i_index = 0; i_index_sample_used = 0;
1060     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1061     {
1062         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1063         int64_t i_entry, i_sample_count, i;
1064
1065         /* save last dts */
1066         ck->i_first_dts = i_last_dts;
1067
1068         /* count how many entries are needed for this chunk
1069          * for p_sample_delta_dts and p_sample_count_dts */
1070         i_sample_count = ck->i_sample_count;
1071
1072         i_entry = 0;
1073         while( i_sample_count > 0 )
1074         {
1075             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1076             /* don't count already used sample in this entry */
1077             if( i_entry == 0 )
1078                 i_sample_count += i_index_sample_used;
1079
1080             i_entry++;
1081         }
1082
1083         /* allocate them */
1084         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1085         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1086
1087         /* now copy */
1088         i_sample_count = ck->i_sample_count;
1089         for( i = 0; i < i_entry; i++ )
1090         {
1091             int64_t i_used;
1092             int64_t i_rest;
1093
1094             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1095
1096             i_used = __MIN( i_rest, i_sample_count );
1097
1098             i_index_sample_used += i_used;
1099             i_sample_count -= i_used;
1100
1101             ck->p_sample_count_dts[i] = i_used;
1102             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1103
1104             i_last_dts += i_used * ck->p_sample_delta_dts[i];
1105
1106             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1107             {
1108                 i_index++;
1109                 i_index_sample_used = 0;
1110             }
1111         }
1112     }
1113
1114     /* Find ctts
1115      *  Gives the delta between decoding time (dts) and composition table (pts)
1116      */
1117     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1118     if( p_box )
1119     {
1120         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1121
1122         msg_Warn( p_demux, "CTTS table" );
1123
1124         /* Create pts-dts table per chunk */
1125         i_index = 0; i_index_sample_used = 0;
1126         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1127         {
1128             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1129             int64_t i_entry, i_sample_count, i;
1130
1131             /* count how many entries are needed for this chunk
1132              * for p_sample_delta_dts and p_sample_count_dts */
1133             i_sample_count = ck->i_sample_count;
1134
1135             i_entry = 0;
1136             while( i_sample_count > 0 )
1137             {
1138                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1139
1140                 /* don't count already used sample in this entry */
1141                 if( i_entry == 0 )
1142                     i_sample_count += i_index_sample_used;
1143
1144                 i_entry++;
1145             }
1146
1147             /* allocate them */
1148             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1149             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1150
1151             /* now copy */
1152             i_sample_count = ck->i_sample_count;
1153             for( i = 0; i < i_entry; i++ )
1154             {
1155                 int64_t i_used;
1156                 int64_t i_rest;
1157
1158                 i_rest = ctts->i_sample_count[i_index] -
1159                     i_index_sample_used;
1160
1161                 i_used = __MIN( i_rest, i_sample_count );
1162
1163                 i_index_sample_used += i_used;
1164                 i_sample_count -= i_used;
1165
1166                 ck->p_sample_count_pts[i] = i_used;
1167                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1168
1169                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1170                 {
1171                     i_index++;
1172                     i_index_sample_used = 0;
1173                 }
1174             }
1175         }
1176     }
1177
1178     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:"I64Fd"s",
1179              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1180              i_last_dts / p_demux_track->i_timescale );
1181
1182     return VLC_SUCCESS;
1183 }
1184
1185 /*
1186  * TrackCreateES:
1187  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1188  */
1189 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1190                           unsigned int i_chunk, es_out_id_t **pp_es )
1191 {
1192     MP4_Box_t   *p_sample;
1193     MP4_Box_t   *p_esds;
1194     MP4_Box_t   *p_box;
1195
1196     *pp_es = NULL;
1197
1198     if( !p_track->chunk[i_chunk].i_sample_description_index )
1199     {
1200         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1201                   p_track->i_track_ID );
1202         return VLC_EGENERIC;
1203     }
1204
1205     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1206                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
1207
1208     if( !p_sample ||
1209         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1210     {
1211         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1212                   p_track->i_track_ID );
1213         return VLC_EGENERIC;
1214     }
1215
1216     p_track->p_sample = p_sample;
1217
1218     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size == 1 )
1219     {
1220         MP4_Box_data_sample_soun_t *p_soun;
1221
1222         p_soun = p_sample->data.p_sample_soun;
1223
1224         if( p_soun->i_qt_version == 0 )
1225         {
1226             switch( p_sample->i_type )
1227             {
1228                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1229                     p_soun->i_qt_version = 1;
1230                     p_soun->i_sample_per_packet = 64;
1231                     p_soun->i_bytes_per_packet  = 34;
1232                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1233                     p_soun->i_bytes_per_sample  = 2;
1234                     break;
1235                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1236                     p_soun->i_qt_version = 1;
1237                     p_soun->i_sample_per_packet = 6;
1238                     p_soun->i_bytes_per_packet  = 2;
1239                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1240                     p_soun->i_bytes_per_sample  = 2;
1241                     break;
1242                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1243                     p_soun->i_qt_version = 1;
1244                     p_soun->i_sample_per_packet = 12;
1245                     p_soun->i_bytes_per_packet  = 2;
1246                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1247                     p_soun->i_bytes_per_sample  = 2;
1248                     break;
1249                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1250                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1251                     p_soun->i_samplesize = 8;
1252                     break;
1253                 default:
1254                     break;
1255             }
1256
1257         }
1258         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1259         {
1260             p_soun->i_qt_version = 0;
1261         }
1262     }
1263
1264
1265     /* It's a little ugly but .. there are special cases */
1266     switch( p_sample->i_type )
1267     {
1268         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1269         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1270             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1271             break;
1272         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1273             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1274             break;
1275         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1276             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1277             break;
1278
1279         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1280             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1281             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1282             /* FIXME UTF-8 doesn't work here ? */
1283             /* p_track->fmt.subs.psz_encoding = strdup( "UTF-8" ); */
1284             break;
1285
1286         default:
1287             p_track->fmt.i_codec = p_sample->i_type;
1288             break;
1289     }
1290
1291     /* now see if esds is present and if so create a data packet
1292         with decoder_specific_info  */
1293 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1294     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1295           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1296         ( p_esds->data.p_esds )&&
1297         ( p_decconfig ) )
1298     {
1299         /* First update information based on i_objectTypeIndication */
1300         switch( p_decconfig->i_objectTypeIndication )
1301         {
1302             case( 0x20 ): /* MPEG4 VIDEO */
1303                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1304                 break;
1305             case( 0x40):
1306                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1307                 break;
1308             case( 0x60):
1309             case( 0x61):
1310             case( 0x62):
1311             case( 0x63):
1312             case( 0x64):
1313             case( 0x65): /* MPEG2 video */
1314                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1315                 break;
1316             /* Theses are MPEG2-AAC */
1317             case( 0x66): /* main profile */
1318             case( 0x67): /* Low complexity profile */
1319             case( 0x68): /* Scaleable Sampling rate profile */
1320                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1321                 break;
1322             /* true MPEG 2 audio */
1323             case( 0x69):
1324                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1325                 break;
1326             case( 0x6a): /* MPEG1 video */
1327                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1328                 break;
1329             case( 0x6b): /* MPEG1 audio */
1330                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1331                 break;
1332             case( 0x6c ): /* jpeg */
1333                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1334                 break;
1335
1336             /* Private ID */
1337             case( 0xe0 ): /* NeroDigital: dvd subs */
1338                 if( p_track->fmt.i_cat == SPU_ES )
1339                 {
1340                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1341                     break;
1342                 }
1343             /* Fallback */
1344             default:
1345                 /* Unknown entry, but don't touch i_fourcc */
1346                 msg_Warn( p_demux,
1347                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1348                           p_decconfig->i_objectTypeIndication,
1349                           p_track->i_track_ID );
1350                 break;
1351         }
1352         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1353         if( p_track->fmt.i_extra > 0 )
1354         {
1355             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1356             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1357                     p_track->fmt.i_extra );
1358         }
1359     }
1360     else
1361     {
1362         switch( p_sample->i_type )
1363         {
1364             /* qt decoder, send the complete chunk */
1365             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1366             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1367             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1368             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1369             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1370                 p_track->fmt.i_extra =
1371                     p_sample->data.p_sample_vide->i_qt_image_description;
1372                 if( p_track->fmt.i_extra > 0 )
1373                 {
1374                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1375                     memcpy( p_track->fmt.p_extra,
1376                             p_sample->data.p_sample_vide->p_qt_image_description,
1377                             p_track->fmt.i_extra);
1378                 }
1379                 break;
1380             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1381             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1382             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1383             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1384             case VLC_FOURCC( 'a', 'l', 'a', 'c' ):
1385                 p_track->fmt.i_extra =
1386                     p_sample->data.p_sample_soun->i_qt_description;
1387                 if( p_track->fmt.i_extra > 0 )
1388                 {
1389                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1390                     memcpy( p_track->fmt.p_extra,
1391                             p_sample->data.p_sample_soun->p_qt_description,
1392                             p_track->fmt.i_extra);
1393                 }
1394                 break;
1395
1396             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1397             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1398             {
1399                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1400
1401                 if( p_avcC )
1402                 {
1403                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1404                     p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1405                     memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
1406                             p_track->fmt.i_extra );
1407                 }
1408                 else
1409                 {
1410                     msg_Err( p_demux, "missing avcC" );
1411                 }
1412                 break;
1413             }
1414
1415             default:
1416                 break;
1417         }
1418     }
1419
1420 #undef p_decconfig
1421
1422     /* some last initialisation */
1423     switch( p_track->fmt.i_cat )
1424     {
1425     case( VIDEO_ES ):
1426         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1427         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1428
1429         /* fall on display size */
1430         if( p_track->fmt.video.i_width <= 0 )
1431             p_track->fmt.video.i_width = p_track->i_width;
1432         if( p_track->fmt.video.i_height <= 0 )
1433             p_track->fmt.video.i_height = p_track->i_height;
1434
1435         /* Find out apect ratio from display size */
1436         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1437             /* Work-around buggy muxed files */
1438             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1439             p_track->fmt.video.i_aspect =
1440                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1441
1442         /* Frame rate */
1443         p_track->fmt.video.i_frame_rate = p_track->i_timescale;
1444         p_track->fmt.video.i_frame_rate_base = 1;
1445
1446         if( p_track->fmt.video.i_frame_rate &&
1447             (p_box = MP4_BoxGet( p_track->p_stbl, "stts" )) &&
1448             p_box->data.p_stts->i_entry_count >= 1 )
1449         {
1450             p_track->fmt.video.i_frame_rate_base =
1451                 p_box->data.p_stts->i_sample_delta[0];
1452         }
1453
1454         break;
1455
1456     case( AUDIO_ES ):
1457         p_track->fmt.audio.i_channels =
1458             p_sample->data.p_sample_soun->i_channelcount;
1459         p_track->fmt.audio.i_rate =
1460             p_sample->data.p_sample_soun->i_sampleratehi;
1461         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1462             p_sample->data.p_sample_soun->i_sampleratehi *
1463                 p_sample->data.p_sample_soun->i_samplesize;
1464         p_track->fmt.audio.i_bitspersample =
1465             p_sample->data.p_sample_soun->i_samplesize;
1466         break;
1467
1468     default:
1469         break;
1470     }
1471
1472     *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1473
1474     return VLC_SUCCESS;
1475 }
1476
1477 /* given a time it return sample/chunk
1478  * it also update elst field of the track
1479  */
1480 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1481                                    int64_t i_start, uint32_t *pi_chunk,
1482                                    uint32_t *pi_sample )
1483 {
1484     demux_sys_t *p_sys = p_demux->p_sys;
1485     MP4_Box_t   *p_stss;
1486     uint64_t     i_dts;
1487     unsigned int i_sample;
1488     unsigned int i_chunk;
1489     int          i_index;
1490
1491     /* FIXME see if it's needed to check p_track->i_chunk_count */
1492     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1493     {
1494         return( VLC_EGENERIC );
1495     }
1496
1497     /* handle elst (find the correct one) */
1498     MP4_TrackSetELST( p_demux, p_track, i_start );
1499     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1500     {
1501         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1502         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1503
1504         /* now calculate i_start for this elst */
1505         /* offset */
1506         i_start -= p_track->i_elst_time * I64C(1000000) / p_sys->i_timescale;
1507         if( i_start < 0 )
1508         {
1509             *pi_chunk = 0;
1510             *pi_sample= 0;
1511
1512             return VLC_SUCCESS;
1513         }
1514         /* to track time scale */
1515         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1516         /* add elst offset */
1517         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1518              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1519             elst->i_media_time[p_track->i_elst] > 0 )
1520         {
1521             i_start += elst->i_media_time[p_track->i_elst];
1522         }
1523
1524         msg_Dbg( p_demux, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd
1525                  "ms (track)", p_track->i_elst,
1526                  i_mvt * 1000 / p_sys->i_timescale,
1527                  i_start * 1000 / p_track->i_timescale );
1528     }
1529     else
1530     {
1531         /* convert absolute time to in timescale unit */
1532         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1533     }
1534
1535     /* we start from sample 0/chunk 0, hope it won't take too much time */
1536     /* *** find good chunk *** */
1537     for( i_chunk = 0; ; i_chunk++ )
1538     {
1539         if( i_chunk + 1 >= p_track->i_chunk_count )
1540         {
1541             /* at the end and can't check if i_start in this chunk,
1542                it will be check while searching i_sample */
1543             i_chunk = p_track->i_chunk_count - 1;
1544             break;
1545         }
1546
1547         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1548             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1549         {
1550             break;
1551         }
1552     }
1553
1554     /* *** find sample in the chunk *** */
1555     i_sample = p_track->chunk[i_chunk].i_sample_first;
1556     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1557     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1558     {
1559         if( i_dts +
1560             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1561             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1562         {
1563             i_dts    +=
1564                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1565                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1566
1567             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1568             i_index++;
1569         }
1570         else
1571         {
1572             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1573             {
1574                 break;
1575             }
1576             i_sample += ( i_start - i_dts ) /
1577                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1578             break;
1579         }
1580     }
1581
1582     if( i_sample >= p_track->i_sample_count )
1583     {
1584         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1585                   "(seeking too far) chunk=%d sample=%d",
1586                   p_track->i_track_ID, i_chunk, i_sample );
1587         return( VLC_EGENERIC );
1588     }
1589
1590
1591     /* *** Try to find nearest sync points *** */
1592     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1593     {
1594         unsigned int i_index;
1595         msg_Dbg( p_demux,
1596                     "track[Id 0x%x] using Sync Sample Box (stss)",
1597                     p_track->i_track_ID );
1598         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1599         {
1600             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1601             {
1602                 if( i_index > 0 )
1603                 {
1604                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1605                             i_sample,
1606                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1607                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1608                     /* new i_sample is less than old so i_chunk can only decreased */
1609                     while( i_chunk > 0 &&
1610                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1611                     {
1612                         i_chunk--;
1613                     }
1614                 }
1615                 else
1616                 {
1617                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1618                             i_sample,
1619                             p_stss->data.p_stss->i_sample_number[i_index] );
1620                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1621                     /* new i_sample is more than old so i_chunk can only increased */
1622                     while( i_chunk < p_track->i_chunk_count - 1 &&
1623                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1624                              p_track->chunk[i_chunk].i_sample_count )
1625                     {
1626                         i_chunk++;
1627                     }
1628                 }
1629                 break;
1630             }
1631         }
1632     }
1633     else
1634     {
1635         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
1636                  "Sample Box (stss)", p_track->i_track_ID );
1637     }
1638
1639     *pi_chunk  = i_chunk;
1640     *pi_sample = i_sample;
1641
1642     return VLC_SUCCESS;
1643 }
1644
1645 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
1646                                  unsigned int i_chunk, unsigned int i_sample )
1647 {
1648     vlc_bool_t b_reselect = VLC_FALSE;
1649
1650     /* now see if actual es is ok */
1651     if( p_track->i_chunk < 0 ||
1652         p_track->i_chunk >= p_track->i_chunk_count - 1 ||
1653         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1654             p_track->chunk[i_chunk].i_sample_description_index )
1655     {
1656         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
1657                   p_track->i_track_ID );
1658
1659         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1660                         p_track->p_es, &b_reselect );
1661
1662         es_out_Del( p_demux->out, p_track->p_es );
1663
1664         p_track->p_es = NULL;
1665
1666         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
1667         {
1668             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1669                      p_track->i_track_ID );
1670
1671             p_track->b_ok       = VLC_FALSE;
1672             p_track->b_selected = VLC_FALSE;
1673             return VLC_EGENERIC;
1674         }
1675     }
1676
1677     /* select again the new decoder */
1678     if( b_reselect )
1679     {
1680         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
1681     }
1682
1683     p_track->i_chunk    = i_chunk;
1684     p_track->i_sample   = i_sample;
1685
1686     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1687 }
1688
1689 /****************************************************************************
1690  * MP4_TrackCreate:
1691  ****************************************************************************
1692  * Parse track information and create all needed data to run a track
1693  * If it succeed b_ok is set to 1 else to 0
1694  ****************************************************************************/
1695 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
1696                              MP4_Box_t *p_box_trak )
1697 {
1698     demux_sys_t *p_sys = p_demux->p_sys;
1699
1700     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1701     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1702     MP4_Box_t *p_elst;
1703
1704     MP4_Box_t *p_mdhd;
1705     MP4_Box_t *p_udta;
1706     MP4_Box_t *p_hdlr;
1707
1708     MP4_Box_t *p_vmhd;
1709     MP4_Box_t *p_smhd;
1710
1711     MP4_Box_t *p_drms;
1712
1713     unsigned int i;
1714     char language[4];
1715
1716     /* hint track unsuported */
1717
1718     /* set default value (-> track unusable) */
1719     p_track->b_ok       = VLC_FALSE;
1720     p_track->b_enable   = VLC_FALSE;
1721     p_track->b_selected = VLC_FALSE;
1722
1723     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1724
1725     if( !p_tkhd )
1726     {
1727         return;
1728     }
1729
1730     /* do we launch this track by default ? */
1731     p_track->b_enable =
1732         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1733
1734     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1735     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1736     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1737
1738     if( p_tref )
1739     {
1740 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
1741     }
1742
1743     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1744     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1745
1746     if( ( !p_mdhd )||( !p_hdlr ) )
1747     {
1748         return;
1749     }
1750
1751     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1752
1753     for( i = 0; i < 3; i++ )
1754     {
1755         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1756     }
1757     language[3] = '\0';
1758
1759     switch( p_hdlr->data.p_hdlr->i_handler_type )
1760     {
1761         case( FOURCC_soun ):
1762             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1763             {
1764                 return;
1765             }
1766             p_track->fmt.i_cat = AUDIO_ES;
1767             break;
1768
1769         case( FOURCC_vide ):
1770             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1771             {
1772                 return;
1773             }
1774             p_track->fmt.i_cat = VIDEO_ES;
1775             break;
1776
1777         case( FOURCC_text ):
1778         case( FOURCC_subp ):
1779             p_track->fmt.i_cat = SPU_ES;
1780             break;
1781
1782         default:
1783             return;
1784     }
1785
1786     p_track->i_elst = 0;
1787     p_track->i_elst_time = 0;
1788     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1789     {
1790         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
1791         int i;
1792
1793         msg_Warn( p_demux, "elst box found" );
1794         for( i = 0; i < elst->i_entry_count; i++ )
1795         {
1796             msg_Dbg( p_demux, "   - [%d] duration="I64Fd"ms media time="I64Fd
1797                      "ms) rate=%d.%d", i,
1798                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
1799                      elst->i_media_time[i] >= 0 ?
1800                      elst->i_media_time[i] * 1000 / p_track->i_timescale : -1,
1801                      elst->i_media_rate_integer[i],
1802                      elst->i_media_rate_fraction[i] );
1803         }
1804     }
1805
1806
1807 /*  TODO
1808     add support for:
1809     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1810 */
1811     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1812         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1813     {
1814         return;
1815     }
1816
1817     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
1818     p_track->b_drms = p_drms != NULL;
1819     p_track->p_drms = p_track->b_drms ?
1820         p_drms->data.p_sample_soun->p_drms : NULL;
1821
1822     /* Set language */
1823     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1824     {
1825         p_track->fmt.psz_language = strdup( language );
1826     }
1827
1828     p_udta = MP4_BoxGet( p_box_trak, "udta" );
1829     if( p_udta )
1830     {
1831         MP4_Box_t *p_0xa9xxx;
1832         for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1833                  p_0xa9xxx = p_0xa9xxx->p_next )
1834         {
1835             switch( p_0xa9xxx->i_type )
1836             {
1837                 case FOURCC_0xa9nam:
1838                     p_track->fmt.psz_description =
1839                         strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text );
1840                     break;
1841             }
1842         }
1843     }
1844
1845     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1846     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1847     {
1848         MP4_Box_t *p_sample;
1849
1850         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1851         if( p_sample && p_sample->data.p_sample_soun)
1852         {
1853             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1854             if( p_soun->i_qt_version == 0 &&
1855                 p_track->i_timescale != p_soun->i_sampleratehi )
1856             {
1857                 msg_Warn( p_demux,
1858                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1859                           "qt_version == 0\n"
1860                           "Making both equal. (report any problem)",
1861                           p_track->i_timescale, p_soun->i_sampleratehi );
1862
1863                 if( p_soun->i_sampleratehi )
1864                     p_track->i_timescale = p_soun->i_sampleratehi;
1865                 else
1866                     p_soun->i_sampleratehi = p_track->i_timescale;
1867             }
1868         }
1869     }
1870
1871     /* Create chunk index table and sample index table */
1872     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
1873         TrackCreateSamplesIndex( p_demux, p_track ) )
1874     {
1875         return; /* cannot create chunks index */
1876     }
1877
1878     p_track->i_chunk  = 0;
1879     p_track->i_sample = 0;
1880
1881     /* now create es */
1882     if( TrackCreateES( p_demux,
1883                        p_track, p_track->i_chunk,
1884                        &p_track->p_es ) )
1885     {
1886         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1887                  p_track->i_track_ID );
1888         return;
1889     }
1890
1891 #if 0
1892     {
1893         int i;
1894         for( i = 0; i < p_track->i_chunk_count; i++ )
1895         {
1896             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
1897                      i, p_track->chunk[i].i_sample_count,
1898                      p_track->chunk[i].i_first_dts );
1899
1900         }
1901     }
1902 #endif
1903     p_track->b_ok = VLC_TRUE;
1904 }
1905
1906 /****************************************************************************
1907  * MP4_TrackDestroy:
1908  ****************************************************************************
1909  * Destroy a track created by MP4_TrackCreate.
1910  ****************************************************************************/
1911 static void MP4_TrackDestroy( demux_t *p_demux, mp4_track_t *p_track )
1912 {
1913     unsigned int i_chunk;
1914
1915     p_track->b_ok = VLC_FALSE;
1916     p_track->b_enable   = VLC_FALSE;
1917     p_track->b_selected = VLC_FALSE;
1918
1919     es_format_Clean( &p_track->fmt );
1920
1921     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1922     {
1923         if( p_track->chunk )
1924         {
1925            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1926            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1927
1928            FREE(p_track->chunk[i_chunk].p_sample_count_pts);
1929            FREE(p_track->chunk[i_chunk].p_sample_offset_pts );
1930         }
1931     }
1932     FREE( p_track->chunk );
1933
1934     if( !p_track->i_sample_size )
1935     {
1936         FREE( p_track->p_sample_size );
1937     }
1938 }
1939
1940 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
1941                             mtime_t i_start )
1942 {
1943     if( !p_track->b_ok )
1944     {
1945         return VLC_EGENERIC;
1946     }
1947
1948     if( p_track->b_selected )
1949     {
1950         msg_Warn( p_demux, "track[Id 0x%x] already selected",
1951                   p_track->i_track_ID );
1952         return VLC_SUCCESS;
1953     }
1954
1955     return MP4_TrackSeek( p_demux, p_track, i_start );
1956 }
1957
1958 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
1959 {
1960     if( !p_track->b_ok )
1961     {
1962         return;
1963     }
1964
1965     if( !p_track->b_selected )
1966     {
1967         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
1968                   p_track->i_track_ID );
1969         return;
1970     }
1971     if( p_track->p_es )
1972     {
1973         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
1974                         p_track->p_es, VLC_FALSE );
1975     }
1976
1977     p_track->b_selected = VLC_FALSE;
1978 }
1979
1980 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
1981                           mtime_t i_start )
1982 {
1983     uint32_t i_chunk;
1984     uint32_t i_sample;
1985
1986     if( !p_track->b_ok )
1987     {
1988         return( VLC_EGENERIC );
1989     }
1990
1991     p_track->b_selected = VLC_FALSE;
1992
1993     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
1994                                 &i_chunk, &i_sample ) )
1995     {
1996         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
1997                   p_track->i_track_ID );
1998         return( VLC_EGENERIC );
1999     }
2000
2001     p_track->b_selected = VLC_TRUE;
2002
2003     if( TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) ==
2004         VLC_SUCCESS )
2005     {
2006         p_track->b_selected = VLC_TRUE;
2007     }
2008     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
2009 }
2010
2011
2012 /*
2013  * 3 types: for audio
2014  * 
2015  */
2016 #define QT_V0_MAX_SAMPLES 1024
2017 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2018 {
2019     int i_size;
2020     MP4_Box_data_sample_soun_t *p_soun;
2021
2022     if( p_track->i_sample_size == 0 )
2023     {
2024         /* most simple case */
2025         return p_track->p_sample_size[p_track->i_sample];
2026     }
2027     if( p_track->fmt.i_cat != AUDIO_ES )
2028     {
2029         return p_track->i_sample_size;
2030     }
2031
2032     p_soun = p_track->p_sample->data.p_sample_soun;
2033
2034     if( p_soun->i_qt_version == 1 )
2035     {
2036         i_size = p_track->chunk[p_track->i_chunk].i_sample_count /
2037             p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2038     }
2039     else if( p_track->i_sample_size > 256 )
2040     {
2041         /* We do that so we don't read too much data
2042          * (in this case we are likely dealing with compressed data) */
2043         i_size = p_track->i_sample_size;
2044     }
2045     else
2046     {
2047         /* Read a bunch of samples at once */
2048         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2049             ( p_track->i_sample -
2050               p_track->chunk[p_track->i_chunk].i_sample_first );
2051
2052         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2053         i_size = i_samples * p_track->i_sample_size;
2054     }
2055
2056     //fprintf( stderr, "size=%d\n", i_size );
2057     return i_size;
2058 }
2059
2060 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2061 {
2062     unsigned int i_sample;
2063     uint64_t i_pos;
2064
2065     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2066
2067     if( p_track->i_sample_size )
2068     {
2069         MP4_Box_data_sample_soun_t *p_soun =
2070             p_track->p_sample->data.p_sample_soun;
2071
2072         if( p_soun->i_qt_version == 0 )
2073         {
2074             i_pos += ( p_track->i_sample -
2075                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2076                      p_track->i_sample_size;
2077         }
2078         else
2079         {
2080             /* we read chunk by chunk */
2081             i_pos += 0;
2082         }
2083     }
2084     else
2085     {
2086         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2087              i_sample < p_track->i_sample; i_sample++ )
2088         {
2089             i_pos += p_track->p_sample_size[i_sample];
2090         }
2091     }
2092
2093     return i_pos;
2094 }
2095
2096 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2097 {
2098     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2099     {
2100         MP4_Box_data_sample_soun_t *p_soun;
2101
2102         p_soun = p_track->p_sample->data.p_sample_soun;
2103
2104         if( p_soun->i_qt_version == 1 )
2105         {
2106             /* chunk by chunk */
2107             p_track->i_sample =
2108                 p_track->chunk[p_track->i_chunk].i_sample_first +
2109                 p_track->chunk[p_track->i_chunk].i_sample_count;
2110         }
2111         else if( p_track->i_sample_size > 256 )
2112         {
2113             /* We do that so we don't read too much data
2114              * (in this case we are likely dealing with compressed data) */
2115             p_track->i_sample += 1;
2116         }
2117         else
2118         {
2119             /* FIXME */
2120             p_track->i_sample += QT_V0_MAX_SAMPLES;
2121             if( p_track->i_sample >
2122                 p_track->chunk[p_track->i_chunk].i_sample_first +
2123                 p_track->chunk[p_track->i_chunk].i_sample_count )
2124             {
2125                 p_track->i_sample =
2126                     p_track->chunk[p_track->i_chunk].i_sample_first +
2127                     p_track->chunk[p_track->i_chunk].i_sample_count;
2128             }
2129         }
2130     }
2131     else
2132     {
2133         p_track->i_sample++;
2134     }
2135
2136     if( p_track->i_sample >= p_track->i_sample_count )
2137         return VLC_EGENERIC;
2138
2139     /* Have we changed chunk ? */
2140     if( p_track->i_sample >=
2141             p_track->chunk[p_track->i_chunk].i_sample_first +
2142             p_track->chunk[p_track->i_chunk].i_sample_count )
2143     {
2144         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2145                                   p_track->i_sample ) )
2146         {
2147             msg_Warn( p_demux, "track[0x%x] will be disabled "
2148                       "(cannot restart decoder)", p_track->i_track_ID );
2149             MP4_TrackUnselect( p_demux, p_track );
2150             return VLC_EGENERIC;
2151         }
2152     }
2153
2154     /* Have we changed elst */
2155     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2156     {
2157         demux_sys_t *p_sys = p_demux->p_sys;
2158         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2159         int64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2160                         p_sys->i_timescale / (int64_t)1000000;
2161
2162         if( p_track->i_elst < elst->i_entry_count &&
2163             i_mvt >= p_track->i_elst_time +
2164                      elst->i_segment_duration[p_track->i_elst] )
2165         {
2166             MP4_TrackSetELST( p_demux, p_track,
2167                               MP4_TrackGetDTS( p_demux, p_track ) );
2168         }
2169     }
2170
2171     return VLC_SUCCESS;
2172 }
2173
2174 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2175                               int64_t i_time )
2176 {
2177     demux_sys_t *p_sys = p_demux->p_sys;
2178     int         i_elst_last = tk->i_elst;
2179
2180     /* handle elst (find the correct one) */
2181     tk->i_elst      = 0;
2182     tk->i_elst_time = 0;
2183     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2184     {
2185         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2186         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2187
2188         for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2189         {
2190             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2191
2192             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2193             {
2194                 break;
2195             }
2196             tk->i_elst_time += i_dur;
2197         }
2198
2199         if( tk->i_elst >= elst->i_entry_count )
2200         {
2201             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2202             tk->i_elst = elst->i_entry_count - 1;
2203             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2204         }
2205
2206         if( elst->i_media_time[tk->i_elst] < 0 )
2207         {
2208             /* track offset */
2209             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2210         }
2211     }
2212     if( i_elst_last != tk->i_elst )
2213     {
2214         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2215     }
2216 }