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