]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
* all: added support for edts/elst entries (needed to play some files).
[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.55 2004/01/18 22:00:00 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 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             i64 = (int64_t)( f *
602                              (double)1000000 *
603                              (double)p_sys->i_duration /
604                              (double)p_sys->i_timescale );
605             return Seek( p_input, i64 );
606
607         case DEMUX_GET_TIME:
608             pi64 = (int64_t*)va_arg( args, int64_t * );
609             *pi64 = (mtime_t)1000000 *
610                     (mtime_t)p_sys->i_time /
611                     (mtime_t)p_sys->i_timescale;
612             return VLC_SUCCESS;
613
614         case DEMUX_SET_TIME:
615             i64 = (int64_t)va_arg( args, int64_t );
616             return Seek( p_input, i64 );
617
618         case DEMUX_GET_LENGTH:
619             pi64 = (int64_t*)va_arg( args, int64_t * );
620             *pi64 = (mtime_t)1000000 *
621                     (mtime_t)p_sys->i_duration /
622                     (mtime_t)p_sys->i_timescale;
623             return VLC_SUCCESS;
624         case DEMUX_GET_FPS:
625             msg_Warn( p_input, "DEMUX_GET_FPS unimplemented !!" );
626             return VLC_EGENERIC;
627         default:
628             msg_Err( p_input, "control query unimplemented !!!" );
629             return demux_vaControlDefault( p_input, i_query, args );
630     }
631 }
632
633 /*****************************************************************************
634  * Close: frees unused data
635  *****************************************************************************/
636 static void Close ( vlc_object_t * p_this )
637 {
638     unsigned int i_track;
639     input_thread_t *  p_input = (input_thread_t *)p_this;
640     demux_sys_t *p_sys = p_input->p_demux_data;
641
642     msg_Dbg( p_input, "freeing all memory" );
643
644     MP4_BoxFree( p_input, p_sys->p_root );
645     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
646     {
647         MP4_TrackDestroy( p_input, &p_sys->track[i_track] );
648     }
649     FREE( p_sys->track );
650
651     free( p_sys );
652 }
653
654
655
656 /****************************************************************************
657  * Local functions, specific to vlc
658  ****************************************************************************/
659
660 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
661 static int TrackCreateChunksIndex( input_thread_t *p_input,
662                                    mp4_track_t *p_demux_track )
663 {
664     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
665     MP4_Box_t *p_stsc;
666
667     unsigned int i_chunk;
668     unsigned int i_index, i_last;
669
670     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
671           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
672         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
673     {
674         return( VLC_EGENERIC );
675     }
676
677     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
678     if( !p_demux_track->i_chunk_count )
679     {
680         msg_Warn( p_input, "no chunk defined" );
681         return( VLC_EGENERIC );
682     }
683     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
684                                    sizeof( mp4_chunk_t ) );
685
686     /* first we read chunk offset */
687     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
688     {
689         p_demux_track->chunk[i_chunk].i_offset =
690                 p_co64->data.p_co64->i_chunk_offset[i_chunk];
691     }
692
693     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
694         to be used for the sample XXX begin to 1
695         We construct it begining at the end */
696     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
697     i_index = p_stsc->data.p_stsc->i_entry_count;
698     if( !i_index )
699     {
700         msg_Warn( p_input, "cannot read chunk table or table empty" );
701         return( VLC_EGENERIC );
702     }
703
704     while( i_index )
705     {
706         i_index--;
707         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
708                 i_chunk < i_last; i_chunk++ )
709         {
710             p_demux_track->chunk[i_chunk].i_sample_description_index =
711                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
712             p_demux_track->chunk[i_chunk].i_sample_count =
713                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
714         }
715         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
716     }
717
718     p_demux_track->chunk[0].i_sample_first = 0;
719     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
720     {
721         p_demux_track->chunk[i_chunk].i_sample_first =
722             p_demux_track->chunk[i_chunk-1].i_sample_first +
723                 p_demux_track->chunk[i_chunk-1].i_sample_count;
724     }
725
726     msg_Dbg( p_input,
727              "track[Id 0x%x] read %d chunk",
728              p_demux_track->i_track_ID,
729              p_demux_track->i_chunk_count );
730
731     return( VLC_SUCCESS );
732 }
733 static int TrackCreateSamplesIndex( input_thread_t *p_input,
734                                     mp4_track_t *p_demux_track )
735 {
736     MP4_Box_t *p_stts; /* makes mapping between sample and decoding time,
737                           ctts make same mapping but for composition time,
738                           not yet used and probably not usefull */
739     MP4_Box_t *p_stsz; /* gives sample size of each samples, there is also stz2
740                           that uses a compressed form FIXME make them in libmp4
741                           as a unique type */
742     /* TODO use also stss and stsh table for seeking */
743     /* FIXME use edit table */
744     int64_t i_sample;
745     int64_t i_chunk;
746
747     int64_t i_index;
748     int64_t i_index_sample_used;
749
750     int64_t i_last_dts;
751
752     p_stts = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
753     p_stsz = MP4_BoxGet( p_demux_track->p_stbl, "stsz" ); /* FIXME and stz2 */
754
755     if( ( !p_stts )||( !p_stsz ) )
756     {
757         msg_Warn( p_input, "cannot read sample table" );
758         return( VLC_EGENERIC );
759     }
760
761     p_demux_track->i_sample_count = p_stsz->data.p_stsz->i_sample_count;
762
763
764     /* for sample size, there are 2 case */
765     if( p_stsz->data.p_stsz->i_sample_size )
766     {
767         /* 1: all sample have the same size, so no need to construct a table */
768         p_demux_track->i_sample_size = p_stsz->data.p_stsz->i_sample_size;
769         p_demux_track->p_sample_size = NULL;
770     }
771     else
772     {
773         /* 2: each sample can have a different size */
774         p_demux_track->i_sample_size = 0;
775         p_demux_track->p_sample_size =
776             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
777
778         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
779         {
780             p_demux_track->p_sample_size[i_sample] =
781                     p_stsz->data.p_stsz->i_entry_size[i_sample];
782         }
783     }
784     /* we have extract all information from stsz,
785         now use stts */
786
787     /* if we don't want to waste too much memory, we can't expand
788        the box !, so each chunk will contain an "extract" of this table
789        for fast research */
790
791     i_last_dts = 0;
792     i_index = 0; i_index_sample_used =0;
793
794     /* create and init last data for each chunk */
795     for(i_chunk = 0 ; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
796     {
797
798         int64_t i_entry, i_sample_count, i;
799         /* save last dts */
800         p_demux_track->chunk[i_chunk].i_first_dts = i_last_dts;
801     /* count how many entries needed for this chunk
802        for p_sample_delta_dts and p_sample_count_dts */
803
804         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
805
806         i_entry = 0;
807         while( i_sample_count > 0 )
808         {
809             i_sample_count -= p_stts->data.p_stts->i_sample_count[i_index+i_entry];
810             if( i_entry == 0 )
811             {
812                 i_sample_count += i_index_sample_used; /* don't count already used sample
813                                                    int this entry */
814             }
815             i_entry++;
816         }
817
818         /* allocate them */
819         p_demux_track->chunk[i_chunk].p_sample_count_dts =
820             calloc( i_entry, sizeof( uint32_t ) );
821         p_demux_track->chunk[i_chunk].p_sample_delta_dts =
822             calloc( i_entry, sizeof( uint32_t ) );
823
824         /* now copy */
825         i_sample_count = p_demux_track->chunk[i_chunk].i_sample_count;
826         for( i = 0; i < i_entry; i++ )
827         {
828             int64_t i_used;
829             int64_t i_rest;
830
831             i_rest = p_stts->data.p_stts->i_sample_count[i_index] - i_index_sample_used;
832
833             i_used = __MIN( i_rest, i_sample_count );
834
835             i_index_sample_used += i_used;
836             i_sample_count -= i_used;
837
838             p_demux_track->chunk[i_chunk].p_sample_count_dts[i] = i_used;
839
840             p_demux_track->chunk[i_chunk].p_sample_delta_dts[i] =
841                         p_stts->data.p_stts->i_sample_delta[i_index];
842
843             i_last_dts += i_used *
844                     p_demux_track->chunk[i_chunk].p_sample_delta_dts[i];
845
846             if( i_index_sample_used >=
847                              p_stts->data.p_stts->i_sample_count[i_index] )
848             {
849
850                 i_index++;
851                 i_index_sample_used = 0;
852             }
853         }
854
855     }
856
857     msg_Dbg( p_input,
858              "track[Id 0x%x] read %d samples length:"I64Fd"s",
859              p_demux_track->i_track_ID,
860              p_demux_track->i_sample_count,
861              i_last_dts / p_demux_track->i_timescale );
862
863     return( VLC_SUCCESS );
864 }
865
866 /*
867  * TrackCreateES:
868  *  Create ES and PES to init decoder if needed, for a track starting at i_chunk
869  */
870 static int  TrackCreateES   ( input_thread_t   *p_input,
871                               mp4_track_t *p_track,
872                               unsigned int     i_chunk,
873                               es_out_id_t      **pp_es )
874 {
875     MP4_Box_t   *p_sample;
876     MP4_Box_t   *p_esds;
877
878     *pp_es = NULL;
879
880     if( !p_track->chunk[i_chunk].i_sample_description_index )
881     {
882         msg_Warn( p_input,
883                   "invalid SampleEntry index (track[Id 0x%x])",
884                   p_track->i_track_ID );
885         return VLC_EGENERIC;
886     }
887
888     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
889                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
890
891     if( !p_sample || !p_sample->data.p_data )
892     {
893         msg_Warn( p_input,
894                   "cannot find SampleEntry (track[Id 0x%x])",
895                   p_track->i_track_ID );
896         return( VLC_EGENERIC );
897     }
898
899     p_track->p_sample = p_sample;
900
901     if( p_track->i_sample_size == 1 )
902     {
903         MP4_Box_data_sample_soun_t *p_soun;
904
905         p_soun = p_sample->data.p_sample_soun;
906
907         if( p_soun->i_qt_version == 0 )
908         {
909             switch( p_sample->i_type )
910             {
911                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
912                     p_soun->i_qt_version = 1;
913                     p_soun->i_sample_per_packet = 64;
914                     p_soun->i_bytes_per_packet  = 34;
915                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
916                     p_soun->i_bytes_per_sample  = 2;
917                     break;
918                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
919                     p_soun->i_qt_version = 1;
920                     p_soun->i_sample_per_packet = 6;
921                     p_soun->i_bytes_per_packet  = 2;
922                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
923                     p_soun->i_bytes_per_sample  = 2;
924                     break;
925                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
926                     p_soun->i_qt_version = 1;
927                     p_soun->i_sample_per_packet = 12;
928                     p_soun->i_bytes_per_packet  = 2;
929                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
930                     p_soun->i_bytes_per_sample  = 2;
931                     break;
932                 default:
933                     break;
934             }
935
936         }
937         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
938         {
939             p_soun->i_qt_version = 0;
940         }
941     }
942
943
944     /* It's a little ugly but .. there are special cases */
945     switch( p_sample->i_type )
946     {
947         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
948         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
949             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
950             break;
951         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
952             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
953             break;
954         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
955             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
956             break;
957         default:
958             p_track->fmt.i_codec = p_sample->i_type;
959             break;
960     }
961
962     /* now see if esds is present and if so create a data packet
963         with decoder_specific_info  */
964 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
965     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
966           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
967         ( p_esds->data.p_esds )&&
968         ( p_decconfig ) )
969     {
970         /* First update information based on i_objectTypeIndication */
971         switch( p_decconfig->i_objectTypeIndication )
972         {
973             case( 0x20 ): /* MPEG4 VIDEO */
974                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
975                 break;
976             case( 0x40):
977                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
978                 break;
979             case( 0x60):
980             case( 0x61):
981             case( 0x62):
982             case( 0x63):
983             case( 0x64):
984             case( 0x65): /* MPEG2 video */
985                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
986                 break;
987             /* Theses are MPEG2-AAC */
988             case( 0x66): /* main profile */
989             case( 0x67): /* Low complexity profile */
990             case( 0x68): /* Scaleable Sampling rate profile */
991                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
992                 break;
993             /* true MPEG 2 audio */
994             case( 0x69):
995                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
996                 break;
997             case( 0x6a): /* MPEG1 video */
998                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
999                 break;
1000             case( 0x6b): /* MPEG1 audio */
1001                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1002                 break;
1003             case( 0x6c ): /* jpeg */
1004                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1005                 break;
1006             default:
1007                 /* Unknown entry, but don't touch i_fourcc */
1008                 msg_Warn( p_input,
1009                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1010                           p_decconfig->i_objectTypeIndication,
1011                           p_track->i_track_ID );
1012                 break;
1013         }
1014         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1015         if( p_track->fmt.i_extra > 0 )
1016         {
1017             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1018             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1019                     p_track->fmt.i_extra );
1020         }
1021     }
1022     else
1023     {
1024         switch( p_sample->i_type )
1025         {
1026             /* qt decoder, send the complete chunk */
1027             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1028             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1029             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1030             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1031             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1032                 p_track->fmt.i_extra =
1033                     p_sample->data.p_sample_vide->i_qt_image_description;
1034                 if( p_track->fmt.i_extra > 0 )
1035                 {
1036                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1037                     memcpy( p_track->fmt.p_extra,
1038                             p_sample->data.p_sample_vide->p_qt_image_description,
1039                             p_track->fmt.i_extra);
1040                 }
1041                 break;
1042             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1043             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1044             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1045             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1046                 p_track->fmt.i_extra =
1047                     p_sample->data.p_sample_soun->i_qt_description;
1048                 if( p_track->fmt.i_extra > 0 )
1049                 {
1050                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1051                     memcpy( p_track->fmt.p_extra,
1052                             p_sample->data.p_sample_soun->p_qt_description,
1053                             p_track->fmt.i_extra);
1054                 }
1055                 break;
1056             default:
1057                 break;
1058         }
1059     }
1060
1061 #undef p_decconfig
1062
1063     /* some last initialisation */
1064     switch( p_track->fmt.i_cat )
1065     {
1066     case( VIDEO_ES ):
1067         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1068         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1069
1070         /* fall on display size */
1071         if( p_track->fmt.video.i_width <= 0 )
1072             p_track->fmt.video.i_width = p_track->i_width;
1073         if( p_track->fmt.video.i_height <= 0 )
1074             p_track->fmt.video.i_height = p_track->i_height;
1075
1076         /* Find out apect ratio from display size */
1077         if( p_track->i_width > 0 && p_track->i_height > 0 )
1078             p_track->fmt.video.i_aspect =
1079                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1080
1081         break;
1082
1083     case( AUDIO_ES ):
1084         p_track->fmt.audio.i_channels =
1085             p_sample->data.p_sample_soun->i_channelcount;
1086         p_track->fmt.audio.i_rate =
1087             p_sample->data.p_sample_soun->i_sampleratehi;
1088         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1089             p_sample->data.p_sample_soun->i_sampleratehi *
1090                 p_sample->data.p_sample_soun->i_samplesize;
1091         p_track->fmt.audio.i_bitspersample =
1092             p_sample->data.p_sample_soun->i_samplesize;
1093         break;
1094
1095     default:
1096         break;
1097     }
1098
1099     *pp_es = es_out_Add( p_input->p_es_out, &p_track->fmt );
1100
1101     return VLC_SUCCESS;
1102 }
1103
1104 /* given a time it return sample/chunk
1105  * it also update elst field of the track
1106  */
1107 static int  TrackTimeToSampleChunk( input_thread_t *p_input,
1108                                     mp4_track_t *p_track,
1109                                     int64_t i_start,
1110                                     uint32_t *pi_chunk,
1111                                     uint32_t *pi_sample )
1112 {
1113     demux_sys_t *p_sys = p_input->p_demux_data;
1114     MP4_Box_t   *p_stss;
1115     uint64_t     i_dts;
1116     unsigned int i_sample;
1117     unsigned int i_chunk;
1118     int          i_index;
1119
1120     /* FIXME see if it's needed to check p_track->i_chunk_count */
1121     if( !p_track->b_ok || p_track->i_chunk_count == 0 )
1122     {
1123         return( VLC_EGENERIC );
1124     }
1125
1126     /* handle elst (find the correct one) */
1127     MP4_TrackSetELST( p_input, p_track, i_start );
1128     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1129     {
1130         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1131         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1132
1133         /* now calculate i_start for this elst */
1134         /* offset */
1135         i_start -= p_track->i_elst_time * (int64_t)1000000 / p_sys->i_timescale;
1136         if( i_start < 0 )
1137         {
1138             *pi_chunk = 0;
1139             *pi_sample= 0;
1140
1141             return VLC_SUCCESS;
1142         }
1143         /* to track time scale */
1144         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1145         /* add elst offset */
1146         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1147              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1148             elst->i_media_time[p_track->i_elst] > 0 )
1149         {
1150             i_start += elst->i_media_time[p_track->i_elst];
1151         }
1152
1153         msg_Dbg( p_input, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd"ms (track)",
1154                  p_track->i_elst,
1155                  i_mvt * 1000 / p_sys->i_timescale,
1156                  i_start * 1000 / p_track->i_timescale );
1157     }
1158     else
1159     {
1160         /* convert absolute time to in timescale unit */
1161         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1162     }
1163
1164     /* we start from sample 0/chunk 0, hope it won't take too much time */
1165     /* *** find good chunk *** */
1166     for( i_chunk = 0; ; i_chunk++ )
1167     {
1168         if( i_chunk + 1 >= p_track->i_chunk_count )
1169         {
1170             /* at the end and can't check if i_start in this chunk,
1171                it will be check while searching i_sample */
1172             i_chunk = p_track->i_chunk_count - 1;
1173             break;
1174         }
1175
1176         if( i_start >= p_track->chunk[i_chunk].i_first_dts &&
1177             i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1178         {
1179             break;
1180         }
1181     }
1182
1183     /* *** find sample in the chunk *** */
1184     i_sample = p_track->chunk[i_chunk].i_sample_first;
1185     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1186     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1187     {
1188         if( i_dts +
1189             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1190             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < i_start )
1191         {
1192             i_dts    +=
1193                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1194                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1195
1196             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1197             i_index++;
1198         }
1199         else
1200         {
1201             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1202             {
1203                 break;
1204             }
1205             i_sample += ( i_start - i_dts ) / p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1206             break;
1207         }
1208     }
1209
1210     if( i_sample >= p_track->i_sample_count )
1211     {
1212         msg_Warn( p_input,
1213                   "track[Id 0x%x] will be disabled (seeking too far) chunk=%d sample=%d",
1214                   p_track->i_track_ID, i_chunk, i_sample );
1215         return( VLC_EGENERIC );
1216     }
1217
1218
1219     /* *** Try to find nearest sync points *** */
1220     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1221     {
1222         unsigned int i_index;
1223         msg_Dbg( p_input,
1224                     "track[Id 0x%x] using Sync Sample Box (stss)",
1225                     p_track->i_track_ID );
1226         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1227         {
1228             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1229             {
1230                 if( i_index > 0 )
1231                 {
1232                     msg_Dbg( p_input, "stts gives %d --> %d (sample number)",
1233                             i_sample,
1234                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1235                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1236                     /* new i_sample is less than old so i_chunk can only decreased */
1237                     while( i_chunk > 0 &&
1238                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1239                     {
1240                         i_chunk--;
1241                     }
1242                 }
1243                 else
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] );
1248                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1249                     /* new i_sample is more than old so i_chunk can only increased */
1250                     while( i_chunk < p_track->i_chunk_count - 1 &&
1251                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1252                                                 p_track->chunk[i_chunk].i_sample_count )
1253                     {
1254                         i_chunk++;
1255                     }
1256                 }
1257                 break;
1258             }
1259         }
1260     }
1261     else
1262     {
1263         msg_Dbg( p_input,
1264                     "track[Id 0x%x] does not provide Sync Sample Box (stss)",
1265                     p_track->i_track_ID );
1266     }
1267
1268     *pi_chunk  = i_chunk;
1269     *pi_sample = i_sample;
1270
1271     return VLC_SUCCESS;
1272 }
1273
1274 static int  TrackGotoChunkSample( input_thread_t   *p_input,
1275                                   mp4_track_t *p_track,
1276                                   unsigned int     i_chunk,
1277                                   unsigned int     i_sample )
1278 {
1279     vlc_bool_t b_reselect = VLC_FALSE;
1280
1281     /* now see if actual es is ok */
1282     if( p_track->i_chunk < 0 ||
1283         p_track->i_chunk >= p_track->i_chunk_count ||
1284         p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1285             p_track->chunk[i_chunk].i_sample_description_index )
1286     {
1287         msg_Warn( p_input, "Recreate ES" );
1288
1289         es_out_Control( p_input->p_es_out, ES_OUT_GET_ES_STATE, p_track->p_es, &b_reselect );
1290
1291         es_out_Del( p_input->p_es_out, p_track->p_es );
1292
1293         p_track->p_es = NULL;
1294
1295         if( TrackCreateES( p_input,
1296                            p_track, i_chunk,
1297                            &p_track->p_es ) )
1298         {
1299             msg_Err( p_input, "cannot create es for track[Id 0x%x]",
1300                      p_track->i_track_ID );
1301
1302             p_track->b_ok       = VLC_FALSE;
1303             p_track->b_selected = VLC_FALSE;
1304             return VLC_EGENERIC;
1305         }
1306     }
1307
1308     /* select again the new decoder */
1309     if( b_reselect )
1310     {
1311         es_out_Control( p_input->p_es_out, ES_OUT_SET_ES, p_track->p_es );
1312     }
1313
1314     p_track->i_chunk    = i_chunk;
1315     p_track->i_sample   = i_sample;
1316
1317     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1318 }
1319
1320 /****************************************************************************
1321  * MP4_TrackCreate:
1322  ****************************************************************************
1323  * Parse track information and create all needed data to run a track
1324  * If it succeed b_ok is set to 1 else to 0
1325  ****************************************************************************/
1326 static void MP4_TrackCreate( input_thread_t *p_input,
1327                              mp4_track_t *p_track,
1328                              MP4_Box_t  * p_box_trak )
1329 {
1330     demux_sys_t *p_sys = p_input->p_demux_data;
1331
1332     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1333     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1334     MP4_Box_t *p_elst;
1335
1336     MP4_Box_t *p_mdhd;
1337     MP4_Box_t *p_hdlr;
1338
1339     MP4_Box_t *p_vmhd;
1340     MP4_Box_t *p_smhd;
1341
1342     MP4_Box_t *p_drms;
1343
1344     unsigned int i;
1345     char language[4];
1346
1347     /* hint track unsuported */
1348
1349     /* set default value (-> track unusable) */
1350     p_track->b_ok       = VLC_FALSE;
1351     p_track->b_enable   = VLC_FALSE;
1352     p_track->b_selected = VLC_FALSE;
1353
1354     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1355
1356     if( !p_tkhd )
1357     {
1358         return;
1359     }
1360
1361     /* do we launch this track by default ? */
1362     p_track->b_enable =
1363         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1364
1365     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1366     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1367     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1368
1369     if( p_tref )
1370     {
1371 /*        msg_Warn( p_input, "unhandled box: tref --> FIXME" ); */
1372     }
1373
1374     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1375     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1376
1377     if( ( !p_mdhd )||( !p_hdlr ) )
1378     {
1379         return;
1380     }
1381
1382     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1383
1384     for( i = 0; i < 3; i++ )
1385     {
1386         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1387     }
1388     language[3] = '\0';
1389
1390     switch( p_hdlr->data.p_hdlr->i_handler_type )
1391     {
1392         case( FOURCC_soun ):
1393             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1394             {
1395                 return;
1396             }
1397             p_track->fmt.i_cat = AUDIO_ES;
1398             break;
1399
1400         case( FOURCC_vide ):
1401             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1402             {
1403                 return;
1404             }
1405             p_track->fmt.i_cat = VIDEO_ES;
1406             break;
1407
1408         default:
1409             return;
1410     }
1411
1412     p_track->i_elst = 0;
1413     p_track->i_elst_time = 0;
1414     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
1415     {
1416         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
1417         int i;
1418
1419         msg_Warn( p_input, "elst box found" );
1420         for( i = 0; i < elst->i_entry_count; i++ )
1421         {
1422             msg_Dbg( p_input, "   - [%d] duration="I64Fd"ms media time="I64Fd"ms) rate=%d.%d",
1423                      i,
1424                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
1425                      elst->i_media_time[i] >= 0 ?
1426                         elst->i_media_time[i] * 1000 / p_track->i_timescale : -1,
1427                      elst->i_media_rate_integer[i],
1428                      elst->i_media_rate_fraction[i] );
1429         }
1430     }
1431
1432
1433 /*  TODO
1434     add support for:
1435     p_dinf = MP4_BoxGet( p_minf, "dinf" );
1436 */
1437     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
1438         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
1439     {
1440         return;
1441     }
1442
1443     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
1444     p_track->b_drms = p_drms != NULL;
1445     p_track->p_drms = p_track->b_drms ?
1446         p_drms->data.p_sample_soun->p_drms : NULL;
1447
1448     /* Set language */
1449     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
1450     {
1451         p_track->fmt.psz_language = LanguageGetName( language );
1452     }
1453
1454     /* fxi i_timescale for AUDIO_ES with i_qt_version == 0 */
1455     if( p_track->fmt.i_cat == AUDIO_ES ) //&& p_track->i_sample_size == 1 )
1456     {
1457         MP4_Box_t *p_sample;
1458
1459         p_sample = MP4_BoxGet(  p_track->p_stsd, "[0]" );
1460         if( p_sample && p_sample->data.p_sample_soun)
1461         {
1462             MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1463             if( p_soun->i_qt_version == 0 &&
1464                 p_track->i_timescale != p_soun->i_sampleratehi )
1465             {
1466                 msg_Warn( p_input,
1467                           "i_timescale ("I64Fu") != i_sampleratehi (%u) with "
1468                           "qt_version == 0\n"
1469                           "Making both equal. (report any problem)",
1470                           p_track->i_timescale, p_soun->i_sampleratehi );
1471
1472                 if( p_soun->i_sampleratehi )
1473                     p_track->i_timescale = p_soun->i_sampleratehi;
1474                 else
1475                     p_soun->i_sampleratehi = p_track->i_timescale;
1476             }
1477         }
1478     }
1479
1480     /* Create chunk index table and sample index table */
1481     if( TrackCreateChunksIndex( p_input,p_track  ) ||
1482         TrackCreateSamplesIndex( p_input, p_track ) )
1483     {
1484         return; /* cannot create chunks index */
1485     }
1486
1487     p_track->i_chunk  = 0;
1488     p_track->i_sample = 0;
1489
1490     /* now create es */
1491     if( TrackCreateES( p_input,
1492                        p_track, p_track->i_chunk,
1493                        &p_track->p_es ) )
1494     {
1495         msg_Err( p_input, "cannot create es for track[Id 0x%x]",
1496                  p_track->i_track_ID );
1497         return;
1498     }
1499
1500 #if 0
1501     {
1502         int i;
1503         for( i = 0; i < p_track->i_chunk_count; i++ )
1504         {
1505             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n", i, p_track->chunk[i].i_sample_count, p_track->chunk[i].i_first_dts );
1506
1507         }
1508     }
1509 #endif
1510     p_track->b_ok = VLC_TRUE;
1511 }
1512
1513 /****************************************************************************
1514  * MP4_TrackDestroy:
1515  ****************************************************************************
1516  * Destroy a track created by MP4_TrackCreate.
1517  ****************************************************************************/
1518 static void MP4_TrackDestroy( input_thread_t *p_input,
1519                               mp4_track_t *p_track )
1520 {
1521     unsigned int i_chunk;
1522
1523     p_track->b_ok = VLC_FALSE;
1524     p_track->b_enable   = VLC_FALSE;
1525     p_track->b_selected = VLC_FALSE;
1526
1527     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1528
1529     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
1530     {
1531         if( p_track->chunk )
1532         {
1533            FREE(p_track->chunk[i_chunk].p_sample_count_dts);
1534            FREE(p_track->chunk[i_chunk].p_sample_delta_dts );
1535         }
1536     }
1537     FREE( p_track->chunk );
1538
1539     if( !p_track->i_sample_size )
1540     {
1541         FREE( p_track->p_sample_size );
1542     }
1543 }
1544
1545 static int  MP4_TrackSelect ( input_thread_t    *p_input,
1546                               mp4_track_t  *p_track,
1547                               mtime_t           i_start )
1548 {
1549     if( !p_track->b_ok )
1550     {
1551         return VLC_EGENERIC;
1552     }
1553
1554     if( p_track->b_selected )
1555     {
1556         msg_Warn( p_input,
1557                   "track[Id 0x%x] already selected",
1558                   p_track->i_track_ID );
1559         return VLC_SUCCESS;
1560     }
1561
1562     return MP4_TrackSeek( p_input, p_track, i_start );
1563 }
1564
1565 static void MP4_TrackUnselect(input_thread_t    *p_input,
1566                               mp4_track_t  *p_track )
1567 {
1568     if( !p_track->b_ok )
1569     {
1570         return;
1571     }
1572
1573     if( !p_track->b_selected )
1574     {
1575         msg_Warn( p_input,
1576                   "track[Id 0x%x] already unselected",
1577                   p_track->i_track_ID );
1578         return;
1579     }
1580     if( p_track->p_es )
1581     {
1582         es_out_Control( p_input->p_es_out, ES_OUT_SET_ES_STATE, p_track->p_es, VLC_FALSE );
1583     }
1584
1585     p_track->b_selected = VLC_FALSE;
1586 }
1587
1588 static int  MP4_TrackSeek   ( input_thread_t    *p_input,
1589                               mp4_track_t  *p_track,
1590                               mtime_t           i_start )
1591 {
1592     uint32_t i_chunk;
1593     uint32_t i_sample;
1594
1595     if( !p_track->b_ok )
1596     {
1597         return( VLC_EGENERIC );
1598     }
1599
1600     if( TrackTimeToSampleChunk( p_input,
1601                                 p_track, i_start,
1602                                 &i_chunk, &i_sample ) )
1603     {
1604         msg_Warn( p_input,
1605                   "cannot select track[Id 0x%x]",
1606                   p_track->i_track_ID );
1607         return( VLC_EGENERIC );
1608     }
1609
1610     p_track->b_selected = VLC_TRUE;
1611
1612     if( TrackGotoChunkSample( p_input, p_track, i_chunk, i_sample ) )
1613     {
1614         p_track->b_selected = VLC_FALSE;
1615     }
1616     return( p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC );
1617 }
1618
1619
1620 /*
1621  * 3 types: for audio
1622  * 
1623  */
1624 #define QT_V0_MAX_SAMPLES    1500
1625 static int  MP4_TrackSampleSize( mp4_track_t   *p_track )
1626 {
1627     int i_size;
1628     MP4_Box_data_sample_soun_t *p_soun;
1629
1630     if( p_track->i_sample_size == 0 )
1631     {
1632         /* most simple case */
1633         return( p_track->p_sample_size[p_track->i_sample] );
1634     }
1635     if( p_track->fmt.i_cat != AUDIO_ES )
1636     {
1637         return( p_track->i_sample_size );
1638     }
1639
1640     if( p_track->i_sample_size != 1 )
1641     {
1642         //msg_Warn( p_input, "SampleSize != 1" );
1643         return( p_track->i_sample_size );
1644     }
1645
1646     p_soun = p_track->p_sample->data.p_sample_soun;
1647
1648     if( p_soun->i_qt_version == 1 )
1649     {
1650         i_size = p_track->chunk[p_track->i_chunk].i_sample_count / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
1651     }
1652     else
1653     {
1654         /* FIXME */
1655         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
1656                 ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first );
1657         if( i_samples > QT_V0_MAX_SAMPLES )
1658         {
1659             i_samples = QT_V0_MAX_SAMPLES;
1660         }
1661         i_size = i_samples * p_soun->i_channelcount * p_soun->i_samplesize / 8;
1662     }
1663
1664     //fprintf( stderr, "size=%d\n", i_size );
1665     return( i_size );
1666 }
1667
1668
1669 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
1670 {
1671     unsigned int i_sample;
1672     uint64_t i_pos;
1673
1674
1675     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
1676
1677     if( p_track->i_sample_size )
1678     {
1679         MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
1680
1681         if( p_soun->i_qt_version == 0 )
1682         {
1683             i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) *
1684                         p_soun->i_channelcount * p_soun->i_samplesize / 8;
1685         }
1686         else
1687         {
1688             /* we read chunk by chunk */
1689             i_pos += 0;
1690         }
1691     }
1692     else
1693     {
1694         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
1695                 i_sample < p_track->i_sample; i_sample++ )
1696         {
1697             i_pos += p_track->p_sample_size[i_sample];
1698         }
1699
1700     }
1701     return( i_pos );
1702 }
1703
1704 static int  MP4_TrackNextSample( input_thread_t     *p_input,
1705                                  mp4_track_t   *p_track )
1706 {
1707
1708     if( p_track->fmt.i_cat == AUDIO_ES &&
1709         p_track->i_sample_size != 0 )
1710     {
1711         MP4_Box_data_sample_soun_t *p_soun;
1712
1713         p_soun = p_track->p_sample->data.p_sample_soun;
1714
1715         if( p_soun->i_qt_version == 1 )
1716         {
1717             /* chunk by chunk */
1718             p_track->i_sample =
1719                 p_track->chunk[p_track->i_chunk].i_sample_first +
1720                 p_track->chunk[p_track->i_chunk].i_sample_count;
1721         }
1722         else
1723         {
1724             /* FIXME */
1725             p_track->i_sample += QT_V0_MAX_SAMPLES;
1726             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 )
1727             {
1728                 p_track->i_sample =
1729                     p_track->chunk[p_track->i_chunk].i_sample_first +
1730                     p_track->chunk[p_track->i_chunk].i_sample_count;
1731             }
1732         }
1733     }
1734     else
1735     {
1736         p_track->i_sample++;
1737     }
1738
1739     if( p_track->i_sample >= p_track->i_sample_count )
1740     {
1741         /* we have reach end of the track so free decoder stuff */
1742         msg_Warn( p_input, "track[0x%x] will be disabled", p_track->i_track_ID );
1743         MP4_TrackUnselect( p_input, p_track );
1744         return VLC_EGENERIC;
1745     }
1746
1747     /* Have we changed chunk ? */
1748     if( p_track->i_sample >=
1749             p_track->chunk[p_track->i_chunk].i_sample_first +
1750             p_track->chunk[p_track->i_chunk].i_sample_count )
1751     {
1752         if( TrackGotoChunkSample( p_input,
1753                                   p_track,
1754                                   p_track->i_chunk + 1,
1755                                   p_track->i_sample ) )
1756         {
1757             msg_Warn( p_input, "track[0x%x] will be disabled (cannot restart decoder)", p_track->i_track_ID );
1758             MP4_TrackUnselect( p_input, p_track );
1759             return VLC_EGENERIC;
1760         }
1761     }
1762
1763     /* Have we changed elst */
1764     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1765     {
1766         demux_sys_t *p_sys = p_input->p_demux_data;
1767         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1768         int64_t i_mvt = MP4_TrackGetPTS( p_input, p_track ) * p_sys->i_timescale / (int64_t)1000000;
1769
1770         if( p_track->i_elst < elst->i_entry_count &&
1771             i_mvt >= p_track->i_elst_time + elst->i_segment_duration[p_track->i_elst] )
1772         {
1773             MP4_TrackSetELST( p_input, p_track, MP4_TrackGetPTS( p_input, p_track ) );
1774         }
1775     }
1776
1777     return VLC_SUCCESS;
1778 }
1779
1780 static void MP4_TrackSetELST( input_thread_t *p_input, mp4_track_t *tk, int64_t i_time )
1781 {
1782     demux_sys_t *p_sys = p_input->p_demux_data;
1783     int         i_elst_last = tk->i_elst;
1784
1785     /* handle elst (find the correct one) */
1786     tk->i_elst      = 0;
1787     tk->i_elst_time = 0;
1788     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
1789     {
1790         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
1791         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
1792
1793         for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
1794         {
1795             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
1796
1797             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
1798             {
1799                 break;
1800             }
1801             tk->i_elst_time += i_dur;
1802         }
1803
1804         if( tk->i_elst >= elst->i_entry_count )
1805         {
1806             /* msg_Dbg( p_input, "invalid number of entry in elst" ); */
1807             tk->i_elst = elst->i_entry_count - 1;
1808             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
1809         }
1810
1811         if( elst->i_media_time[tk->i_elst] < 0 )
1812         {
1813             /* track offset */
1814             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
1815         }
1816     }
1817     if( i_elst_last != tk->i_elst )
1818     {
1819         msg_Warn( p_input, "elst old=%d new=%d", i_elst_last, tk->i_elst );
1820     }
1821 }
1822
1823 static char *LanguageGetName( const char *psz_code )
1824 {
1825     const iso639_lang_t *pl;
1826
1827     pl = GetLang_2B( psz_code );
1828     if( !strcmp( pl->psz_iso639_1, "??" ) )
1829     {
1830         pl = GetLang_2T( psz_code );
1831     }
1832
1833     if( !strcmp( pl->psz_iso639_1, "??" ) )
1834     {
1835        return strdup( psz_code );
1836     }
1837
1838     if( *pl->psz_native_name )
1839     {
1840         return strdup( pl->psz_native_name );
1841     }
1842     return strdup( pl->psz_eng_name );
1843 }
1844