]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
cb7bc8e039cfbb77ee4d611059c60118bf4ffef3
[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.8 2002/11/28 16:32:29 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 #include <string.h>                                              /* strdup() */
28 #include <errno.h>
29 #include <sys/types.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/input.h>
33 #include "codecs.h"
34 #include "libmp4.h"
35 #include "mp4.h"
36
37 /*****************************************************************************
38  * Local prototypes
39  *****************************************************************************/
40 static int    MP4Init    ( vlc_object_t * );
41 static void __MP4End     ( vlc_object_t * );
42 static int    MP4Demux   ( input_thread_t * );
43
44 /* New input could have something like that... */
45 static int   MP4Seek     ( input_thread_t *, mtime_t );
46
47 #define MP4End(a) __MP4End(VLC_OBJECT(a))
48
49 /*****************************************************************************
50  * Module descriptor
51  *****************************************************************************/
52 vlc_module_begin();
53     set_description( "MP4 demuxer" );
54     set_capability( "demux", 242 );
55     set_callbacks( MP4Init, __MP4End );
56 vlc_module_end();
57
58 /*****************************************************************************
59  * Declaration of local function 
60  *****************************************************************************/
61
62 static int MP4_TrackSynchro( input_thread_t *p_input, track_data_mp4_t *p_track );
63
64 static void MP4_ParseTrack();
65
66 static int MP4_CreateChunksIndex();
67 static int MP4_CreateSamplesIndex();
68
69 static void MP4_StartDecoder();
70 static void MP4_StopDecoder();
71
72 static int  MP4_ReadSample();
73 static int  MP4_DecodeSample();
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     
86 /*****************************************************************************
87  * MP4Init: check file and initializes MP4 structures
88  *****************************************************************************/
89 static int MP4Init( vlc_object_t * p_this )
90 {   
91     input_thread_t  *p_input = (input_thread_t *)p_this;
92     uint8_t         *p_peek;
93     
94     demux_sys_t     *p_demux;
95     
96     MP4_Box_t       *p_ftyp;
97
98
99     MP4_Box_t       *p_mvhd;
100     MP4_Box_t       *p_trak;
101
102     int             i;
103     /* I need to seek */
104     if( !p_input->stream.b_seekable )
105     {
106         msg_Warn( p_input, "MP4 plugin discarded (unseekable)" );
107         return( -1 );
108             
109     } 
110     /* Initialize access plug-in structures. */
111     if( p_input->i_mtu == 0 )
112     {
113         /* Improve speed. */
114         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE ;
115     }
116
117     p_input->pf_demux = MP4Demux;
118
119     /* a little test to see if it could be a mp4 */
120     if( input_Peek( p_input, &p_peek, 8 ) < 8 )
121     {
122         msg_Warn( p_input, "MP4 plugin discarded (cannot peek)" );
123         return( -1 );
124     }
125
126     
127     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
128     {
129         case( FOURCC_ftyp ):
130         case( FOURCC_moov ):
131         case( FOURCC_moof ):
132         case( FOURCC_mdat ):
133         case( FOURCC_udta ): 
134         case( FOURCC_free ):
135         case( FOURCC_skip ):
136         case( FOURCC_wide ): 
137             break;
138          default:
139             msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
140             return( -1 );
141     }
142
143     /* create our structure that will contains all data */
144     if( !( p_input->p_demux_data = 
145                 p_demux = malloc( sizeof( demux_sys_t ) ) ) )
146     {
147         msg_Err( p_input, "out of memory" );
148         return( -1 );
149     }
150     memset( p_demux, 0, sizeof( demux_sys_t ) );
151     p_input->p_demux_data = p_demux;
152        
153
154     /* Now load all boxes ( except raw data ) */
155     if( !MP4_BoxGetRoot( p_input, &p_demux->box_root ) )
156     {
157         msg_Warn( p_input, "MP4 plugin discarded (not a valid file)" );
158         return( -1 );
159     }
160
161     MP4_BoxDumpStructure( p_input, &p_demux->box_root );
162
163     if( ( p_ftyp = MP4_BoxGet( &p_demux->box_root, "/ftyp" ) ) )
164     {
165         switch( p_ftyp->data.p_ftyp->i_major_brand )
166         {
167             case( FOURCC_isom ):
168                 msg_Info( p_input, 
169                           "ISO Media file (isom) version %d.",
170                           p_ftyp->data.p_ftyp->i_minor_version );
171                 break;
172             default:
173                 msg_Info( p_input,
174                           "Unrecognize major file specification (%c%c%c%c).",
175                            p_ftyp->data.p_ftyp->i_major_brand&0xff,
176                            ( p_ftyp->data.p_ftyp->i_major_brand >>  8)&0xff,
177                            ( p_ftyp->data.p_ftyp->i_major_brand >> 16 )&0xff,
178                            ( p_ftyp->data.p_ftyp->i_major_brand >> 24 )&0xff );
179                 break;
180         }
181     }
182     else
183     {
184         msg_Info( p_input, "File Type box missing(assume ISO Media file)" );
185     }
186
187     /* the file need to have one moov box */
188     if( MP4_BoxCount( &p_demux->box_root, "/moov" ) != 1 )
189     {
190         msg_Err( p_input, 
191                  "MP4 plugin discarded (%d moov box)",
192                  MP4_BoxCount( &p_demux->box_root, "/moov" ) );
193         MP4End( p_input );
194         return( -1 );
195     }
196
197     if( !(p_mvhd = MP4_BoxGet( &p_demux->box_root, "/moov/mvhd" ) ) )
198     {
199         msg_Err( p_input, "cannot find /moov/mvhd !" );
200         MP4End( p_input );
201         return( -1 );
202     }
203     else
204     {
205         p_demux->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
206         p_demux->i_duration = p_mvhd->data.p_mvhd->i_duration;
207     }
208     
209     if( !( p_demux->i_tracks = 
210                 MP4_BoxCount( &p_demux->box_root, "/moov/trak" ) ) )
211     {
212         msg_Err( p_input, "cannot find any /moov/trak !" );
213         MP4End( p_input );
214         return( -1 );
215     }
216     msg_Dbg( p_input, "find %d track%c",
217                         p_demux->i_tracks,
218                         p_demux->i_tracks ? 's':' ' );
219
220     /* allocate memory */
221     p_demux->track = calloc( p_demux->i_tracks, sizeof( track_data_mp4_t ) );
222
223     /* now process each track and extract all usefull informations */
224     for( i = 0; i < p_demux->i_tracks; i++ )
225     {
226         p_trak = MP4_BoxGet( &p_demux->box_root, "/moov/trak[%d]", i );
227         MP4_ParseTrack( p_input, &p_demux->track[i], p_trak );
228
229         if( p_demux->track[i].b_ok )
230         {
231             char *psz_cat;
232             switch( p_demux->track[i].i_cat )
233             {
234                 case( VIDEO_ES ):
235                     psz_cat = "video";
236                     break;
237                 case( AUDIO_ES ):
238                     psz_cat = "audio";
239                     break;
240                 default:
241                     psz_cat = "unknown";
242                     break;
243             }
244             
245             msg_Dbg( p_input, "adding track[Id 0x%x] %s (%s) language %c%c%c",
246                             p_demux->track[i].i_track_ID,
247                             psz_cat,
248                             p_demux->track[i].b_enable ? "enable":"disable",
249                             p_demux->track[i].i_language[0],
250                             p_demux->track[i].i_language[1], 
251                             p_demux->track[i].i_language[2] );
252         }
253         else
254         {
255             msg_Dbg( p_input, "ignoring track[Id 0x%x]", p_demux->track[i].i_track_ID );
256         }
257
258     }
259   
260     /*  create one program */
261     vlc_mutex_lock( &p_input->stream.stream_lock );
262     if( input_InitStream( p_input, 0 ) == -1)
263     {
264         vlc_mutex_unlock( &p_input->stream.stream_lock );
265         msg_Err( p_input, "cannot init stream" );
266         MP4End( p_input );
267         return( -1 );
268     }
269     if( input_AddProgram( p_input, 0, 0) == NULL )
270     {
271         vlc_mutex_unlock( &p_input->stream.stream_lock );
272         msg_Err( p_input, "cannot add program" );
273         MP4End( p_input );
274         return( -1 );
275     }
276     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
277     /* XXX beurk and beurk, see MP4Demux and MP4Seek */
278     if( p_demux->i_duration/p_demux->i_timescale > 0 )
279     {
280         p_input->stream.i_mux_rate =  
281             p_input->stream.p_selected_area->i_size / 50 / 
282             ( p_demux->i_duration / p_demux->i_timescale );
283     }
284     else
285     {
286         p_input->stream.i_mux_rate = 0;
287     }
288     vlc_mutex_unlock( &p_input->stream.stream_lock );
289    
290     
291     for( i = 0; i < p_demux->i_tracks; i++ )
292     {
293         /* start decoder for this track if enable by default*/
294         if( p_demux->track[i].b_enable )
295         {
296             MP4_StartDecoder( p_input, &p_demux->track[i] );
297         }
298     }
299
300     vlc_mutex_lock( &p_input->stream.stream_lock );
301     p_input->stream.p_selected_program->b_is_ok = 1;
302     vlc_mutex_unlock( &p_input->stream.stream_lock );
303         
304     return( 0 );    
305
306 }
307
308 /*****************************************************************************
309  * MP4Demux: read packet and send them to decoders 
310  *****************************************************************************
311  * TODO check for newly selected track (ie audio upt to now )
312  *****************************************************************************/
313 static int MP4Demux( input_thread_t *p_input )
314 {
315     demux_sys_t *p_demux = p_input->p_demux_data;
316     int i_track;
317
318     /* XXX beurk, beuRK and BEURK, 
319        but only way I've found to detect seek from interface */
320     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
321     {
322         mtime_t i_date;
323         
324         /* first wait for empty buffer, arbitrary time FIXME */
325         msleep( DEFAULT_PTS_DELAY );
326         /* *** calculate new date *** */
327
328         i_date = (mtime_t)1000000 * 
329                  (mtime_t)p_demux->i_duration /
330                  (mtime_t)p_demux->i_timescale * 
331                  (mtime_t)MP4_TellAbsolute( p_input ) /
332                  (mtime_t)p_input->stream.p_selected_area->i_size;
333         MP4Seek( p_input, i_date );
334     }
335     
336     /* first wait for the good time to read a packet */
337     input_ClockManageRef( p_input,
338                           p_input->stream.p_selected_program,
339                           p_demux->i_pcr );
340
341
342     /* update pcr XXX in mpeg scale so in 90000 unit/s */
343     p_demux->i_pcr = MP4_GetMoviePTS( p_demux ) * 9 / 100;
344     
345
346     /* we will read 100ms for each stream so ...*/
347     p_demux->i_time += __MAX( p_demux->i_timescale / 10 , 1 );
348     
349
350     for( i_track = 0; i_track < p_demux->i_tracks; i_track++ )
351     {
352         if( ( !p_demux->track[i_track].b_ok )||
353             ( !p_demux->track[i_track].p_es )||
354             ( !p_demux->track[i_track].p_es->p_decoder_fifo )||
355             ( MP4_GetTrackPTS( &p_demux->track[i_track] ) >=
356                         MP4_GetMoviePTS( p_demux ) ) )
357         {
358             continue; /* no need to read something */
359         }
360         while( MP4_GetTrackPTS( &p_demux->track[i_track] ) <
361                         MP4_GetMoviePTS( p_demux ) )
362         {
363
364             pes_packet_t *p_pes;
365
366             /* read a sample */
367             if( !MP4_ReadSample( p_input ,
368                                  &p_demux->track[i_track],
369                                  &p_pes ) )
370             {
371                 break;
372             }
373
374             /* send it to decoder and update time of this track 
375                  it also launch a new decoder if needed */
376             MP4_DecodeSample( p_input ,
377                               &p_demux->track[i_track],
378                               p_pes );
379         }
380
381     }
382     
383     /* now check if all tracks are finished or unhandled*/
384     
385     for( i_track = 0; i_track < p_demux->i_tracks; i_track++ )
386     {
387         if( ( p_demux->track[i_track].b_ok )&&
388             ( p_demux->track[i_track].i_sample < p_demux->track[i_track].i_sample_count )&&
389             ( p_demux->track[i_track].p_es )&&
390             ( p_demux->track[i_track].p_es->p_decoder_fifo ) )
391         {
392             return( 1 );
393         }
394     }
395
396     return( 0 ); /* EOF */
397 }
398 /*****************************************************************************
399  * MP4Seek: Got to i_date
400  ******************************************************************************/
401 static int   MP4Seek     ( input_thread_t *p_input, mtime_t i_date )
402 {
403     demux_sys_t *p_demux = p_input->p_demux_data;
404     int i_track;
405
406     /* First update update global time */
407     p_demux->i_time = i_date * p_demux->i_timescale / 1000000;
408     p_demux->i_pcr = __MAX( MP4_GetMoviePTS( p_demux ) - DEFAULT_PTS_DELAY,
409                             0 ) * 9 / 100; 
410     
411     /* Now for each stream try to go to this time */
412     for( i_track = 0; i_track < p_demux->i_tracks; i_track++ )
413     {
414         MP4_TrackSynchro( p_input, &p_demux->track[i_track] );
415     }
416     return( 1 );
417 }
418
419 /*****************************************************************************
420  * MP4End: frees unused data
421  *****************************************************************************/
422 static void __MP4End ( vlc_object_t * p_this )
423 {   
424 #define FREE( p ) \
425     if( p ) { free( p ); } 
426     int i_track;
427     input_thread_t *  p_input = (input_thread_t *)p_this;
428     demux_sys_t *p_demux = p_input->p_demux_data;
429     
430     msg_Dbg( p_input, "Freeing all memory" );
431     MP4_BoxFree( p_input, &p_demux->box_root );
432     for( i_track = 0; i_track < p_demux->i_tracks; i_track++ )
433     {
434         int i_chunk;
435         for( i_chunk = 0; 
436                 i_chunk < p_demux->track[i_track].i_chunk_count; i_chunk++ )
437         {
438             if( p_demux->track[i_track].chunk )
439             {
440                FREE(p_demux->track[i_track].chunk[i_chunk].p_sample_count_dts);
441                FREE(p_demux->track[i_track].chunk[i_chunk].p_sample_delta_dts );
442             }
443         }
444
445         if( !p_demux->track[i_track].i_sample_size )
446         {
447             FREE( p_demux->track[i_track].p_sample_size );
448         }
449     }
450     FREE( p_demux->track );
451 #undef FREE
452 }
453
454
455 /****************************************************************************
456  * Local functions, specific to vlc
457  ****************************************************************************/
458
459 /****************************************************************************
460  * MP4_TrackSynchro : synchronize a track with movie time after seek or 
461  *                    for newly selected track
462  *****************************************************************************
463  * TODO add support of Edit List (edts/elts) and Shadow Sync Sample(stsh)
464  ****************************************************************************/
465 static int MP4_TrackSynchro( input_thread_t *p_input, track_data_mp4_t *p_track )
466 {
467     demux_sys_t *p_demux = p_input->p_demux_data;
468     int i_chunk_last;
469     MP4_Box_t   *p_stss;
470
471     if( !p_track->b_ok ||
472         !p_track->p_es ||
473         !p_track->p_es->p_decoder_fifo )
474     {
475         return( 0 );
476     }
477     p_track->i_sample = 0;
478     i_chunk_last = p_track->i_chunk;
479     p_track->i_chunk = 0;
480     for( ;; )
481     {
482         if( p_track->i_sample >= p_track->i_sample_count )
483         {
484             msg_Warn( p_input, 
485                         "track[Id 0x%x] will be disabled (seeking too far)",
486                         p_track->i_track_ID );
487             MP4_StopDecoder( p_input, p_track );
488             break;
489         }
490         if( MP4_GetTrackPTS( p_track ) >= MP4_GetMoviePTS( p_demux ) )
491         {
492             break;
493         }
494         /* go one sample after */
495         p_track->i_sample++;
496         if( p_track->i_sample >= p_track->chunk[p_track->i_chunk].i_sample_first +
497                 p_track->chunk[p_track->i_chunk].i_sample_count )
498         {
499             p_track->i_chunk++;
500         }
501         
502     }
503     if( p_track->i_sample >= p_track->i_sample_count )
504     {
505         return( 0 );
506     }
507
508     /* *** Try to find nearest sync points *** */
509     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
510     {
511         int i_index;
512         msg_Dbg( p_input, 
513                     "track[Id 0x%x] using Sync Sample Box (stss)", 
514                     p_track->i_track_ID );
515         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
516         {
517             if( p_stss->data.p_stss->i_sample_number[i_index] >= p_track->i_sample )
518             {
519                 if( i_index > 0 )
520                 {
521                     msg_Dbg( p_input, "stts gives %d --> %d (sample number)", 
522                             p_track->i_sample, 
523                             p_stss->data.p_stss->i_sample_number[i_index-1] );
524                     p_track->i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
525                     /* new track.i_sample is less than old so i_chunk can only decreased */
526                     while( p_track->i_chunk > 0 && 
527                             p_track->i_sample < p_track->chunk[p_track->i_chunk].i_sample_first )
528                     {
529                         p_track->i_chunk--;
530                     }
531                 }
532                 else
533                 {
534                     msg_Dbg( p_input, "stts gives %d --> %d (sample number)", 
535                             p_track->i_sample, 
536                             p_stss->data.p_stss->i_sample_number[i_index-1] );
537                     p_track->i_sample = p_stss->data.p_stss->i_sample_number[i_index];
538                     /* new track.i_sample is more than old so i_chunk can only increased */
539                     while( p_track->i_chunk < p_track->i_chunk_count - 1 &&
540                            p_track->i_sample >= p_track->chunk[p_track->i_chunk].i_sample_first +
541                                                 p_track->chunk[p_track->i_chunk].i_sample_count )
542                     {
543                         p_track->i_chunk++;
544                     }
545                 }
546                 break;
547             }
548         }
549     }
550     else
551     {
552         msg_Dbg( p_input, 
553                     "track[Id 0x%x] doesn't provided Sync Sample Box (stss)", 
554                     p_track->i_track_ID );
555     }
556
557     /* *** If i_sample_description_index has changed restart decoder *** */
558     if( p_track->chunk[i_chunk_last].i_sample_description_index !=
559             p_track->chunk[p_track->i_chunk].i_sample_description_index )
560     {
561         msg_Warn( p_input,
562                 "SampleEntry has changed, restarting decoder" );
563         MP4_StopDecoder( p_input, p_track );
564         MP4_StartDecoder( p_input, p_track );
565     }
566     return( 1 );
567 }
568
569 /****************************************************************************
570  * Parse track information and create all needed data to run a track
571  * If it succeed b_ok is set to 1 else to 0
572  ****************************************************************************/
573 static void MP4_ParseTrack( input_thread_t *p_input,
574                      track_data_mp4_t *p_demux_track,
575                      MP4_Box_t  * p_trak )
576 {
577     int i;
578
579     MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
580     MP4_Box_t *p_tref = MP4_BoxGet( p_trak, "tref" );
581     MP4_Box_t *p_elst;
582
583     MP4_Box_t *p_mdhd;
584     MP4_Box_t *p_hdlr;
585
586     MP4_Box_t *p_vmhd;
587     MP4_Box_t *p_smhd; 
588
589     /* hint track unsuported */
590
591     /* by default, track isn't usable */
592     p_demux_track->b_ok = 0;
593
594     /* by default, we don't known the categorie */
595     p_demux_track->i_cat = UNKNOWN_ES;
596     
597     if( !p_tkhd )
598     {
599         return;
600     }
601
602     /* do we launch this track by default ? */
603     p_demux_track->b_enable = 
604         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
605
606     p_demux_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
607     p_demux_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
608     p_demux_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
609     
610     if( ( p_elst = MP4_BoxGet( p_trak, "edts/elst" ) ) )
611     {
612 /*        msg_Warn( p_input, "Unhandled box: edts --> FIXME" ); */
613     }
614
615     if( p_tref )
616     {
617 /*        msg_Warn( p_input, "Unhandled box: tref --> FIXME" ); */
618     } 
619
620     p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
621     p_hdlr = MP4_BoxGet( p_trak, "mdia/hdlr" );
622     
623     if( ( !p_mdhd )||( !p_hdlr ) )
624     {
625         return;
626     }
627
628     p_demux_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
629
630     for( i = 0; i < 3; i++ ) 
631     {
632         p_demux_track->i_language[i] = p_mdhd->data.p_mdhd->i_language[i];
633     }
634     p_mdhd->data.p_mdhd->i_language[3] = 0;
635     
636     switch( p_hdlr->data.p_hdlr->i_handler_type )
637     {
638         case( FOURCC_soun ):
639             if( !( p_smhd = MP4_BoxGet( p_trak, "mdia/minf/smhd" ) ) )
640             {
641                 return;
642             }
643             p_demux_track->i_cat = AUDIO_ES;
644             break;
645
646         case( FOURCC_vide ):
647             if( !( p_vmhd = MP4_BoxGet( p_trak, "mdia/minf/vmhd" ) ) )
648             {
649                 return;
650             }
651             p_demux_track->i_cat = VIDEO_ES;
652             break;
653             
654         default:
655             return;
656     }
657 /*  TODO
658     add support for:
659     p_dinf = MP4_BoxGet( p_minf, "dinf" );
660 */
661     if( !( p_demux_track->p_stbl = MP4_BoxGet( p_trak,"mdia/minf/stbl" ) ) )
662     {
663         return;
664     }
665     
666     if( !( p_demux_track->p_stsd = MP4_BoxGet( p_trak,"mdia/minf/stbl/stsd") ) )
667     {
668         return;
669     }
670     
671     /* Create chunk  index table */
672     if( !MP4_CreateChunksIndex( p_input,p_demux_track  ) )
673     {
674         return; /* cannot create chunks index */
675     }
676     
677     /* create sample index table needed for reading and seeking */
678     if( !MP4_CreateSamplesIndex( p_input, p_demux_track ) )
679     {
680         return; /* cannot create samples index */
681     }
682      
683     p_demux_track->b_ok = 1;        
684 }
685                      
686
687
688 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
689 static int MP4_CreateChunksIndex( input_thread_t *p_input,
690                                    track_data_mp4_t *p_demux_track )
691 {
692     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
693     MP4_Box_t *p_stsc;
694
695     int i_chunk;
696     int i_index, i_last;
697    
698
699     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
700           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )|| 
701         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
702     {
703         return( 0 );
704     }
705      
706     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
707     if( !p_demux_track->i_chunk_count )
708     {
709         msg_Warn( p_input, "No chunk defined" );
710         return( 0 );
711     }
712     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count, 
713                                    sizeof( chunk_data_mp4_t ) );
714
715     /* first we read chunk offset */
716     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
717     {
718         p_demux_track->chunk[i_chunk].i_offset = 
719                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
720     }
721
722     /* now we read index for SampleEntry( soun vide mp4a mp4v ...) 
723         to be used for the sample XXX begin to 1 
724         We construct it begining at the end */
725     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
726     i_index = p_stsc->data.p_stsc->i_entry_count;
727     if( !i_index )
728     {
729         msg_Warn( p_input, "cannot read chunk table or table empty" );
730         return( 0 );
731     }
732
733     while( i_index )
734     {
735         i_index--;
736         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
737                 i_chunk < i_last; i_chunk++ )
738         {
739             p_demux_track->chunk[i_chunk].i_sample_description_index = 
740                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
741             p_demux_track->chunk[i_chunk].i_sample_count =
742                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
743         }
744         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
745     }
746
747     p_demux_track->chunk[i_chunk].i_sample_first = 0;
748     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
749     {
750         p_demux_track->chunk[i_chunk].i_sample_first =
751             p_demux_track->chunk[i_chunk-1].i_sample_first + 
752                 p_demux_track->chunk[i_chunk-1].i_sample_count;
753         
754     }
755     
756     msg_Dbg( p_input, 
757              "track[Id 0x%x] read %d chunk",
758              p_demux_track->i_track_ID,
759             p_demux_track->i_chunk_count );
760     return( 1 );
761
762 }
763
764
765
766 static int MP4_CreateSamplesIndex( input_thread_t *p_input,
767                                    track_data_mp4_t *p_demux_track )
768 {
769     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
770                           ctts make same mapping but for composition time, 
771                           not yet used and probably not usefull */
772     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2 
773                           that uses a compressed form FIXME make them in libmp4 
774                           as a unique type */
775     /* TODO use also stss and stsh table for seeking */
776     /* FIXME use edit table */
777     int64_t i_sample;
778     int64_t i_chunk;
779
780     int64_t i_index;
781     int64_t i_index_sample_used;
782
783     int64_t i_last_dts; 
784     
785     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
786     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
787
788     
789     if( ( !p_stts )||( !p_stsz ) )
790     {
791         msg_Warn( p_input, "cannot read sample table" );
792         return( 0 ); 
793     }
794         
795     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
796
797
798     /* for sample size, there are 2 case */
799     if( p_stsz->data.p_stsz->i_sample_size )
800     {
801         /* 1: all sample have the same size, so no need to construct a table */
802         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
803         p_demux_track->p_sample_size = NULL;
804     }
805     else
806     {
807         /* 2: each sample can have a different size */
808         p_demux_track->i_sample_size = 0;
809         p_demux_track->p_sample_size = 
810             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
811         
812         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
813         {
814             p_demux_track->p_sample_size[i_sample] = 
815                     p_stsz->data.p_stsz->i_entry_size[i_sample];
816         }
817     }
818     /* we have extract all information from stsz,
819         now use stts */
820
821     /* if we don't want to waste too much memory, we can't expand
822        the box !, so each chunk will contain an "extract" of this table 
823        for fast research */
824         
825     i_last_dts = 0;
826     i_index = 0; i_index_sample_used =0;
827
828     /* create and init last data for each chunk */
829     for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
830     {
831
832         int64_t i_entry, i_sample_count, i;
833         /* save last dts */
834         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
835     /* count how many entries needed for this chunk 
836        for p_sample_delta_dts and p_sample_count_dts */
837
838         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
839
840         i_entry = 0;
841         while( i_sample_count > 0 )
842         {
843             i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
844             if( i_entry == 0 )
845             {
846                 i_sample_count += i_index_sample_used; /* don't count already used sample 
847                                                    int this entry */
848             }
849             i_entry++;
850         }
851
852         /* allocate them */
853         p_demux_track->chunk[i_chunk].p_sample_count_dts = 
854             calloc( i_entry, sizeof( uint32_t ) );
855         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
856             calloc( i_entry, sizeof( uint32_t ) );
857
858         /* now copy */
859         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
860         for( i = 0; i < i_entry; i++ )
861         {
862             int64_t i_used;
863             int64_t i_rest;
864             
865             i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;
866
867             i_used = __MIN( i_rest, i_sample_count );
868
869             i_index_sample_used += i_used;
870             i_sample_count -= i_used;
871
872             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
873
874             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
875                         p_stts->data.p_stts->i_sample_delta[i_index];
876             
877             i_last_dts += i_used * 
878                     p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
879
880             if( i_index_sample_used >=
881                              p_stts->data.p_stts->i_sample_count[i_index] )
882             {
883
884                 i_index++;
885                 i_index_sample_used = 0;
886             }
887         }
888         
889     }
890
891     msg_Dbg( p_input, 
892              "track[Id 0x%x] read %d samples length:"I64Fd"s", 
893              p_demux_track->i_track_ID,
894              p_demux_track->i_sample_count,
895              i_last_dts / p_demux_track->i_timescale );
896
897     return( 1 );
898 }
899
900 static void MP4_StartDecoder( input_thread_t *p_input,
901                                  track_data_mp4_t *p_demux_track )
902 {
903     MP4_Box_t   *p_sample;
904     int         i;
905     int         i_chunk;
906
907     int         i_decoder_specific_info_len;
908     uint8_t     *p_decoder_specific_info;
909     
910     uint8_t             *p_init;
911     BITMAPINFOHEADER    *p_bih;
912     WAVEFORMATEX        *p_wf;
913
914     MP4_Box_t   *p_esds;
915
916     
917     if( (!p_demux_track->b_ok )||( p_demux_track->i_cat == UNKNOWN_ES ) )
918     {
919         return;
920     }
921     
922     msg_Dbg( p_input, "Starting decoder for track[Id 0x%x]",
923                       p_demux_track->i_track_ID );
924
925     /* launch decoder according in chunk we are */
926     i_chunk = p_demux_track->i_chunk;
927
928     if( !p_demux_track->chunk[i_chunk].i_sample_description_index )
929     {
930         msg_Warn( p_input, 
931                   "invalid SampleEntry index (track[Id 0x%x])",
932                   p_demux_track->i_track_ID );
933         return;
934     } 
935     p_sample = MP4_BoxGet(  p_demux_track->p_stsd, 
936                             "[%d]", 
937                 p_demux_track->chunk[i_chunk].i_sample_description_index - 1 );
938
939     if( ( !p_sample )||( !p_sample->data.p_data ) )
940     {
941         msg_Warn( p_input, 
942                   "cannot find SampleEntry (track[Id 0x%x])",
943                   p_demux_track->i_track_ID );
944         return;
945     }
946
947     vlc_mutex_lock( &p_input->stream.stream_lock );
948     p_demux_track->p_es = input_AddES( p_input,
949                                        p_input->stream.p_selected_program, 
950                                        p_demux_track->i_track_ID,
951                                        0 );
952     vlc_mutex_unlock( &p_input->stream.stream_lock );
953     /* Initialise ES, first language as description */
954     for( i = 0; i < 3; i++ )
955     {
956         p_demux_track->p_es->psz_desc[i] = p_demux_track->i_language[i];
957     }
958     p_demux_track->p_es->psz_desc[3] = '\0';
959     
960     p_demux_track->p_es->i_stream_id = p_demux_track->i_track_ID;
961
962     /* It's a little ugly but .. there are special cases */
963     switch( p_sample->i_type )
964     {
965         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
966         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
967             p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm', 'p', 'g', 'a' );
968             break;
969         default:
970             p_demux_track->p_es->i_fourcc = p_sample->i_type;
971             break;
972     }
973     
974     p_demux_track->p_es->i_cat = p_demux_track->i_cat;
975     
976     i_decoder_specific_info_len = 0;
977     p_decoder_specific_info = NULL;
978
979     /* now see if esds is present and if so create a data packet 
980         with decoder_specific_info  */
981 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
982     if( ( p_esds = MP4_BoxGet( p_sample, "esds" ) )&&
983         ( p_esds->data.p_esds )&&
984         ( p_decconfig ) )
985     {
986         /* First update information based on i_objectTypeIndication */
987         switch( p_decconfig->i_objectTypeIndication )
988         {
989             case( 0x20 ): /* MPEG4 VIDEO */
990                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','4','v' );
991                 break;
992             case( 0x40):
993                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','4','a' );
994                 break;
995             case( 0x60):
996             case( 0x61):
997             case( 0x62):
998             case( 0x63):
999             case( 0x64):
1000             case( 0x65): /* MPEG2 video */
1001                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','g','v' );
1002                 break;
1003             /* Theses are MPEG2-AAC */
1004             case( 0x66): /* main profile */
1005             case( 0x67): /* Low complexity profile */
1006             case( 0x68): /* Scaleable Sampling rate profile */
1007                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','4','a' );
1008                 break;
1009             /* true MPEG 2 audio */
1010             case( 0x69): 
1011                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','g','a' );
1012                 break;
1013             case( 0x6a): /* MPEG1 video */
1014                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','g','v' );
1015                 break;
1016             case( 0x6b): /* MPEG1 audio */
1017                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'm','p','g','a' );
1018                 break;
1019             case( 0x6c ): /* jpeg */
1020                 p_demux_track->p_es->i_fourcc = VLC_FOURCC( 'j','p','e','g' );
1021                 break;
1022             default:
1023                 /* Unknown entry, but don't touch i_fourcc */
1024                 msg_Warn( p_input, 
1025                           "objectTypeIndication(0x%x) unknow (Track[ID 0x%x])",
1026                           p_decconfig->i_objectTypeIndication,
1027                           p_demux_track->i_track_ID );
1028                 break;
1029         }
1030         i_decoder_specific_info_len = 
1031                 p_decconfig->i_decoder_specific_info_len;
1032         p_decoder_specific_info = 
1033                 p_decconfig->p_decoder_specific_info;
1034     }
1035
1036 #undef p_decconfig
1037
1038     /* some last initialisation */
1039     /* XXX I create a bitmapinfoheader_t or 
1040        waveformatex_t for each stream, up to now it's the best thing 
1041        I've found but it could exist a better solution :) as something 
1042        like adding some new fields in p_es ...
1043
1044        XXX I don't set all values, only thoses that are interesting or known
1045         --> bitmapinfoheader_t : width and height 
1046         --> waveformatex_t : channels, samplerate, bitspersample
1047         and at the end I add p_decoder_specific_info 
1048         
1049         TODO set more values
1050      
1051      */
1052
1053     switch( p_demux_track->i_cat )
1054     {
1055         case( VIDEO_ES ):    
1056             /* now create a bitmapinfoheader_t for decoder and 
1057                add information found in p_esds */
1058             p_init = malloc( sizeof( BITMAPINFOHEADER ) + i_decoder_specific_info_len );
1059             p_bih = (BITMAPINFOHEADER*)p_init;
1060
1061             p_bih->biSize     = sizeof( BITMAPINFOHEADER ) + i_decoder_specific_info_len;
1062             p_bih->biWidth    = p_sample->data.p_sample_vide->i_width;
1063             p_bih->biHeight   = p_sample->data.p_sample_vide->i_height;
1064             p_bih->biPlanes   = 1;      // FIXME
1065             p_bih->biBitCount = 0;      // FIXME
1066             p_bih->biCompression   = 0; // FIXME
1067             p_bih->biSizeImage     = 0; // FIXME
1068             p_bih->biXPelsPerMeter = 0; // FIXME
1069             p_bih->biYPelsPerMeter = 0; // FIXME
1070             p_bih->biClrUsed       = 0; // FIXME
1071             p_bih->biClrImportant  = 0; // FIXME
1072
1073             if( p_bih->biWidth == 0 )
1074             {
1075                 // fall on display size
1076                 p_bih->biWidth = p_demux_track->i_width;
1077             }
1078             if( p_bih->biHeight == 0 )
1079             {
1080                 // fall on display size
1081                 p_bih->biHeight = p_demux_track->i_height;
1082             }
1083             
1084             if( i_decoder_specific_info_len )
1085             {
1086                 memcpy( p_init + sizeof( BITMAPINFOHEADER ), 
1087                         p_decoder_specific_info,
1088                         i_decoder_specific_info_len);
1089             }
1090             break;
1091
1092         case( AUDIO_ES ):
1093             p_init = malloc( sizeof( WAVEFORMATEX ) + i_decoder_specific_info_len);
1094             p_wf = (WAVEFORMATEX*)p_init;
1095
1096             p_wf->wFormatTag = 0;
1097             p_wf->nChannels = p_sample->data.p_sample_soun->i_channelcount;
1098             p_wf->nSamplesPerSec = p_sample->data.p_sample_soun->i_sampleratehi;
1099             p_wf->nAvgBytesPerSec = p_sample->data.p_sample_soun->i_channelcount *
1100                                     p_sample->data.p_sample_soun->i_sampleratehi *
1101                                     p_sample->data.p_sample_soun->i_samplesize / 8;
1102             p_wf->nBlockAlign = 0;
1103             p_wf->wBitsPerSample = p_sample->data.p_sample_soun->i_samplesize;
1104             p_wf->cbSize = i_decoder_specific_info_len;
1105
1106             if( i_decoder_specific_info_len )
1107             {
1108                 memcpy( p_init + sizeof( WAVEFORMATEX ), 
1109                         p_decoder_specific_info,
1110                         i_decoder_specific_info_len);
1111             }
1112             break;
1113
1114         default:
1115             p_init = NULL;
1116             break;
1117     }
1118
1119     p_demux_track->p_es->p_demux_data = (es_sys_t *)p_init;
1120     vlc_mutex_lock( &p_input->stream.stream_lock );
1121     input_SelectES( p_input, p_demux_track->p_es );
1122     vlc_mutex_unlock( &p_input->stream.stream_lock );
1123
1124     p_demux_track->b_ok = 1;
1125     p_demux_track->b_selected = 1;
1126 }
1127
1128 static void MP4_StopDecoder( input_thread_t *p_input,
1129                              track_data_mp4_t *p_demux_track )
1130 {
1131     msg_Dbg( p_input, "Stopping decoder (track[Id 0x%x])",
1132                       p_demux_track->i_track_ID );
1133
1134     input_UnselectES( p_input, p_demux_track->p_es );
1135     p_demux_track->p_es = NULL;
1136
1137     p_demux_track->b_selected = 0;
1138 }
1139
1140 static int  MP4_ReadSample( input_thread_t *p_input,
1141                             track_data_mp4_t *p_demux_track,
1142                             pes_packet_t **pp_pes )
1143 {
1144     int i_size;
1145     off_t i_pos;
1146
1147     data_packet_t *p_data;
1148
1149
1150     /* this track have already reach the end */
1151     if( p_demux_track->i_sample >= p_demux_track->i_sample_count )
1152     {
1153         *pp_pes = NULL;
1154         return( 0 );
1155     }
1156     /* caculate size and position for this sample */
1157     i_size = p_demux_track->i_sample_size ? 
1158                     p_demux_track->i_sample_size : 
1159                     p_demux_track->p_sample_size[p_demux_track->i_sample];
1160
1161     i_pos  = MP4_GetTrackPos( p_demux_track );
1162
1163     /* go,go go ! */
1164     if( ! MP4_SeekAbsolute( p_input, i_pos ) )
1165     {
1166         return( 0 );
1167     }
1168
1169     /* now create a pes */
1170     if( !(*pp_pes = input_NewPES( p_input->p_method_data ) ) )
1171     {
1172         return( 0 );
1173     }
1174     /* and a data packet for the data */
1175     if( !(p_data = input_NewPacket( p_input->p_method_data, i_size ) ) )
1176     {
1177         input_DeletePES( p_input->p_method_data, *pp_pes );
1178         *pp_pes = NULL;
1179         return( 0 );
1180     }
1181     
1182     /* initialisation of all the field */
1183     (*pp_pes)->i_dts =
1184         (*pp_pes)->i_pts = MP4_GetTrackPTS( p_demux_track );
1185     (*pp_pes)->p_first = (*pp_pes)->p_last  = p_data;
1186     (*pp_pes)->i_nb_data = 1;
1187     (*pp_pes)->i_pes_size = i_size;
1188
1189     if( !i_size )    
1190     {
1191         return( 1 );
1192     }
1193     
1194 /*    msg_Dbg( p_input, "will read %d bytes", i_size ); */
1195     if( !MP4_ReadData( p_input, p_data->p_payload_start, i_size ) )
1196     {
1197         input_DeletePES( p_input->p_method_data, *pp_pes );
1198         input_DeletePacket( p_input->p_method_data, p_data );
1199         return( 0 );
1200     }
1201
1202         return( 1 );
1203 }
1204
1205
1206 static int  MP4_DecodeSample( input_thread_t *p_input,
1207                               track_data_mp4_t *p_demux_track,
1208                               pes_packet_t *p_pes )
1209 {
1210
1211     if( !p_pes )
1212     {
1213         return( 0 );
1214     }
1215
1216     /* don't forget to convert in mpeg clock */
1217     /* FIXME correct ffmpeg to use dts instead of pts that it incorrect 
1218        and, set it here ( and correct avi demux ) */
1219     p_pes->i_dts =
1220         p_pes->i_pts = input_ClockGetTS( p_input,
1221                                          p_input->stream.p_selected_program,
1222                                          p_pes->i_pts * 9/100);
1223
1224     
1225     input_DecodePES( p_demux_track->p_es->p_decoder_fifo, p_pes );
1226     
1227     /* now update sample position */
1228     p_demux_track->i_sample++; /* easy ;) */
1229     if( p_demux_track->i_sample >= p_demux_track->i_sample_count )
1230     {
1231         /* we have reach end of the track so free decoder stuff */
1232         MP4_StopDecoder( p_input, p_demux_track );
1233         return( 1 );
1234     }
1235     /* Have we changed chunk ? */
1236     if( p_demux_track->i_sample >=
1237             p_demux_track->chunk[p_demux_track->i_chunk].i_sample_first +
1238                 p_demux_track->chunk[p_demux_track->i_chunk].i_sample_count )
1239     {
1240         /* we haven't reached the end of the track, so see if we 
1241            have to change the decoder for the next frame because 
1242            i_sample_description_index has changed */
1243
1244         p_demux_track->i_chunk++;
1245         if( p_demux_track->chunk[p_demux_track->i_chunk-1].i_sample_description_index 
1246               != p_demux_track->chunk[p_demux_track->i_chunk].i_sample_description_index  )
1247         {
1248             /* FIXME */
1249             msg_Warn( p_input, 
1250                       "SampleEntry has changed, starting a new decoder" );
1251             MP4_StopDecoder( p_input, p_demux_track );
1252             MP4_StartDecoder( p_input, p_demux_track );
1253         }
1254     }
1255
1256     
1257     return( 1 );
1258 }
1259
1260
1261