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