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