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