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