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