]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
e8f3989052f798c8eeba467023c7147d358c76b0
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: mp4.c,v 1.46 2003/12/20 16:22:59 gbazin Exp $
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #include <stdlib.h>                                      /* malloc(), free() */
27
28 #include <vlc/vlc.h>
29 #include <vlc/input.h>
30 #include <vlc_playlist.h>
31
32 #include "libmp4.h"
33 #include "mp4.h"
34
35 /*****************************************************************************
36  * Module descriptor
37  *****************************************************************************/
38 static int  Open ( vlc_object_t * );
39 static void Close( vlc_object_t * );
40
41 vlc_module_begin();
42     set_description( _("MP4 demuxer") );
43     set_capability( "demux", 242 );
44     set_callbacks( Open, Close );
45 vlc_module_end();
46
47 /*****************************************************************************
48  * Local prototypes
49  *****************************************************************************/
50 static int    Demux   ( input_thread_t * );
51 static int    DemuxRef( input_thread_t *p_input )
52 {
53     return 0;
54 }
55 static int   Seek     ( input_thread_t *, mtime_t );
56 static int   Control  ( input_thread_t *, int, va_list );
57
58 /*****************************************************************************
59  * Declaration of local function
60  *****************************************************************************/
61 static void MP4_TrackCreate ( input_thread_t *, track_data_mp4_t *, MP4_Box_t  *);
62 static void MP4_TrackDestroy( input_thread_t *, track_data_mp4_t * );
63
64 static int  MP4_TrackSelect ( input_thread_t *, track_data_mp4_t *, mtime_t );
65 static void MP4_TrackUnselect(input_thread_t *, track_data_mp4_t * );
66
67 static int  MP4_TrackSeek   ( input_thread_t *, track_data_mp4_t *, mtime_t );
68
69 static uint64_t MP4_GetTrackPos    ( track_data_mp4_t * );
70 static int      MP4_TrackSampleSize( track_data_mp4_t * );
71 static int      MP4_TrackNextSample( input_thread_t *, track_data_mp4_t * );
72
73 #define FREE( p ) \
74     if( p ) { free( p ); (p) = NULL;}
75
76 /*****************************************************************************
77  * Open: check file and initializes MP4 structures
78  *****************************************************************************/
79 static int Open( vlc_object_t * p_this )
80 {
81     input_thread_t  *p_input = (input_thread_t *)p_this;
82     demux_sys_t     *p_sys;
83
84     uint8_t         *p_peek;
85
86     MP4_Box_t       *p_ftyp;
87     MP4_Box_t       *p_rmra;
88     MP4_Box_t       *p_mvhd;
89     MP4_Box_t       *p_trak;
90
91     unsigned int    i;
92     vlc_bool_t      b_seekable;
93
94     /* a little test to see if it could be a mp4 */
95     if( stream_Peek( p_input->s, &p_peek, 8 ) < 8 )
96     {
97         msg_Warn( p_input, "MP4 plugin discarded (cannot peek)" );
98         return VLC_EGENERIC;
99     }
100     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
101     {
102         case FOURCC_ftyp:
103         case FOURCC_moov:
104         case FOURCC_foov:
105         case FOURCC_moof:
106         case FOURCC_mdat:
107         case FOURCC_udta:
108         case FOURCC_free:
109         case FOURCC_skip:
110         case FOURCC_wide:
111             break;
112          default:
113             msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
114             return VLC_EGENERIC;
115     }
116
117     /* I need to seek */
118     stream_Control( p_input->s, STREAM_CAN_SEEK, &b_seekable );
119     if( !b_seekable )
120     {
121         msg_Warn( p_input, "MP4 plugin discarded (unseekable)" );
122         return VLC_EGENERIC;
123     }
124
125     /*Set exported functions */
126     p_input->pf_demux = Demux;
127     p_input->pf_demux_control = Control;
128
129     /* create our structure that will contains all data */
130     p_input->p_demux_data = p_sys = malloc( sizeof( demux_sys_t ) );
131     memset( p_sys, 0, sizeof( demux_sys_t ) );
132
133     /* Now load all boxes ( except raw data ) */
134     if( ( p_sys->p_root = MP4_BoxGetRoot( p_input ) ) == NULL )
135     {
136         msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
137         goto error;
138     }
139
140     MP4_BoxDumpStructure( p_input, p_sys->p_root );
141
142     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
143     {
144         switch( p_ftyp->data.p_ftyp->i_major_brand )
145         {
146             case( FOURCC_isom ):
147                 msg_Dbg( p_input,
148                          "ISO Media file (isom) version %d.",
149                          p_ftyp->data.p_ftyp->i_minor_version );
150                 break;
151             default:
152                 msg_Dbg( p_input,
153                          "unrecognized major file specification (%4.4s).",
154                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
155                 break;
156         }
157     }
158     else
159     {
160         msg_Dbg( p_input, "file type box missing (assuming ISO Media file)" );
161     }
162
163     /* the file need to have one moov box */
164     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
165     {
166         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
167
168         if( !p_foov )
169         {
170             msg_Err( p_input, "MP4 plugin discarded (no moov box)" );
171             goto error;
172         }
173         /* we have a free box as a moov, rename it */
174         p_foov->i_type = FOURCC_moov;
175     }
176
177     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
178     {
179         playlist_t *p_playlist;
180         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
181         int        i;
182
183         msg_Dbg( p_input, "detected playlist mov file (%d ref)", i_count );
184
185         p_playlist =
186             (playlist_t *)vlc_object_find( p_input,
187                                            VLC_OBJECT_PLAYLIST,
188                                            FIND_ANYWHERE );
189         if( p_playlist )
190         {
191             //p_playlist->pp_items[p_playlist->i_index]->b_autodeletion = VLC_TRUE;
192             for( i = 0; i < i_count; i++ )
193             {
194                 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
195                 char      *psz_ref;
196                 uint32_t  i_ref_type;
197
198                 if( !p_rdrf || !( psz_ref = p_rdrf->data.p_rdrf->psz_ref ) )
199                 {
200                     continue;
201                 }
202                 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
203
204                 msg_Dbg( p_input, "new ref=`%s' type=%4.4s",
205                          psz_ref, (char*)&i_ref_type );
206
207                 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
208                 {
209                     if( strstr( psz_ref, "qt5gateQT" ) )
210                     {
211                         msg_Dbg( p_input, "ignoring pseudo ref =`%s'", psz_ref );
212                         continue;
213                     }
214                     if( !strncmp( psz_ref, "http://", 7 ) ||
215                         !strncmp( psz_ref, "rtsp://", 7 ) )
216                     {
217                         msg_Dbg( p_input, "adding ref = `%s'", psz_ref );
218                         playlist_Add( p_playlist, psz_ref, 0, 0,
219                                       PLAYLIST_APPEND, PLAYLIST_END );
220                     }
221                     else
222                     {
223                         /* msg dbg relative ? */
224                         char *psz_absolute = alloca( strlen( p_input->psz_source ) + strlen( psz_ref ) + 1);
225                         char *end = strrchr( p_input->psz_source, '/' );
226
227                         if( end )
228                         {
229                             int i_len = end + 1 - p_input->psz_source;
230
231                             strncpy( psz_absolute, p_input->psz_source, i_len);
232                             psz_absolute[i_len] = '\0';
233                         }
234                         else
235                         {
236                             strcpy( psz_absolute, "" );
237                         }
238                         strcat( psz_absolute, psz_ref );
239                         msg_Dbg( p_input, "adding ref = `%s'", psz_absolute );
240                         playlist_Add( p_playlist, psz_absolute, 0, 0,
241                                       PLAYLIST_APPEND, PLAYLIST_END );
242                     }
243                 }
244                 else
245                 {
246                     msg_Err( p_input, "unknown ref type=%4.4s FIXME (send a bug report)", (char*)&p_rdrf->data.p_rdrf->i_ref_type );
247                 }
248             }
249             vlc_object_release( p_playlist );
250         }
251         else
252         {
253             msg_Err( p_input, "can't find playlist" );
254         }
255     }
256
257     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
258     {
259         if( !p_rmra )
260         {
261             msg_Err( p_input, "cannot find /moov/mvhd" );
262             goto error;
263         }
264         else
265         {
266             msg_Warn( p_input, "cannot find /moov/mvhd (pure ref file)" );
267             p_input->pf_demux = DemuxRef;
268             return VLC_SUCCESS;
269         }
270     }
271     else
272     {
273         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
274         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
275     }
276
277     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
278     {
279         msg_Err( p_input, "cannot find any /moov/trak" );
280         goto error;
281     }
282     msg_Dbg( p_input, "find %d track%c",
283                         p_sys->i_tracks,
284                         p_sys->i_tracks ? 's':' ' );
285
286     /*  create one program */
287     vlc_mutex_lock( &p_input->stream.stream_lock );
288     if( input_InitStream( p_input, 0 ) == -1)
289     {
290         vlc_mutex_unlock( &p_input->stream.stream_lock );
291         msg_Err( p_input, "cannot init stream" );
292         goto error;
293     }
294     if( p_sys->i_duration/p_sys->i_timescale > 0 )
295     {
296         p_input->stream.i_mux_rate =
297             p_input->stream.p_selected_area->i_size / 50 /
298             ( p_sys->i_duration / p_sys->i_timescale );
299     }
300     else
301     {
302         p_input->stream.i_mux_rate = 0;
303     }
304     vlc_mutex_unlock( &p_input->stream.stream_lock );
305
306
307     /* allocate memory */
308     p_sys->track = calloc( p_sys->i_tracks, sizeof( track_data_mp4_t ) );
309     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( track_data_mp4_t ) );
310
311     /* now process each track and extract all usefull informations */
312     for( i = 0; i < p_sys->i_tracks; i++ )
313     {
314         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
315         MP4_TrackCreate( p_input, &p_sys->track[i], p_trak );
316
317         if( p_sys->track[i].b_ok )
318         {
319             char *psz_cat;
320             switch( p_sys->track[i].fmt.i_cat )
321             {
322                 case( VIDEO_ES ):
323                     psz_cat = "video";
324                     break;
325                 case( AUDIO_ES ):
326                     psz_cat = "audio";
327                     break;
328                 default:
329                     psz_cat = "unknown";
330                     break;
331             }
332
333             msg_Dbg( p_input, "adding track[Id 0x%x] %s (%s) language %s",
334                             p_sys->track[i].i_track_ID,
335                             psz_cat,
336                             p_sys->track[i].b_enable ? "enable":"disable",
337                             p_sys->track[i].fmt.psz_language ? p_sys->track[i].fmt.psz_language : "undef" );
338         }
339         else
340         {
341             msg_Dbg( p_input, "ignoring track[Id 0x%x]", p_sys->track[i].i_track_ID );
342         }
343
344     }
345     return VLC_SUCCESS;
346
347 error:
348     if( p_sys->p_root )
349     {
350         MP4_BoxFree( p_input, p_sys->p_root );
351     }
352     free( p_sys );
353     return VLC_EGENERIC;
354 }
355
356 /*****************************************************************************
357  * Demux: read packet and send them to decoders
358  *****************************************************************************
359  * TODO check for newly selected track (ie audio upt to now )
360  *****************************************************************************/
361 static int Demux( input_thread_t *p_input )
362 {
363     demux_sys_t *p_sys = p_input->p_demux_data;
364     unsigned int i_track;
365
366
367     unsigned int i_track_selected;
368     vlc_bool_t   b_play_audio;
369
370     /* check for newly selected/unselected track */
371     for( i_track = 0, i_track_selected = 0; i_track <  p_sys->i_tracks; i_track++ )
372     {
373 #define track   p_sys->track[i_track]
374         if( track.b_selected && track.i_sample >= track.i_sample_count )
375         {
376             msg_Warn( p_input, "track[0x%x] will be disabled", track.i_track_ID );
377             MP4_TrackUnselect( p_input, &track );
378         }
379         else if( track.b_ok )
380         {
381             vlc_bool_t b;
382             es_out_Control( p_input->p_es_out, ES_OUT_GET_ES_STATE, track.p_es, &b );
383
384             if( track.b_selected && !b )
385             {
386                 MP4_TrackUnselect( p_input, &track );
387             }
388             else if( !track.b_selected && b)
389             {
390                 MP4_TrackSelect( p_input, &track, MP4_GetMoviePTS( p_sys ) );
391             }
392
393             if( track.b_selected )
394             {
395                 i_track_selected++;
396             }
397         }
398 #undef  track
399     }
400
401     if( i_track_selected <= 0 )
402     {
403         msg_Warn( p_input, "no track selected, exiting..." );
404         return( 0 );
405     }
406
407     /* first wait for the good time to read a packet */
408     input_ClockManageRef( p_input,
409                           p_input->stream.p_selected_program,
410                           p_sys->i_pcr );
411
412     /* update pcr XXX in mpeg scale so in 90000 unit/s */
413     p_sys->i_pcr = MP4_GetMoviePTS( p_sys ) * 9 / 100;
414
415     /* we will read 100ms for each stream so ...*/
416     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
417
418     /* Check if we need to send the audio data to decoder */
419     b_play_audio = !p_input->stream.control.b_mute;
420
421     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
422     {
423 #define track p_sys->track[i_track]
424         if( !track.b_ok ||
425             !track.b_selected ||
426             MP4_GetTrackPTS( &track ) >= MP4_GetMoviePTS( p_sys ) )
427         {
428             continue;
429         }
430
431         while( MP4_GetTrackPTS( &track ) < MP4_GetMoviePTS( p_sys ) )
432         {
433
434             if( !b_play_audio && track.fmt.i_cat == AUDIO_ES )
435             {
436                 if( MP4_TrackNextSample( p_input, &track ) )
437                 {
438                     break;
439                 }
440             }
441             else
442             {
443                 block_t *p_block;
444
445                 /* go,go go ! */
446                 if( stream_Seek( p_input->s, MP4_GetTrackPos( &track ) ) )
447                 {
448                     msg_Warn( p_input, "track[0x%x] will be disabled (eof?)", track.i_track_ID );
449                     MP4_TrackUnselect( p_input, &track );
450                     break;
451                 }
452
453                 /* now read pes */
454                 if( ( p_block = stream_Block( p_input->s,
455                                               MP4_TrackSampleSize( &track ) ) ) == NULL )
456                 {
457                     msg_Warn( p_input, "track[0x%x] will be disabled (eof?)", track.i_track_ID );
458                     MP4_TrackUnselect( p_input, &track );
459                     break;
460                 }
461
462                 if( track.fmt.i_cat == VIDEO_ES )
463                 {
464                     /* FIXME sometime we can calculate PTS */
465                     p_block->i_pts = 0;
466                     p_block->i_dts =
467                         input_ClockGetTS( p_input,
468                                           p_input->stream.p_selected_program,
469                                           MP4_GetTrackPTS( &track ) * 9/100 );
470                 }
471                 else
472                 {
473                     p_block->i_pts =
474                     p_block->i_dts =
475                         input_ClockGetTS( p_input,
476                                           p_input->stream.p_selected_program,
477                                           MP4_GetTrackPTS( &track ) * 9/100 );
478                 }
479
480                 es_out_Send( p_input->p_es_out, track.p_es, p_block );
481
482                 if( MP4_TrackNextSample( p_input, &track ) )
483                 {
484                     break;
485                 }
486             }
487         }
488 #undef track
489     }
490
491     return( 1 );
492 }
493 /*****************************************************************************
494  * Seek: Got to i_date
495  ******************************************************************************/
496 static int   Seek     ( input_thread_t *p_input, mtime_t i_date )
497 {
498     demux_sys_t *p_sys = p_input->p_demux_data;
499     unsigned int i_track;
500     /* First update update global time */
501     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
502     p_sys->i_pcr  = i_date* 9 / 100;
503
504     /* Now for each stream try to go to this time */
505     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
506     {
507 #define track p_sys->track[i_track]
508         if( track.b_ok && track.b_selected )
509         {
510             MP4_TrackSeek( p_input, &track, i_date );
511         }
512 #undef  track
513     }
514     return( 1 );
515 }
516
517 /*****************************************************************************
518  * Control:
519  *****************************************************************************/
520 static int   Control  ( input_thread_t *p_input, int i_query, va_list args )
521 {
522     demux_sys_t *p_sys = p_input->p_demux_data;
523
524     double   f, *pf;
525     int64_t i64, *pi64;
526
527     switch( i_query )
528     {
529         case DEMUX_GET_POSITION:
530             pf = (double*)va_arg( args, double * );
531             if( p_sys->i_duration > 0 )
532             {
533                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
534             }
535             else
536             {
537                 *pf = 0.0;
538             }
539             return VLC_SUCCESS;
540
541         case DEMUX_SET_POSITION:
542             f = (double)va_arg( args, double );
543             i64 = (int64_t)( f *
544                              (double)1000000 *
545                              (double)p_sys->i_duration /
546                              (double)p_sys->i_timescale );
547             return Seek( p_input, i64 );
548
549         case DEMUX_GET_TIME:
550             pi64 = (int64_t*)va_arg( args, int64_t * );
551             *pi64 = (mtime_t)1000000 *
552                     (mtime_t)p_sys->i_time /
553                     (mtime_t)p_sys->i_timescale;
554             return VLC_SUCCESS;
555
556         case DEMUX_SET_TIME:
557             i64 = (int64_t)va_arg( args, int64_t );
558             return Seek( p_input, i64 );
559
560         case DEMUX_GET_LENGTH:
561             pi64 = (int64_t*)va_arg( args, int64_t * );
562             *pi64 = (mtime_t)1000000 *
563                     (mtime_t)p_sys->i_duration /
564                     (mtime_t)p_sys->i_timescale;
565             return VLC_SUCCESS;
566         case DEMUX_GET_FPS:
567             msg_Warn( p_input, "DEMUX_GET_FPS unimplemented !!" );
568             return VLC_EGENERIC;
569         default:
570             msg_Err( p_input, "control query unimplemented !!!" );
571             return demux_vaControlDefault( p_input, i_query, args );
572     }
573 }
574
575 /*****************************************************************************
576  * Close: frees unused data
577  *****************************************************************************/
578 static void Close ( vlc_object_t * p_this )
579 {
580     unsigned int i_track;
581     input_thread_t *  p_input = (input_thread_t *)p_this;
582     demux_sys_t *p_sys = p_input->p_demux_data;
583
584     msg_Dbg( p_input, "freeing all memory" );
585
586     MP4_BoxFree( p_input, p_sys->p_root );
587     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
588     {
589         MP4_TrackDestroy( p_input, &p_sys->track[i_track] );
590     }
591     FREE( p_sys->track );
592
593     free( p_sys );
594 }
595
596
597
598 /****************************************************************************
599  * Local functions, specific to vlc
600  ****************************************************************************/
601
602 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
603 static int TrackCreateChunksIndex( input_thread_t *p_input,
604                                    track_data_mp4_t *p_demux_track )
605 {
606     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
607     MP4_Box_t *p_stsc;
608
609     unsigned int i_chunk;
610     unsigned int i_index, i_last;
611
612     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
613           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
614         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
615     {
616         return( VLC_EGENERIC );
617     }
618
619     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
620     if( !p_demux_track->i_chunk_count )
621     {
622         msg_Warn( p_input, "no chunk defined" );
623         return( VLC_EGENERIC );
624     }
625     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
626                                    sizeof( chunk_data_mp4_t ) );
627
628     /* first we read chunk offset */
629     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
630     {
631         p_demux_track->chunk[i_chunk].i_offset =
632                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
633     }
634
635     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
636         to be used for the sample XXX begin to 1
637         We construct it begining at the end */
638     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
639     i_index = p_stsc->data.p_stsc->i_entry_count;
640     if( !i_index )
641     {
642         msg_Warn( p_input, "cannot read chunk table or table empty" );
643         return( VLC_EGENERIC );
644     }
645
646     while( i_index )
647     {
648         i_index--;
649         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
650                 i_chunk < i_last; i_chunk++ )
651         {
652             p_demux_track->chunk[i_chunk].i_sample_description_index =
653                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
654             p_demux_track->chunk[i_chunk].i_sample_count =
655                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
656         }
657         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
658     }
659
660     p_demux_track->chunk[0].i_sample_first = 0;
661     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
662     {
663         p_demux_track->chunk[i_chunk].i_sample_first =
664             p_demux_track->chunk[i_chunk-1].i_sample_first +
665                 p_demux_track->chunk[i_chunk-1].i_sample_count;
666     }
667
668     msg_Dbg( p_input,
669              "track[Id 0x%x] read %d chunk",
670              p_demux_track->i_track_ID,
671             p_demux_track->i_chunk_count );
672
673     return( VLC_SUCCESS );
674 }
675 static int TrackCreateSamplesIndex( input_thread_t *p_input,
676                                     track_data_mp4_t *p_demux_track )
677 {
678     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
679                           ctts make same mapping but for composition time,
680                           not yet used and probably not usefull */
681     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
682                           that uses a compressed form FIXME make them in libmp4
683                           as a unique type */
684     /* TODO use also stss and stsh table for seeking */
685     /* FIXME use edit table */
686     int64_t i_sample;
687     int64_t i_chunk;
688
689     int64_t i_index;
690     int64_t i_index_sample_used;
691
692     int64_t i_last_dts;
693
694     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
695     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
696
697     if( ( !p_stts )||( !p_stsz ) )
698     {
699         msg_Warn( p_input, "cannot read sample table" );
700         return( VLC_EGENERIC );
701     }
702
703     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
704
705
706     /* for sample size, there are 2 case */
707     if( p_stsz->data.p_stsz->i_sample_size )
708     {
709         /* 1: all sample have the same size, so no need to construct a table */
710         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
711         p_demux_track->p_sample_size = NULL;
712     }
713     else
714     {
715         /* 2: each sample can have a different size */
716         p_demux_track->i_sample_size = 0;
717         p_demux_track->p_sample_size =
718             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
719
720         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
721         {
722             p_demux_track->p_sample_size[i_sample] =
723                     p_stsz->data.p_stsz->i_entry_size[i_sample];
724         }
725     }
726     /* we have extract all information from stsz,
727         now use stts */
728
729     /* if we don't want to waste too much memory, we can't expand
730        the box !, so each chunk will contain an "extract" of this table
731        for fast research */
732
733     i_last_dts = 0;
734     i_index = 0; i_index_sample_used =0;
735
736     /* create and init last data for each chunk */
737     for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
738     {
739
740         int64_t i_entry, i_sample_count, i;
741         /* save last dts */
742         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
743     /* count how many entries needed for this chunk
744        for p_sample_delta_dts and p_sample_count_dts */
745
746         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
747
748         i_entry = 0;
749         while( i_sample_count > 0 )
750         {
751             i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
752             if( i_entry == 0 )
753             {
754                 i_sample_count += i_index_sample_used; /* don't count already used sample
755                                                    int this entry */
756             }
757             i_entry++;
758         }
759
760         /* allocate them */
761         p_demux_track->chunk[i_chunk].p_sample_count_dts =
762             calloc( i_entry, sizeof( uint32_t ) );
763         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
764             calloc( i_entry, sizeof( uint32_t ) );
765
766         /* now copy */
767         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
768         for( i = 0; i < i_entry; i++ )
769         {
770             int64_t i_used;
771             int64_t i_rest;
772
773             i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;
774
775             i_used = __MIN( i_rest, i_sample_count );
776
777             i_index_sample_used += i_used;
778             i_sample_count -= i_used;
779
780             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
781
782             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
783                         p_stts->data.p_stts->i_sample_delta[i_index];
784
785             i_last_dts += i_used *
786                     p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
787
788             if( i_index_sample_used >=
789                              p_stts->data.p_stts->i_sample_count[i_index] )
790             {
791
792                 i_index++;
793                 i_index_sample_used = 0;
794             }
795         }
796
797     }
798
799     msg_Dbg( p_input,
800              "track[Id 0x%x] read %d samples length:"I64Fd"s",
801              p_demux_track->i_track_ID,
802              p_demux_track->i_sample_count,
803              i_last_dts / p_demux_track->i_timescale );
804
805     return( VLC_SUCCESS );
806 }
807
808 /*
809  * TrackCreateES:
810  *  Create ES and PES to init decoder if needed, for a track starting at i_chunk
811  */
812 static int  TrackCreateES   ( input_thread_t   *p_input,
813                               track_data_mp4_t *p_track,
814                               unsigned int     i_chunk,
815                               es_out_id_t      **pp_es )
816 {
817     MP4_Box_t   *p_sample;
818     MP4_Box_t   *p_esds;
819
820     *pp_es = NULL;
821
822     if( !p_track->chunk[i_chunk].i_sample_description_index )
823     {
824         msg_Warn( p_input,
825                   "invalid SampleEntry index (track[Id 0x%x])",
826                   p_track->i_track_ID );
827         return VLC_EGENERIC;
828     }
829
830     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
831                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
832
833     if( !p_sample || !p_sample->data.p_data )
834     {
835         msg_Warn( p_input,
836                   "cannot find SampleEntry (track[Id 0x%x])",
837                   p_track->i_track_ID );
838         return( VLC_EGENERIC );
839     }
840
841     p_track->p_sample = p_sample;
842
843     if( p_track->i_sample_size == 1 )
844     {
845         MP4_Box_data_sample_soun_t *p_soun;
846
847         p_soun = p_sample->data.p_sample_soun;
848
849         if( p_soun->i_qt_version == 0 )
850         {
851             switch( p_sample->i_type )
852             {
853                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
854                     p_soun->i_qt_version = 1;
855                     p_soun->i_sample_per_packet = 64;
856                     p_soun->i_bytes_per_packet  = 34;
857                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
858                     p_soun->i_bytes_per_sample  = 2;
859                     break;
860                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
861                     p_soun->i_qt_version = 1;
862                     p_soun->i_sample_per_packet = 6;
863                     p_soun->i_bytes_per_packet  = 2;
864                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
865                     p_soun->i_bytes_per_sample  = 2;
866                     break;
867                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
868                     p_soun->i_qt_version = 1;
869                     p_soun->i_sample_per_packet = 12;
870                     p_soun->i_bytes_per_packet  = 2;
871                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
872                     p_soun->i_bytes_per_sample  = 2;
873                     break;
874                 default:
875                     break;
876             }
877
878         }
879         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
880         {
881             p_soun->i_qt_version = 0;
882         }
883     }
884
885
886     /* It's a little ugly but .. there are special cases */
887     switch( p_sample->i_type )
888     {
889         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
890         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
891             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
892             break;
893         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
894             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
895             break;
896         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
897             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
898             break;
899         default:
900             p_track->fmt.i_codec = p_sample->i_type;
901             break;
902     }
903
904     /* now see if esds is present and if so create a data packet
905         with decoder_specific_info  */
906 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
907     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
908           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
909         ( p_esds->data.p_esds )&&
910         ( p_decconfig ) )
911     {
912         /* First update information based on i_objectTypeIndication */
913         switch( p_decconfig->i_objectTypeIndication )
914         {
915             case( 0x20 ): /* MPEG4 VIDEO */
916                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
917                 break;
918             case( 0x40):
919                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
920                 break;
921             case( 0x60):
922             case( 0x61):
923             case( 0x62):
924             case( 0x63):
925             case( 0x64):
926             case( 0x65): /* MPEG2 video */
927                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
928                 break;
929             /* Theses are MPEG2-AAC */
930             case( 0x66): /* main profile */
931             case( 0x67): /* Low complexity profile */
932             case( 0x68): /* Scaleable Sampling rate profile */
933                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
934                 break;
935             /* true MPEG 2 audio */
936             case( 0x69):
937                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
938                 break;
939             case( 0x6a): /* MPEG1 video */
940                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
941                 break;
942             case( 0x6b): /* MPEG1 audio */
943                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
944                 break;
945             case( 0x6c ): /* jpeg */
946                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
947                 break;
948             default:
949                 /* Unknown entry, but don't touch i_fourcc */
950                 msg_Warn( p_input,
951                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
952                           p_decconfig->i_objectTypeIndication,
953                           p_track->i_track_ID );
954                 break;
955         }
956         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
957         if( p_track->fmt.i_extra > 0 )
958         {
959             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
960             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
961                     p_track->fmt.i_extra );
962         }
963     }
964     else
965     {
966         switch( p_sample->i_type )
967         {
968             /* qt decoder, send the complete chunk */
969             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
970             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
971             case VLC_FOURCC( 'V', 'P', '3', '1' ):
972             case VLC_FOURCC( '3', 'I', 'V', '1' ):
973             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
974                 p_track->fmt.i_extra =
975                     p_sample->data.p_sample_vide->i_qt_image_description;
976                 if( p_track->fmt.i_extra > 0 )
977                 {
978                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
979                     memcpy( p_track->fmt.p_extra,
980                             p_sample->data.p_sample_vide->p_qt_image_description,
981                             p_track->fmt.i_extra);
982                 }
983                 break;
984             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
985             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
986             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
987             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
988                 p_track->fmt.i_extra =
989                     p_sample->data.p_sample_soun->i_qt_description;
990                 if( p_track->fmt.i_extra > 0 )
991                 {
992                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
993                     memcpy( p_track->fmt.p_extra,
994                             p_sample->data.p_sample_soun->p_qt_description,
995                             p_track->fmt.i_extra);
996                 }
997                 break;
998             default:
999                 break;
1000         }
1001     }
1002
1003 #undef p_decconfig
1004
1005     /* some last initialisation */
1006     switch( p_track->fmt.i_cat )
1007     {
1008     case( VIDEO_ES ):
1009         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1010         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1011
1012         /* fall on display size */
1013         if( p_track->fmt.video.i_width <= 0 )
1014             p_track->fmt.video.i_width = p_track->i_width;
1015         if( p_track->fmt.video.i_height <= 0 )
1016             p_track->fmt.video.i_height = p_track->i_height;
1017
1018         /* Find out apect ratio from display size */
1019         if( p_track->i_width > 0 && p_track->i_height > 0 )
1020             p_track->fmt.video.i_aspect =
1021                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1022
1023         break;
1024
1025     case( AUDIO_ES ):
1026         p_track->fmt.audio.i_channels =
1027             p_sample->data.p_sample_soun->i_channelcount;
1028         p_track->fmt.audio.i_rate =
1029             p_sample->data.p_sample_soun->i_sampleratehi;
1030         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1031             p_sample->data.p_sample_soun->i_sampleratehi *
1032                 p_sample->data.p_sample_soun->i_samplesize;
1033         p_track->fmt.audio.i_bitspersample =
1034             p_sample->data.p_sample_soun->i_samplesize;
1035         break;
1036
1037     default:
1038         break;
1039     }
1040
1041     *pp_es = es_out_Add( p_input->p_es_out, &p_track->fmt );
1042
1043     return VLC_SUCCESS;
1044 }
1045
1046 /* given a time it return sample/chunk */
1047 static int  TrackTimeToSampleChunk( input_thread_t *p_input,
1048                                     track_data_mp4_t *p_track,
1049                                     uint64_t i_start,
1050                                     uint32_t *pi_chunk,
1051                                     uint32_t *pi_sample )
1052 {
1053     MP4_Box_t    *p_stss;
1054     uint64_t     i_dts;
1055     unsigned int i_sample;
1056     unsigned int i_chunk;
1057     int          i_index;
1058
1059     /* convert absolute time to in timescale unit */
1060     i_start = i_start * (mtime_t)p_track->i_timescale / (mtime_t)1000000;
1061
1062     /* FIXME see if it's needed to check p_track->i_chunk_count */
1063     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1064     {
1065         return( VLC_EGENERIC );
1066     }
1067
1068     /* we start from sample 0/chunk 0, hope it won't take too much time */
1069     /* *** find good chunk *** */
1070     for( i_chunk = 0; ; i_chunk++ )
1071     {
1072         if( i_chunk + 1 >= p_track->i_chunk_count )
1073         {
1074             /* at the end and can't check if i_start in this chunk,
1075                it will be check while searching i_sample */
1076             i_chunk = p_track->i_chunk_count - 1;
1077             break;
1078         }
1079
1080         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1081             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1082         {
1083             break;
1084         }
1085     }
1086
1087     /* *** find sample in the chunk *** */
1088     i_sample = p_track->chunk[i_chunk].i_sample_first;
1089     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1090     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1091     {
1092         if( i_dts +
1093             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1094             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1095         {
1096             i_dts    +=
1097                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1098                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1099
1100             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1101             i_index++;
1102         }
1103         else
1104         {
1105             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1106             {
1107                 break;
1108             }
1109             i_sample += ( i_start - i_dts ) / p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1110             break;
1111         }
1112     }
1113
1114     if( i_sample >= p_track->i_sample_count )
1115     {
1116         msg_Warn( p_input,
1117                   "track[Id 0x%x] will be disabled (seeking too far) chunk=%d sample=%d",
1118                   p_track->i_track_ID, i_chunk, i_sample );
1119         return( VLC_EGENERIC );
1120     }
1121
1122
1123     /* *** Try to find nearest sync points *** */
1124     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1125     {
1126         unsigned int i_index;
1127         msg_Dbg( p_input,
1128                     "track[Id 0x%x] using Sync Sample Box (stss)",
1129                     p_track->i_track_ID );
1130         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1131         {
1132             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1133             {
1134                 if( i_index > 0 )
1135                 {
1136                     msg_Dbg( p_input, "stts gives %d --> %d (sample number)",
1137                             i_sample,
1138                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1139                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1140                     /* new i_sample is less than old so i_chunk can only decreased */
1141                     while( i_chunk > 0 &&
1142                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1143                     {
1144                         i_chunk--;
1145                     }
1146                 }
1147                 else
1148                 {
1149                     msg_Dbg( p_input, "stts gives %d --> %d (sample number)",
1150                             i_sample,
1151                             p_stss->data.p_stss->i_sample_number[i_index] );
1152                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1153                     /* new i_sample is more than old so i_chunk can only increased */
1154                     while( i_chunk < p_track->i_chunk_count - 1 &&
1155                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1156                                                 p_track->chunk[i_chunk].i_sample_count )
1157                     {
1158                         i_chunk++;
1159                     }
1160                 }
1161                 break;
1162             }
1163         }
1164     }
1165     else
1166     {
1167         msg_Dbg( p_input,
1168                     "track[Id 0x%x] does not provide Sync Sample Box (stss)",
1169                     p_track->i_track_ID );
1170     }
1171
1172     if( pi_chunk  ) *pi_chunk  = i_chunk;
1173     if( pi_sample ) *pi_sample = i_sample;
1174     return( VLC_SUCCESS );
1175 }
1176
1177 static int  TrackGotoChunkSample( input_thread_t   *p_input,
1178                                   track_data_mp4_t *p_track,
1179                                   unsigned int     i_chunk,
1180                                   unsigned int     i_sample )
1181 {
1182     vlc_bool_t b_reselect = VLC_FALSE;
1183
1184     /* now see if actual es is ok */
1185     if( p_track->i_chunk < 0 ||
1186         p_track->i_chunk >= p_track->i_chunk_count ||
1187         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1188             p_track->chunk[i_chunk].i_sample_description_index )
1189     {
1190         msg_Warn( p_input, "Recreate ES" );
1191
1192         es_out_Control( p_input->p_es_out, ES_OUT_GET_ES_STATE, p_track->p_es, &b_reselect );
1193
1194         es_out_Del( p_input->p_es_out, p_track->p_es );
1195
1196         p_track->p_es = NULL;
1197
1198         if( TrackCreateES( p_input,
1199                            p_track, i_chunk,
1200                            &p_track->p_es ) )
1201         {
1202             msg_Err( p_input, "cannot create es for track[Id 0x%x]",
1203                      p_track->i_track_ID );
1204
1205             p_track->b_ok       = VLC_FALSE;
1206             p_track->b_selected = VLC_FALSE;
1207             return VLC_EGENERIC;
1208         }
1209     }
1210
1211     /* select again the new decoder */
1212     if( b_reselect )
1213     {
1214         es_out_Control( p_input->p_es_out, ES_OUT_SET_ES, p_track->p_es );
1215     }
1216
1217     p_track->i_chunk    = i_chunk;
1218     p_track->i_sample   = i_sample;
1219
1220     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1221 }
1222
1223 /****************************************************************************
1224  * MP4_TrackCreate:
1225  ****************************************************************************
1226  * Parse track information and create all needed data to run a track
1227  * If it succeed b_ok is set to 1 else to 0
1228  ****************************************************************************/
1229 static void MP4_TrackCreate( input_thread_t *p_input,
1230                              track_data_mp4_t *p_track,
1231                              MP4_Box_t  * p_box_trak )
1232 {
1233     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1234     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1235     MP4_Box_t *p_elst;
1236
1237     MP4_Box_t *p_mdhd;
1238     MP4_Box_t *p_hdlr;
1239
1240     MP4_Box_t *p_vmhd;
1241     MP4_Box_t *p_smhd;
1242
1243     unsigned int i;
1244     char language[4];
1245
1246     /* hint track unsuported */
1247
1248     /* set default value (-> track unusable) */
1249     p_track->b_ok       = VLC_FALSE;
1250     p_track->b_enable   = VLC_FALSE;
1251     p_track->b_selected = VLC_FALSE;
1252
1253     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1254
1255     if( !p_tkhd )
1256     {
1257         return;
1258     }
1259
1260     /* do we launch this track by default ? */
1261     p_track->b_enable =
1262         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1263
1264     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1265     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1266     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1267
1268     if( ( p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1269     {
1270 /*        msg_Warn( p_input, "unhandled box: edts --> FIXME" ); */
1271     }
1272
1273     if( p_tref )
1274     {
1275 /*        msg_Warn( p_input, "unhandled box: tref --> FIXME" ); */
1276     }
1277
1278     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1279     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1280
1281     if( ( !p_mdhd )||( !p_hdlr ) )
1282     {
1283         return;
1284     }
1285
1286     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1287
1288     for( i = 0; i < 3; i++ )
1289     {
1290         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1291     }
1292     language[3] = '\0';
1293
1294     switch( p_hdlr->data.p_hdlr->i_handler_type )
1295     {
1296         case( FOURCC_soun ):
1297             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1298             {
1299                 return;
1300             }
1301             p_track->fmt.i_cat = AUDIO_ES;
1302             break;
1303
1304         case( FOURCC_vide ):
1305             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1306             {
1307                 return;
1308             }
1309             p_track->fmt.i_cat = VIDEO_ES;
1310             break;
1311
1312         default:
1313             return;
1314     }
1315 /*  TODO
1316     add support for:
1317     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1318 */
1319     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1320         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1321     {
1322         return;
1323     }
1324
1325     /* Set language */
1326     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1327     {
1328         p_track->fmt.psz_language = strdup( language );
1329     }
1330
1331     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1332     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1333     {
1334         MP4_Box_t *p_sample;
1335
1336         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1337         if( p_sample && p_sample->data.p_sample_soun)
1338         {
1339             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1340             if( p_soun->i_qt_version == 0 &&
1341                 p_track->i_timescale != p_soun->i_sampleratehi )
1342             {
1343                 msg_Warn( p_input,
1344                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1345                           "qt_version == 0\n"
1346                           "Making both equal. (report any problem)",
1347                           p_track->i_timescale, p_soun->i_sampleratehi );
1348
1349                 if( p_soun->i_sampleratehi )
1350                     p_track->i_timescale = p_soun->i_sampleratehi;
1351                 else
1352                     p_soun->i_sampleratehi = p_track->i_timescale;
1353             }
1354         }
1355     }
1356
1357     /* Create chunk index table and sample index table */
1358     if( TrackCreateChunksIndex( p_input,p_track  ) ||
1359         TrackCreateSamplesIndex( p_input, p_track ) )
1360     {
1361         return; /* cannot create chunks index */
1362     }
1363
1364     p_track->i_chunk  = 0;
1365     p_track->i_sample = 0;
1366
1367     /* now create es */
1368     if( TrackCreateES( p_input,
1369                        p_track, p_track->i_chunk,
1370                        &p_track->p_es ) )
1371     {
1372         msg_Err( p_input, "cannot create es for track[Id 0x%x]",
1373                  p_track->i_track_ID );
1374         return;
1375     }
1376
1377 #if 0
1378     {
1379         int i;
1380         for( i = 0; i < p_track->i_chunk_count; i++ )
1381         {
1382             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n", i, p_track->chunk[i].i_sample_count, p_track->chunk[i].i_first_dts );
1383
1384         }
1385     }
1386 #endif
1387     p_track->b_ok = VLC_TRUE;
1388 }
1389
1390 /****************************************************************************
1391  * MP4_TrackDestroy:
1392  ****************************************************************************
1393  * Destroy a track created by MP4_TrackCreate.
1394  ****************************************************************************/
1395 static void MP4_TrackDestroy( input_thread_t *p_input,
1396                               track_data_mp4_t *p_track )
1397 {
1398     unsigned int i_chunk;
1399
1400     p_track->b_ok = VLC_FALSE;
1401     p_track->b_enable   = VLC_FALSE;
1402     p_track->b_selected = VLC_FALSE;
1403
1404     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1405
1406     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1407     {
1408         if( p_track->chunk )
1409         {
1410            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1411            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1412         }
1413     }
1414     FREE( p_track->chunk );
1415
1416     if( !p_track->i_sample_size )
1417     {
1418         FREE( p_track->p_sample_size );
1419     }
1420 }
1421
1422 static int  MP4_TrackSelect ( input_thread_t    *p_input,
1423                               track_data_mp4_t  *p_track,
1424                               mtime_t           i_start )
1425 {
1426     uint32_t i_chunk;
1427     uint32_t i_sample;
1428
1429     if( !p_track->b_ok )
1430     {
1431         return( VLC_EGENERIC );
1432     }
1433
1434     if( p_track->b_selected )
1435     {
1436         msg_Warn( p_input,
1437                   "track[Id 0x%x] already selected",
1438                   p_track->i_track_ID );
1439         return( VLC_SUCCESS );
1440     }
1441
1442     if( TrackTimeToSampleChunk( p_input,
1443                                 p_track, i_start,
1444                                 &i_chunk, &i_sample ) )
1445     {
1446         msg_Warn( p_input,
1447                   "cannot select track[Id 0x%x]",
1448                   p_track->i_track_ID );
1449         return( VLC_EGENERIC );
1450     }
1451
1452     p_track->b_selected = VLC_TRUE;
1453
1454     if( TrackGotoChunkSample( p_input, p_track, i_chunk, i_sample ) )
1455     {
1456         p_track->b_selected = VLC_FALSE;
1457     }
1458     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1459 }
1460
1461 static void MP4_TrackUnselect(input_thread_t    *p_input,
1462                               track_data_mp4_t  *p_track )
1463 {
1464     if( !p_track->b_ok )
1465     {
1466         return;
1467     }
1468
1469     if( !p_track->b_selected )
1470     {
1471         msg_Warn( p_input,
1472                   "track[Id 0x%x] already unselected",
1473                   p_track->i_track_ID );
1474         return;
1475     }
1476     if( p_track->p_es )
1477     {
1478         es_out_Control( p_input->p_es_out, ES_OUT_SET_ES_STATE, p_track->p_es, VLC_FALSE );
1479     }
1480
1481     p_track->b_selected = VLC_FALSE;
1482 }
1483
1484 static int  MP4_TrackSeek   ( input_thread_t    *p_input,
1485                               track_data_mp4_t  *p_track,
1486                               mtime_t           i_start )
1487 {
1488     uint32_t i_chunk;
1489     uint32_t i_sample;
1490
1491     if( !p_track->b_ok )
1492     {
1493         return( VLC_EGENERIC );
1494     }
1495
1496     if( TrackTimeToSampleChunk( p_input,
1497                                 p_track, i_start,
1498                                 &i_chunk, &i_sample ) )
1499     {
1500         msg_Warn( p_input,
1501                   "cannot select track[Id 0x%x]",
1502                   p_track->i_track_ID );
1503         return( VLC_EGENERIC );
1504     }
1505
1506     p_track->b_selected = VLC_TRUE;
1507
1508     TrackGotoChunkSample( p_input, p_track, i_chunk, i_sample );
1509
1510     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
1511 }
1512
1513
1514
1515
1516
1517 /*
1518  * 3 types: for audio
1519  * 
1520  */
1521 #define QT_V0_MAX_SAMPLES    1500
1522 static int  MP4_TrackSampleSize( track_data_mp4_t   *p_track )
1523 {
1524     int i_size;
1525     MP4_Box_data_sample_soun_t *p_soun;
1526
1527     if( p_track->i_sample_size == 0 )
1528     {
1529         /* most simple case */
1530         return( p_track->p_sample_size[p_track->i_sample] );
1531     }
1532     if( p_track->fmt.i_cat != AUDIO_ES )
1533     {
1534         return( p_track->i_sample_size );
1535     }
1536
1537     if( p_track->i_sample_size != 1 )
1538     {
1539         //msg_Warn( p_input, "SampleSize != 1" );
1540         return( p_track->i_sample_size );
1541     }
1542
1543     p_soun = p_track->p_sample->data.p_sample_soun;
1544
1545     if( p_soun->i_qt_version == 1 )
1546     {
1547         i_size = p_track->chunk[p_track->i_chunk].i_sample_count / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
1548     }
1549     else
1550     {
1551         /* FIXME */
1552         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
1553                 ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first );
1554         if( i_samples > QT_V0_MAX_SAMPLES )
1555         {
1556             i_samples = QT_V0_MAX_SAMPLES;
1557         }
1558         i_size = i_samples * p_soun->i_channelcount * p_soun->i_samplesize / 8;
1559     }
1560
1561     //fprintf( stderr, "size=%d\n", i_size );
1562     return( i_size );
1563 }
1564
1565
1566 static uint64_t MP4_GetTrackPos( track_data_mp4_t *p_track )
1567 {
1568     unsigned int i_sample;
1569     uint64_t i_pos;
1570
1571
1572     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
1573
1574     if( p_track->i_sample_size )
1575     {
1576         MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
1577
1578         if( p_soun->i_qt_version == 0 )
1579         {
1580             i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) *
1581                         p_soun->i_channelcount * p_soun->i_samplesize / 8;
1582         }
1583         else
1584         {
1585             /* we read chunk by chunk */
1586             i_pos += 0;
1587         }
1588     }
1589     else
1590     {
1591         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
1592                 i_sample < p_track->i_sample; i_sample++ )
1593         {
1594             i_pos += p_track->p_sample_size[i_sample];
1595         }
1596
1597     }
1598     return( i_pos );
1599 }
1600
1601 static int  MP4_TrackNextSample( input_thread_t     *p_input,
1602                                  track_data_mp4_t   *p_track )
1603 {
1604
1605     if( p_track->fmt.i_cat == AUDIO_ES &&
1606         p_track->i_sample_size != 0 )
1607     {
1608         MP4_Box_data_sample_soun_t *p_soun;
1609
1610         p_soun = p_track->p_sample->data.p_sample_soun;
1611
1612         if( p_soun->i_qt_version == 1 )
1613         {
1614             /* chunk by chunk */
1615             p_track->i_sample =
1616                 p_track->chunk[p_track->i_chunk].i_sample_first +
1617                 p_track->chunk[p_track->i_chunk].i_sample_count;
1618         }
1619         else
1620         {
1621             /* FIXME */
1622             p_track->i_sample += QT_V0_MAX_SAMPLES;
1623             if( p_track->i_sample > p_track->chunk[p_track->i_chunk].i_sample_first + p_track->chunk[p_track->i_chunk].i_sample_count )
1624             {
1625                 p_track->i_sample =
1626                     p_track->chunk[p_track->i_chunk].i_sample_first +
1627                     p_track->chunk[p_track->i_chunk].i_sample_count;
1628             }
1629         }
1630     }
1631     else
1632     {
1633         p_track->i_sample++;
1634     }
1635
1636     if( p_track->i_sample >= p_track->i_sample_count )
1637     {
1638         /* we have reach end of the track so free decoder stuff */
1639         msg_Warn( p_input, "track[0x%x] will be disabled", p_track->i_track_ID );
1640         MP4_TrackUnselect( p_input, p_track );
1641         return( VLC_EGENERIC );
1642     }
1643
1644     /* Have we changed chunk ? */
1645     if( p_track->i_sample >=
1646             p_track->chunk[p_track->i_chunk].i_sample_first +
1647             p_track->chunk[p_track->i_chunk].i_sample_count )
1648     {
1649         if( TrackGotoChunkSample( p_input,
1650                                   p_track,
1651                                   p_track->i_chunk + 1,
1652                                   p_track->i_sample ) )
1653         {
1654             msg_Warn( p_input, "track[0x%x] will be disabled (cannot restart decoder)", p_track->i_track_ID );
1655             MP4_TrackUnselect( p_input, p_track );
1656             return( VLC_EGENERIC );
1657         }
1658     }
1659
1660     return( VLC_SUCCESS );
1661 }
1662
1663