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