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