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