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