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