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