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