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