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