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