]> git.sesse.net Git - vlc/blob - modules/demux/mp4/mp4.c
Allow playback of in24 little-endian or big-endian in mov files.
[vlc] / modules / demux / mp4 / mp4.c
1 /*****************************************************************************
2  * mp4.c : MP4 file input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 the VideoLAN team
5  * $Id$
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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26
27 #include <vlc/vlc.h>
28
29 #include <stdio.h>
30 #include <stdlib.h>                                      /* malloc(), free() */
31
32 #include <vlc_demux.h>
33 #include <vlc_playlist.h>
34 #include <vlc_md5.h>
35 #include <vlc_charset.h>
36 #include "iso_lang.h"
37 #include <vlc_meta.h>
38
39 #include "libmp4.h"
40 #include "drms.h"
41
42 #ifdef UNDER_CE
43 #define uint64_t int64_t
44 #endif
45
46 /*****************************************************************************
47  * Module descriptor
48  *****************************************************************************/
49 static int  Open ( vlc_object_t * );
50 static void Close( vlc_object_t * );
51
52 vlc_module_begin();
53     set_category( CAT_INPUT );
54     set_subcategory( SUBCAT_INPUT_DEMUX );
55     set_description( _("MP4 stream demuxer") );
56     set_capability( "demux2", 242 );
57     set_callbacks( Open, Close );
58 vlc_module_end();
59
60 /*****************************************************************************
61  * Local prototypes
62  *****************************************************************************/
63 static int   Demux   ( demux_t * );
64 static int   DemuxRef( demux_t *p_demux ){ return 0;}
65 static int   Seek    ( demux_t *, mtime_t );
66 static int   Control ( demux_t *, int, va_list );
67
68 /* Contain all information about a chunk */
69 typedef struct
70 {
71     uint64_t     i_offset; /* absolute position of this chunk in the file */
72     uint32_t     i_sample_description_index; /* index for SampleEntry to use */
73     uint32_t     i_sample_count; /* how many samples in this chunk */
74     uint32_t     i_sample_first; /* index of the first sample in this chunk */
75
76     /* now provide way to calculate pts, dts, and offset without to
77         much memory and with fast acces */
78
79     /* with this we can calculate dts/pts without waste memory */
80     uint64_t     i_first_dts;
81     uint32_t     *p_sample_count_dts;
82     uint32_t     *p_sample_delta_dts;   /* dts delta */
83
84     uint32_t     *p_sample_count_pts;
85     int32_t      *p_sample_offset_pts;  /* pts-dts */
86
87     /* TODO if needed add pts
88         but quickly *add* support for edts and seeking */
89
90 } mp4_chunk_t;
91
92  /* Contain all needed information for read all track with vlc */
93 typedef struct
94 {
95     unsigned int i_track_ID;/* this should be unique */
96
97     int b_ok;               /* The track is usable */
98     int b_enable;           /* is the trak enable by default */
99     vlc_bool_t b_selected;  /* is the trak being played */
100     vlc_bool_t b_chapter;   /* True when used for chapter only */
101
102     es_format_t fmt;
103     es_out_id_t *p_es;
104
105     /* display size only ! */
106     int i_width;
107     int i_height;
108
109     /* more internal data */
110     uint64_t        i_timescale;    /* time scale for this track only */
111
112     /* elst */
113     int             i_elst;         /* current elst */
114     int64_t         i_elst_time;    /* current elst start time (in movie time scale)*/
115     MP4_Box_t       *p_elst;        /* elst (could be NULL) */
116
117     /* give the next sample to read, i_chunk is to find quickly where
118       the sample is located */
119     uint32_t         i_sample;       /* next sample to read */
120     uint32_t         i_chunk;        /* chunk where next sample is stored */
121     /* total count of chunk and sample */
122     uint32_t         i_chunk_count;
123     uint32_t         i_sample_count;
124
125     mp4_chunk_t    *chunk; /* always defined  for each chunk */
126
127     /* sample size, p_sample_size defined only if i_sample_size == 0
128         else i_sample_size is size for all sample */
129     uint32_t         i_sample_size;
130     uint32_t         *p_sample_size; /* XXX perhaps add file offset if take
131                                     too much time to do sumations each time*/
132
133     MP4_Box_t *p_stbl;  /* will contain all timing information */
134     MP4_Box_t *p_stsd;  /* will contain all data to initialize decoder */
135     MP4_Box_t *p_sample;/* point on actual sdsd */
136
137     vlc_bool_t b_drms;
138     void      *p_drms;
139
140 } mp4_track_t;
141
142
143 struct demux_sys_t
144 {
145     MP4_Box_t    *p_root;      /* container for the whole file */
146
147     mtime_t      i_pcr;
148
149     uint64_t     i_time;         /* time position of the presentation
150                                   * in movie timescale */
151     uint64_t     i_timescale;    /* movie time scale */
152     uint64_t     i_duration;     /* movie duration */
153     unsigned int i_tracks;       /* number of tracks */
154     mp4_track_t  *track;         /* array of track */
155
156     /* */
157     MP4_Box_t    *p_tref_chap;
158
159     /* */
160     input_title_t *p_title;
161 };
162
163 /*****************************************************************************
164  * Declaration of local function
165  *****************************************************************************/
166 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t  *);
167 static void MP4_TrackDestroy( demux_t *, mp4_track_t * );
168
169 static int  MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
170 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
171
172 static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, mtime_t );
173
174 static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
175 static int      MP4_TrackSampleSize( mp4_track_t * );
176 static int      MP4_TrackNextSample( demux_t *, mp4_track_t * );
177 static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
178
179 static void     MP4_UpdateSeekpoint( demux_t * );
180
181 /* Return time in s of a track */
182 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
183 {
184 #define chunk p_track->chunk[p_track->i_chunk]
185
186     unsigned int i_index = 0;
187     unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
188     int64_t i_dts = chunk.i_first_dts;
189
190     while( i_sample > 0 )
191     {
192         if( i_sample > chunk.p_sample_count_dts[i_index] )
193         {
194             i_dts += chunk.p_sample_count_dts[i_index] *
195                 chunk.p_sample_delta_dts[i_index];
196             i_sample -= chunk.p_sample_count_dts[i_index];
197             i_index++;
198         }
199         else
200         {
201             i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
202             i_sample = 0;
203             break;
204         }
205     }
206
207 #undef chunk
208
209     /* now handle elst */
210     if( p_track->p_elst )
211     {
212         demux_sys_t         *p_sys = p_demux->p_sys;
213         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
214
215         /* convert to offset */
216         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
217               elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
218             elst->i_media_time[p_track->i_elst] > 0 )
219         {
220             i_dts -= elst->i_media_time[p_track->i_elst];
221         }
222
223         /* add i_elst_time */
224         i_dts += p_track->i_elst_time * p_track->i_timescale /
225             p_sys->i_timescale;
226
227         if( i_dts < 0 ) i_dts = 0;
228     }
229
230     return I64C(1000000) * i_dts / p_track->i_timescale;
231 }
232
233 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
234 {
235     mp4_chunk_t *ck = &p_track->chunk[p_track->i_chunk];
236     unsigned int i_index = 0;
237     unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
238
239     if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
240         return -1;
241
242     for( i_index = 0;; i_index++ )
243     {
244         if( i_sample < ck->p_sample_count_pts[i_index] )
245             return ck->p_sample_offset_pts[i_index] * I64C(1000000) /
246                    (int64_t)p_track->i_timescale;
247
248         i_sample -= ck->p_sample_count_pts[i_index];
249     }
250 }
251
252 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
253 {
254     return I64C(1000000) * p_sys->i_time / p_sys->i_timescale;
255 }
256
257 /* Function to lookup the currently playing item */
258 static vlc_bool_t FindItem( demux_t *p_demux, playlist_t *p_playlist,
259                      playlist_item_t **pp_item );
260
261 static void LoadChapter( demux_t  *p_demux );
262
263 /*****************************************************************************
264  * Open: check file and initializes MP4 structures
265  *****************************************************************************/
266 static int Open( vlc_object_t * p_this )
267 {
268     demux_t  *p_demux = (demux_t *)p_this;
269     demux_sys_t     *p_sys;
270
271     uint8_t         *p_peek;
272
273     MP4_Box_t       *p_ftyp;
274     MP4_Box_t       *p_rmra;
275     MP4_Box_t       *p_mvhd;
276     MP4_Box_t       *p_trak;
277
278     unsigned int    i;
279     vlc_bool_t      b_seekable;
280
281     /* A little test to see if it could be a mp4 */
282     if( stream_Peek( p_demux->s, &p_peek, 8 ) < 8 ) return VLC_EGENERIC;
283
284     switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
285     {
286         case FOURCC_ftyp:
287         case FOURCC_moov:
288         case FOURCC_foov:
289         case FOURCC_moof:
290         case FOURCC_mdat:
291         case FOURCC_udta:
292         case FOURCC_free:
293         case FOURCC_skip:
294         case FOURCC_wide:
295         case VLC_FOURCC( 'p', 'n', 'o', 't' ):
296             break;
297          default:
298             return VLC_EGENERIC;
299     }
300
301     /* I need to seek */
302     stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
303     if( !b_seekable )
304     {
305         msg_Warn( p_demux, "MP4 plugin discarded (unseekable)" );
306         return VLC_EGENERIC;
307     }
308
309     /*Set exported functions */
310     p_demux->pf_demux = Demux;
311     p_demux->pf_control = Control;
312
313     /* create our structure that will contains all data */
314     p_demux->p_sys = p_sys = malloc( sizeof( demux_sys_t ) );
315     memset( p_sys, 0, sizeof( demux_sys_t ) );
316
317     /* Now load all boxes ( except raw data ) */
318     if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
319     {
320         msg_Warn( p_demux, "MP4 plugin discarded (not a valid file)" );
321         goto error;
322     }
323
324     MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
325
326     if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
327     {
328         switch( p_ftyp->data.p_ftyp->i_major_brand )
329         {
330             case( FOURCC_isom ):
331                 msg_Dbg( p_demux,
332                          "ISO Media file (isom) version %d.",
333                          p_ftyp->data.p_ftyp->i_minor_version );
334                 break;
335             default:
336                 msg_Dbg( p_demux,
337                          "unrecognized major file specification (%4.4s).",
338                           (char*)&p_ftyp->data.p_ftyp->i_major_brand );
339                 break;
340         }
341     }
342     else
343     {
344         msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
345     }
346
347     /* the file need to have one moov box */
348     if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
349     {
350         MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
351
352         if( !p_foov )
353         {
354             msg_Err( p_demux, "MP4 plugin discarded (no moov box)" );
355             goto error;
356         }
357         /* we have a free box as a moov, rename it */
358         p_foov->i_type = FOURCC_moov;
359     }
360
361     if( ( p_rmra = MP4_BoxGet( p_sys->p_root,  "/moov/rmra" ) ) )
362     {
363         playlist_t *p_playlist;
364         playlist_item_t *p_current, *p_item_in_category;
365         int        i_count = MP4_BoxCount( p_rmra, "rmda" );
366         int        i;
367         vlc_bool_t b_play = VLC_FALSE;
368
369         msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
370
371         p_playlist = pl_Yield( p_demux );
372         if( p_playlist )
373         {
374             b_play = FindItem( p_demux, p_playlist, &p_current );
375             p_item_in_category = playlist_ItemToNode( p_playlist, p_current, VLC_TRUE );
376             p_current->p_input->i_type = ITEM_TYPE_PLAYLIST;
377
378             for( i = 0; i < i_count; i++ )
379             {
380                 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
381                 char      *psz_ref;
382                 uint32_t  i_ref_type;
383
384                 if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
385                 {
386                     continue;
387                 }
388                 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
389
390                 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
391                          psz_ref, (char*)&i_ref_type );
392
393                 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
394                 {
395                     if( strstr( psz_ref, "qt5gateQT" ) )
396                     {
397                         msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
398                         continue;
399                     }
400                     if( !strncmp( psz_ref, "http://", 7 ) ||
401                         !strncmp( psz_ref, "rtsp://", 7 ) )
402                     {
403                         ;
404                     }
405                     else
406                     {
407                         char *psz_absolute;
408                         char *psz_path = strdup( p_demux->psz_path );
409                         char *end = strrchr( psz_path, '/' );
410                         if( end ) end[1] = '\0';
411                         else *psz_path = '\0';
412
413                         asprintf( &psz_absolute, "%s://%s%s",
414                                       p_demux->psz_access, psz_path, psz_ref );
415
416                         if( psz_ref ) free( psz_ref );
417                         psz_ref = psz_absolute;
418                         free( psz_path );
419                     }
420                     if( p_current )
421                     {
422                         input_item_t *p_input;
423                         msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
424                         p_input = input_ItemNewExt( p_playlist, psz_ref, NULL,
425                                             0, NULL, -1 );
426                         input_ItemCopyOptions( p_current->p_input, p_input );
427                         playlist_BothAddInput( p_playlist, p_input,
428                                                p_item_in_category,
429                                                PLAYLIST_APPEND, PLAYLIST_END,
430                                                NULL, NULL, VLC_FALSE );
431                     }
432                 }
433                 else
434                 {
435                     msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
436                              (char*)&p_rdrf->data.p_rdrf->i_ref_type );
437                 }
438                 if( psz_ref ) free( psz_ref );
439             }
440             if( b_play && p_item_in_category &&
441                 p_item_in_category->i_children > 0 )
442             {
443                 playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, VLC_TRUE,
444                                   p_item_in_category, NULL );
445             }
446             vlc_object_release( p_playlist );
447         }
448         else
449         {
450             msg_Err( p_demux, "can't find playlist" );
451         }
452     }
453
454     if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
455     {
456         if( !p_rmra )
457         {
458             msg_Err( p_demux, "cannot find /moov/mvhd" );
459             goto error;
460         }
461         else
462         {
463             msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
464             p_demux->pf_demux = DemuxRef;
465             return VLC_SUCCESS;
466         }
467     }
468     else
469     {
470         p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
471         p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
472     }
473
474     if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
475     {
476         msg_Err( p_demux, "cannot find any /moov/trak" );
477         goto error;
478     }
479     msg_Dbg( p_demux, "find %d track%c",
480                         p_sys->i_tracks,
481                         p_sys->i_tracks ? 's':' ' );
482
483     /* allocate memory */
484     p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
485     memset( p_sys->track, 0, p_sys->i_tracks * sizeof( mp4_track_t ) );
486
487     /* Search the first chap reference (like quicktime) */
488     p_sys->p_tref_chap = NULL;
489     for( i = 0; i < p_sys->i_tracks; i++ )
490     {
491         MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
492         MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
493         if( !p_chap || p_chap->data.p_tref_generic->i_entry_count <= 0 )
494             continue;
495
496         p_sys->p_tref_chap = p_chap;
497         break;
498     }
499
500     /* now process each track and extract all usefull information */
501     for( i = 0; i < p_sys->i_tracks; i++ )
502     {
503         p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
504         MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak );
505
506         if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
507         {
508             const char *psz_cat;
509             switch( p_sys->track[i].fmt.i_cat )
510             {
511                 case( VIDEO_ES ):
512                     psz_cat = "video";
513                     break;
514                 case( AUDIO_ES ):
515                     psz_cat = "audio";
516                     break;
517                 case( SPU_ES ):
518                     psz_cat = "subtitle";
519                     break;
520
521                 default:
522                     psz_cat = "unknown";
523                     break;
524             }
525
526             msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
527                      p_sys->track[i].i_track_ID, psz_cat,
528                      p_sys->track[i].b_enable ? "enable":"disable",
529                      p_sys->track[i].fmt.psz_language ?
530                      p_sys->track[i].fmt.psz_language : "undef" );
531         }
532         else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
533         {
534             msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
535                      p_sys->track[i].i_track_ID,
536                      p_sys->track[i].fmt.psz_language ?
537                      p_sys->track[i].fmt.psz_language : "undef" );
538         }
539         else
540         {
541             msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
542                      p_sys->track[i].i_track_ID );
543         }
544     }
545
546     /* */
547     LoadChapter( p_demux );
548
549     return VLC_SUCCESS;
550
551 error:
552     if( p_sys->p_root )
553     {
554         MP4_BoxFree( p_demux->s, p_sys->p_root );
555     }
556     free( p_sys );
557     return VLC_EGENERIC;
558 }
559
560 /*****************************************************************************
561  * Demux: read packet and send them to decoders
562  *****************************************************************************
563  * TODO check for newly selected track (ie audio upt to now )
564  *****************************************************************************/
565 static int Demux( demux_t *p_demux )
566 {
567     demux_sys_t *p_sys = p_demux->p_sys;
568     unsigned int i_track;
569
570
571     unsigned int i_track_selected;
572
573     /* check for newly selected/unselected track */
574     for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
575          i_track++ )
576     {
577         mp4_track_t *tk = &p_sys->track[i_track];
578         vlc_bool_t b;
579
580         if( !tk->b_ok || tk->b_chapter ||
581             ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
582         {
583             continue;
584         }
585
586         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
587
588         if( tk->b_selected && !b )
589         {
590             MP4_TrackUnselect( p_demux, tk );
591         }
592         else if( !tk->b_selected && b)
593         {
594             MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
595         }
596
597         if( tk->b_selected )
598         {
599             i_track_selected++;
600         }
601     }
602
603     if( i_track_selected <= 0 )
604     {
605         p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
606         if( p_sys->i_timescale > 0 )
607         {
608             int64_t i_length = (mtime_t)1000000 *
609                                (mtime_t)p_sys->i_duration /
610                                (mtime_t)p_sys->i_timescale;
611             if( MP4_GetMoviePTS( p_sys ) >= i_length )
612                 return 0;
613             return 1;
614         }
615
616         msg_Warn( p_demux, "no track selected, exiting..." );
617         return 0;
618     }
619
620     /* */
621     MP4_UpdateSeekpoint( p_demux );
622
623     /* first wait for the good time to read a packet */
624     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pcr + 1 );
625
626     p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
627
628     /* we will read 100ms for each stream so ...*/
629     p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
630
631     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
632     {
633         mp4_track_t *tk = &p_sys->track[i_track];
634
635         if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
636             continue;
637
638         while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
639         {
640 #if 0
641             msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
642                      MP4_TrackGetDTS( p_demux, tk ),
643                      MP4_GetMoviePTS( p_sys ) );
644 #endif
645
646             if( MP4_TrackSampleSize( tk ) > 0 )
647             {
648                 block_t *p_block;
649                 int64_t i_delta;
650
651                 /* go,go go ! */
652                 if( stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
653                 {
654                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
655                               tk->i_track_ID );
656                     MP4_TrackUnselect( p_demux, tk );
657                     break;
658                 }
659
660                 /* now read pes */
661                 if( !(p_block =
662                          stream_Block( p_demux->s, MP4_TrackSampleSize(tk) )) )
663                 {
664                     msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
665                               tk->i_track_ID );
666                     MP4_TrackUnselect( p_demux, tk );
667                     break;
668                 }
669
670                 if( tk->b_drms && tk->p_drms )
671                 {
672                     drms_decrypt( tk->p_drms, (uint32_t*)p_block->p_buffer,
673                                   p_block->i_buffer );
674                 }
675                 else if( tk->fmt.i_cat == SPU_ES )
676                 {
677                     if( tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) &&
678                         p_block->i_buffer >= 2 )
679                     {
680                         uint16_t i_size = GetWBE( p_block->p_buffer );
681
682                         if( i_size + 2 <= p_block->i_buffer )
683                         {
684                             char *p;
685                             /* remove the length field, and append a '\0' */
686                             memmove( &p_block->p_buffer[0],
687                                      &p_block->p_buffer[2], i_size );
688                             p_block->p_buffer[i_size] = '\0';
689                             p_block->i_buffer = i_size + 1;
690
691                             /* convert \r -> \n */
692                             while( ( p = strchr((char *) p_block->p_buffer, '\r' ) ) )
693                             {
694                                 *p = '\n';
695                             }
696                         }
697                         else
698                         {
699                             /* Invalid */
700                             p_block->i_buffer = 0;
701                         }
702                     }
703                 }
704                 /* dts */
705                 p_block->i_dts = MP4_TrackGetDTS( p_demux, tk ) + 1;
706                 /* pts */
707                 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
708                 if( i_delta != -1 )
709                     p_block->i_pts = p_block->i_dts + i_delta;
710                 else if( tk->fmt.i_cat != VIDEO_ES )
711                     p_block->i_pts = p_block->i_dts;
712                 else
713                     p_block->i_pts = 0;
714
715                 if( !tk->b_drms || ( tk->b_drms && tk->p_drms ) )
716                     es_out_Send( p_demux->out, tk->p_es, p_block );
717             }
718
719             /* Next sample */
720             if( MP4_TrackNextSample( p_demux, tk ) )
721                 break;
722         }
723     }
724
725     return 1;
726 }
727
728 static void MP4_UpdateSeekpoint( demux_t *p_demux )
729 {
730     demux_sys_t *p_sys = p_demux->p_sys;
731     int64_t i_time;
732     int i;
733     if( !p_sys->p_title )
734         return;
735     i_time = MP4_GetMoviePTS( p_sys );
736     for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
737     {
738         if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
739             break;
740     }
741     i--;
742
743     if( i != p_demux->info.i_seekpoint && i >= 0 )
744     {
745         p_demux->info.i_seekpoint = i;
746         p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
747     }
748 }
749 /*****************************************************************************
750  * Seek: Got to i_date
751 ******************************************************************************/
752 static int Seek( demux_t *p_demux, mtime_t i_date )
753 {
754     demux_sys_t *p_sys = p_demux->p_sys;
755     unsigned int i_track;
756
757     /* First update update global time */
758     p_sys->i_time = i_date * p_sys->i_timescale / 1000000;
759     p_sys->i_pcr  = i_date;
760
761     /* Now for each stream try to go to this time */
762     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
763     {
764         mp4_track_t *tk = &p_sys->track[i_track];
765         MP4_TrackSeek( p_demux, tk, i_date );
766     }
767     MP4_UpdateSeekpoint( p_demux );
768     return VLC_SUCCESS;
769 }
770
771 /*****************************************************************************
772  * Control:
773  *****************************************************************************/
774 static int Control( demux_t *p_demux, int i_query, va_list args )
775 {
776     demux_sys_t *p_sys = p_demux->p_sys;
777
778     double f, *pf;
779     int64_t i64, *pi64;
780
781     switch( i_query )
782     {
783         case DEMUX_GET_POSITION:
784             pf = (double*)va_arg( args, double * );
785             if( p_sys->i_duration > 0 )
786             {
787                 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
788             }
789             else
790             {
791                 *pf = 0.0;
792             }
793             return VLC_SUCCESS;
794
795         case DEMUX_SET_POSITION:
796             f = (double)va_arg( args, double );
797             if( p_sys->i_timescale > 0 )
798             {
799                 i64 = (int64_t)( f * (double)1000000 *
800                                  (double)p_sys->i_duration /
801                                  (double)p_sys->i_timescale );
802                 return Seek( p_demux, i64 );
803             }
804             else return VLC_SUCCESS;
805
806         case DEMUX_GET_TIME:
807             pi64 = (int64_t*)va_arg( args, int64_t * );
808             if( p_sys->i_timescale > 0 )
809             {
810                 *pi64 = (mtime_t)1000000 *
811                         (mtime_t)p_sys->i_time /
812                         (mtime_t)p_sys->i_timescale;
813             }
814             else *pi64 = 0;
815             return VLC_SUCCESS;
816
817         case DEMUX_SET_TIME:
818             i64 = (int64_t)va_arg( args, int64_t );
819             return Seek( p_demux, i64 );
820
821         case DEMUX_GET_LENGTH:
822             pi64 = (int64_t*)va_arg( args, int64_t * );
823             if( p_sys->i_timescale > 0 )
824             {
825                 *pi64 = (mtime_t)1000000 *
826                         (mtime_t)p_sys->i_duration /
827                         (mtime_t)p_sys->i_timescale;
828             }
829             else *pi64 = 0;
830             return VLC_SUCCESS;
831
832         case DEMUX_GET_FPS:
833             msg_Warn( p_demux, "DEMUX_GET_FPS unimplemented !!" );
834             return VLC_EGENERIC;
835
836         case DEMUX_GET_META:
837         {
838             vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
839             MP4_Box_t  *p_0xa9xxx;
840
841             MP4_Box_t  *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
842             if( p_udta == NULL )
843             {
844                 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
845                 if( p_udta == NULL )
846                 {
847                     return VLC_EGENERIC;
848                 }
849             }
850
851             for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
852                  p_0xa9xxx = p_0xa9xxx->p_next )
853             {
854
855                 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
856                     continue;
857
858                 /* FIXME FIXME: should convert from whatever the character
859                  * encoding of MP4 meta data is to UTF-8. */
860 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
861     if( psz_utf ) { EnsureUTF8( psz_utf );  \
862                     fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
863
864                 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
865                 switch( p_0xa9xxx->i_type )
866                 {
867                 case FOURCC_0xa9nam: /* Full name */
868                     SET( vlc_meta_SetTitle );
869                     break;
870                 case FOURCC_0xa9aut:
871                     SET( vlc_meta_SetArtist );
872                     break;
873                 case FOURCC_0xa9ART:
874                     SET( vlc_meta_SetArtist );
875                     break;
876                 case FOURCC_0xa9cpy:
877                     SET( vlc_meta_SetCopyright );
878                     break;
879                 case FOURCC_0xa9day: /* Creation Date */
880                     SET( vlc_meta_SetDate );
881                     break;
882                 case FOURCC_0xa9des: /* Description */
883                     SET( vlc_meta_SetDescription );
884                     break;
885                 case FOURCC_0xa9gen: /* Genre */
886                     SET( vlc_meta_SetGenre );
887                     break;
888
889                 case FOURCC_0xa9alb: /* Album */
890                     SET( vlc_meta_SetAlbum );
891                     break;
892
893                 case FOURCC_0xa9swr:
894                 case FOURCC_0xa9inf: /* Information */
895                 case FOURCC_0xa9dir: /* Director */
896                 case FOURCC_0xa9dis: /* Disclaimer */
897                 case FOURCC_0xa9enc: /* Encoded By */
898                 case FOURCC_0xa9trk: /* Track */
899                 case FOURCC_0xa9cmt: /* Commment */
900                 case FOURCC_0xa9url: /* URL */
901                 case FOURCC_0xa9req: /* Requirements */
902                 case FOURCC_0xa9fmt: /* Original Format */
903                 case FOURCC_0xa9dsa: /* Display Source As */
904                 case FOURCC_0xa9hst: /* Host Computer */
905                 case FOURCC_0xa9prd: /* Producer */
906                 case FOURCC_0xa9prf: /* Performers */
907                 case FOURCC_0xa9ope: /* Original Performer */
908                 case FOURCC_0xa9src: /* Providers Source Content */
909                 case FOURCC_0xa9wrt: /* Writer */
910                 case FOURCC_0xa9com: /* Composer */
911                 case FOURCC_WLOC:    /* Window Location */
912                     /* TODO one day, but they aren't really meaningfull */
913                     break;
914 #undef SET
915
916                 default:
917                     break;
918                 }
919             }
920             return VLC_SUCCESS;
921         }
922
923         case DEMUX_GET_TITLE_INFO:
924         {
925             input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
926             int *pi_int    = (int*)va_arg( args, int* );
927             int *pi_title_offset = (int*)va_arg( args, int* );
928             int *pi_seekpoint_offset = (int*)va_arg( args, int* );
929
930             if( !p_sys->p_title )
931                 return VLC_EGENERIC;
932
933             *pi_int = 1;
934             *ppp_title = malloc( sizeof( input_title_t**) );
935             (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
936             *pi_title_offset = 0;
937             *pi_seekpoint_offset = 0;
938             return VLC_SUCCESS;
939         }
940         case DEMUX_SET_TITLE:
941         {
942             const int i_title = (int)va_arg( args, int );
943             if( !p_sys->p_title || i_title != 0 )
944                 return VLC_EGENERIC;
945             return VLC_SUCCESS;
946         }
947         case DEMUX_SET_SEEKPOINT:
948         {
949             const int i_seekpoint = (int)va_arg( args, int );
950             if( !p_sys->p_title )
951                 return VLC_EGENERIC;
952             return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
953         }
954
955         case DEMUX_SET_NEXT_DEMUX_TIME:
956         case DEMUX_SET_GROUP:
957             return VLC_EGENERIC;
958
959         default:
960             msg_Warn( p_demux, "control query %u unimplemented", i_query );
961             return VLC_EGENERIC;
962     }
963 }
964
965 /*****************************************************************************
966  * Close: frees unused data
967  *****************************************************************************/
968 static void Close ( vlc_object_t * p_this )
969 {
970     demux_t *  p_demux = (demux_t *)p_this;
971     demux_sys_t *p_sys = p_demux->p_sys;
972     unsigned int i_track;
973
974     msg_Dbg( p_demux, "freeing all memory" );
975
976     MP4_BoxFree( p_demux->s, p_sys->p_root );
977     for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
978     {
979         MP4_TrackDestroy( p_demux, &p_sys->track[i_track] );
980     }
981     FREENULL( p_sys->track );
982
983     if( p_sys->p_title )
984         vlc_input_title_Delete( p_sys->p_title );
985
986     free( p_sys );
987 }
988
989
990
991 /****************************************************************************
992  * Local functions, specific to vlc
993  ****************************************************************************/
994 /* Chapters */
995 static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
996 {
997     demux_sys_t *p_sys = p_demux->p_sys;
998     int i;
999
1000     p_sys->p_title = vlc_input_title_New();
1001     for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1002     {
1003         seekpoint_t *s = vlc_seekpoint_New();
1004
1005         s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1006         EnsureUTF8( s->psz_name );
1007         s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1008         TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1009     }
1010 }
1011 static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
1012 {
1013     demux_sys_t *p_sys = p_demux->p_sys;
1014
1015     for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1016     {
1017         const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1018         const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1019         const unsigned int i_size = MP4_TrackSampleSize( tk );
1020
1021         if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1022         {
1023             char p_buffer[256];
1024             const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1025             const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1026
1027             if( i_len > 0 )
1028             {
1029                 seekpoint_t *s = vlc_seekpoint_New();
1030
1031                 s->psz_name = strndup( &p_buffer[2], i_len );
1032                 EnsureUTF8( s->psz_name );
1033
1034                 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1035
1036                 if( !p_sys->p_title )
1037                     p_sys->p_title = vlc_input_title_New();
1038                 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1039             }
1040         }
1041         if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1042                               tk->chunk[tk->i_chunk].i_sample_count )
1043             tk->i_chunk++;
1044     }
1045 }
1046 static void LoadChapter( demux_t  *p_demux )
1047 {
1048     demux_sys_t *p_sys = p_demux->p_sys;
1049     MP4_Box_t *p_chpl;
1050
1051     if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1052     {
1053         LoadChapterGpac( p_demux, p_chpl );
1054     }
1055     else if( p_sys->p_tref_chap )
1056     {
1057         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1058         unsigned int i, j;
1059
1060         /* Load the first subtitle track like quicktime */
1061         for( i = 0; i < p_chap->i_entry_count; i++ )
1062         {
1063             for( j = 0; j < p_sys->i_tracks; j++ )
1064             {
1065                 mp4_track_t *tk = &p_sys->track[j];
1066                 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1067                     tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_FOURCC( 's', 'u', 'b', 't' ) )
1068                     break;
1069             }
1070             if( j < p_sys->i_tracks )
1071             {
1072                 LoadChapterApple( p_demux, &p_sys->track[i] );
1073                 break;
1074             }
1075         }
1076     }
1077 }
1078
1079 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1080 static int TrackCreateChunksIndex( demux_t *p_demux,
1081                                    mp4_track_t *p_demux_track )
1082 {
1083     MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1084     MP4_Box_t *p_stsc;
1085
1086     unsigned int i_chunk;
1087     unsigned int i_index, i_last;
1088
1089     if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1090           !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1091         ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1092     {
1093         return( VLC_EGENERIC );
1094     }
1095
1096     p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1097     if( !p_demux_track->i_chunk_count )
1098     {
1099         msg_Warn( p_demux, "no chunk defined" );
1100         return( VLC_EGENERIC );
1101     }
1102     p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1103                                    sizeof( mp4_chunk_t ) );
1104
1105     /* first we read chunk offset */
1106     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1107     {
1108         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1109
1110         ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1111
1112         ck->i_first_dts = 0;
1113         ck->p_sample_count_dts = NULL;
1114         ck->p_sample_delta_dts = NULL;
1115         ck->p_sample_count_pts = NULL;
1116         ck->p_sample_offset_pts = NULL;
1117     }
1118
1119     /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1120         to be used for the sample XXX begin to 1
1121         We construct it begining at the end */
1122     i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1123     i_index = p_stsc->data.p_stsc->i_entry_count;
1124     if( !i_index )
1125     {
1126         msg_Warn( p_demux, "cannot read chunk table or table empty" );
1127         return( VLC_EGENERIC );
1128     }
1129
1130     while( i_index-- )
1131     {
1132         for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1133              i_chunk < i_last; i_chunk++ )
1134         {
1135             p_demux_track->chunk[i_chunk].i_sample_description_index =
1136                     p_stsc->data.p_stsc->i_sample_description_index[i_index];
1137             p_demux_track->chunk[i_chunk].i_sample_count =
1138                     p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1139         }
1140         i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1141     }
1142
1143     p_demux_track->chunk[0].i_sample_first = 0;
1144     for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1145     {
1146         p_demux_track->chunk[i_chunk].i_sample_first =
1147             p_demux_track->chunk[i_chunk-1].i_sample_first +
1148                 p_demux_track->chunk[i_chunk-1].i_sample_count;
1149     }
1150
1151     msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1152              p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1153
1154     return VLC_SUCCESS;
1155 }
1156
1157 static int TrackCreateSamplesIndex( demux_t *p_demux,
1158                                     mp4_track_t *p_demux_track )
1159 {
1160     MP4_Box_t *p_box;
1161     MP4_Box_data_stsz_t *stsz;
1162     MP4_Box_data_stts_t *stts;
1163     /* TODO use also stss and stsh table for seeking */
1164     /* FIXME use edit table */
1165     int64_t i_sample;
1166     int64_t i_chunk;
1167
1168     int64_t i_index;
1169     int64_t i_index_sample_used;
1170
1171     int64_t i_last_dts;
1172
1173     /* Find stsz
1174      *  Gives the sample size for each samples. There is also a stz2 table
1175      *  (compressed form) that we need to implement TODO */
1176     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1177     if( !p_box )
1178     {
1179         /* FIXME and stz2 */
1180         msg_Warn( p_demux, "cannot find STSZ box" );
1181         return VLC_EGENERIC;
1182     }
1183     stsz = p_box->data.p_stsz;
1184
1185     /* Find stts
1186      *  Gives mapping between sample and decoding time
1187      */
1188     p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1189     if( !p_box )
1190     {
1191         msg_Warn( p_demux, "cannot find STTS box" );
1192         return VLC_EGENERIC;
1193     }
1194     stts = p_box->data.p_stts;
1195
1196     /* Use stsz table to create a sample number -> sample size table */
1197     p_demux_track->i_sample_count = stsz->i_sample_count;
1198     if( stsz->i_sample_size )
1199     {
1200         /* 1: all sample have the same size, so no need to construct a table */
1201         p_demux_track->i_sample_size = stsz->i_sample_size;
1202         p_demux_track->p_sample_size = NULL;
1203     }
1204     else
1205     {
1206         /* 2: each sample can have a different size */
1207         p_demux_track->i_sample_size = 0;
1208         p_demux_track->p_sample_size =
1209             calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1210
1211         for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1212         {
1213             p_demux_track->p_sample_size[i_sample] =
1214                     stsz->i_entry_size[i_sample];
1215         }
1216     }
1217
1218     /* Use stts table to create a sample number -> dts table.
1219      * XXX: if we don't want to waste too much memory, we can't expand
1220      *  the box! so each chunk will contain an "extract" of this table
1221      *  for fast research (problem with raw stream where a sample is sometime
1222      *  just channels*bits_per_sample/8 */
1223
1224     i_last_dts = 0;
1225     i_index = 0; i_index_sample_used = 0;
1226     for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1227     {
1228         mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1229         int64_t i_entry, i_sample_count, i;
1230
1231         /* save last dts */
1232         ck->i_first_dts = i_last_dts;
1233
1234         /* count how many entries are needed for this chunk
1235          * for p_sample_delta_dts and p_sample_count_dts */
1236         i_sample_count = ck->i_sample_count;
1237
1238         i_entry = 0;
1239         while( i_sample_count > 0 )
1240         {
1241             i_sample_count -= stts->i_sample_count[i_index+i_entry];
1242             /* don't count already used sample in this entry */
1243             if( i_entry == 0 )
1244                 i_sample_count += i_index_sample_used;
1245
1246             i_entry++;
1247         }
1248
1249         /* allocate them */
1250         ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1251         ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1252
1253         /* now copy */
1254         i_sample_count = ck->i_sample_count;
1255         for( i = 0; i < i_entry; i++ )
1256         {
1257             int64_t i_used;
1258             int64_t i_rest;
1259
1260             i_rest = stts->i_sample_count[i_index] - i_index_sample_used;
1261
1262             i_used = __MIN( i_rest, i_sample_count );
1263
1264             i_index_sample_used += i_used;
1265             i_sample_count -= i_used;
1266
1267             ck->p_sample_count_dts[i] = i_used;
1268             ck->p_sample_delta_dts[i] = stts->i_sample_delta[i_index];
1269
1270             i_last_dts += i_used * ck->p_sample_delta_dts[i];
1271
1272             if( i_index_sample_used >= stts->i_sample_count[i_index] )
1273             {
1274                 i_index++;
1275                 i_index_sample_used = 0;
1276             }
1277         }
1278     }
1279
1280     /* Find ctts
1281      *  Gives the delta between decoding time (dts) and composition table (pts)
1282      */
1283     p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1284     if( p_box )
1285     {
1286         MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1287
1288         msg_Warn( p_demux, "CTTS table" );
1289
1290         /* Create pts-dts table per chunk */
1291         i_index = 0; i_index_sample_used = 0;
1292         for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1293         {
1294             mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1295             int64_t i_entry, i_sample_count, i;
1296
1297             /* count how many entries are needed for this chunk
1298              * for p_sample_delta_dts and p_sample_count_dts */
1299             i_sample_count = ck->i_sample_count;
1300
1301             i_entry = 0;
1302             while( i_sample_count > 0 )
1303             {
1304                 i_sample_count -= ctts->i_sample_count[i_index+i_entry];
1305
1306                 /* don't count already used sample in this entry */
1307                 if( i_entry == 0 )
1308                     i_sample_count += i_index_sample_used;
1309
1310                 i_entry++;
1311             }
1312
1313             /* allocate them */
1314             ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1315             ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1316
1317             /* now copy */
1318             i_sample_count = ck->i_sample_count;
1319             for( i = 0; i < i_entry; i++ )
1320             {
1321                 int64_t i_used;
1322                 int64_t i_rest;
1323
1324                 i_rest = ctts->i_sample_count[i_index] -
1325                     i_index_sample_used;
1326
1327                 i_used = __MIN( i_rest, i_sample_count );
1328
1329                 i_index_sample_used += i_used;
1330                 i_sample_count -= i_used;
1331
1332                 ck->p_sample_count_pts[i] = i_used;
1333                 ck->p_sample_offset_pts[i] = ctts->i_sample_offset[i_index];
1334
1335                 if( i_index_sample_used >= ctts->i_sample_count[i_index] )
1336                 {
1337                     i_index++;
1338                     i_index_sample_used = 0;
1339                 }
1340             }
1341         }
1342     }
1343
1344     msg_Dbg( p_demux, "track[Id 0x%x] read %d samples length:"I64Fd"s",
1345              p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1346              i_last_dts / p_demux_track->i_timescale );
1347
1348     return VLC_SUCCESS;
1349 }
1350
1351 /*
1352  * TrackCreateES:
1353  * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1354  */
1355 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1356                           unsigned int i_chunk, es_out_id_t **pp_es )
1357 {
1358     MP4_Box_t   *p_sample;
1359     MP4_Box_t   *p_esds;
1360     MP4_Box_t   *p_box;
1361
1362     if( pp_es )
1363         *pp_es = NULL;
1364
1365     if( !p_track->chunk[i_chunk].i_sample_description_index )
1366     {
1367         msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1368                   p_track->i_track_ID );
1369         return VLC_EGENERIC;
1370     }
1371
1372     p_sample = MP4_BoxGet(  p_track->p_stsd, "[%d]",
1373                 p_track->chunk[i_chunk].i_sample_description_index - 1 );
1374
1375     if( !p_sample ||
1376         ( !p_sample->data.p_data && p_track->fmt.i_cat != SPU_ES ) )
1377     {
1378         msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1379                   p_track->i_track_ID );
1380         return VLC_EGENERIC;
1381     }
1382
1383     p_track->p_sample = p_sample;
1384
1385     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size == 1 )
1386     {
1387         MP4_Box_data_sample_soun_t *p_soun;
1388
1389         p_soun = p_sample->data.p_sample_soun;
1390
1391         if( p_soun->i_qt_version == 0 )
1392         {
1393             switch( p_sample->i_type )
1394             {
1395                 case VLC_FOURCC( 'i', 'm', 'a', '4' ):
1396                     p_soun->i_qt_version = 1;
1397                     p_soun->i_sample_per_packet = 64;
1398                     p_soun->i_bytes_per_packet  = 34;
1399                     p_soun->i_bytes_per_frame   = 34 * p_soun->i_channelcount;
1400                     p_soun->i_bytes_per_sample  = 2;
1401                     break;
1402                 case VLC_FOURCC( 'M', 'A', 'C', '3' ):
1403                     p_soun->i_qt_version = 1;
1404                     p_soun->i_sample_per_packet = 6;
1405                     p_soun->i_bytes_per_packet  = 2;
1406                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1407                     p_soun->i_bytes_per_sample  = 2;
1408                     break;
1409                 case VLC_FOURCC( 'M', 'A', 'C', '6' ):
1410                     p_soun->i_qt_version = 1;
1411                     p_soun->i_sample_per_packet = 12;
1412                     p_soun->i_bytes_per_packet  = 2;
1413                     p_soun->i_bytes_per_frame   = 2 * p_soun->i_channelcount;
1414                     p_soun->i_bytes_per_sample  = 2;
1415                     break;
1416                 case VLC_FOURCC( 'a', 'l', 'a', 'w' ):
1417                 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1418                     p_soun->i_samplesize = 8;
1419                     break;
1420                 default:
1421                     break;
1422             }
1423
1424         }
1425         else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1426         {
1427             p_soun->i_qt_version = 0;
1428         }
1429     }
1430
1431
1432     /* It's a little ugly but .. there are special cases */
1433     switch( p_sample->i_type )
1434     {
1435         case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1436         case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1437             p_track->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1438             break;
1439
1440         case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
1441             p_track->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1442
1443             /* Buggy files workaround */
1444             if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
1445                 p_sample->data.p_sample_soun->i_sampleratehi) )
1446             {
1447                 MP4_Box_data_sample_soun_t *p_soun =
1448                     p_sample->data.p_sample_soun;
1449
1450                 msg_Warn( p_demux, "i_timescale ("I64Fu") != i_sampleratehi "
1451                           "(%u), making both equal (report any problem).",
1452                           p_track->i_timescale, p_soun->i_sampleratehi );
1453
1454                 if( p_soun->i_sampleratehi )
1455                     p_track->i_timescale = p_soun->i_sampleratehi;
1456                 else
1457                     p_soun->i_sampleratehi = p_track->i_timescale;
1458             }
1459             break;
1460
1461         case( VLC_FOURCC( 's', '2', '6', '3' ) ):
1462             p_track->fmt.i_codec = VLC_FOURCC( 'h', '2', '6', '3' );
1463             break;
1464
1465         case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
1466         case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
1467             p_track->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1468             /* FIXME: Not true, could be UTF-16 with a Byte Order Mark (0xfeff) */
1469             /* FIXME UTF-8 doesn't work here ? */
1470             p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
1471             break;
1472
1473         case VLC_FOURCC('y','v','1','2'):
1474             p_track->fmt.i_codec = VLC_FOURCC('Y','V','1','2');
1475             break;
1476         case VLC_FOURCC('y','u','v','2'):
1477             p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
1478             break;
1479
1480         case VLC_FOURCC('i','n','2','4'):
1481             /* in in24/in32 there's enda-atom to tell it's little-endian (if present) */
1482             if( ( MP4_BoxGet( p_sample, "wave/enda" ) ) ||
1483                 ( MP4_BoxGet( p_sample, "enda" ) ) )
1484             {
1485                 p_track->fmt.i_codec = VLC_FOURCC('4','2','n','i');
1486             } else {
1487                 p_track->fmt.i_codec = p_sample->i_type;
1488             }
1489             break;
1490
1491         default:
1492             p_track->fmt.i_codec = p_sample->i_type;
1493             break;
1494     }
1495
1496     /* now see if esds is present and if so create a data packet
1497         with decoder_specific_info  */
1498 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
1499     if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
1500           ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
1501         ( p_esds->data.p_esds )&&
1502         ( p_decconfig ) )
1503     {
1504         /* First update information based on i_objectTypeIndication */
1505         switch( p_decconfig->i_objectTypeIndication )
1506         {
1507             case( 0x20 ): /* MPEG4 VIDEO */
1508                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','v' );
1509                 break;
1510             case( 0x40):
1511                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1512                 break;
1513             case( 0x60):
1514             case( 0x61):
1515             case( 0x62):
1516             case( 0x63):
1517             case( 0x64):
1518             case( 0x65): /* MPEG2 video */
1519                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1520                 break;
1521             /* Theses are MPEG2-AAC */
1522             case( 0x66): /* main profile */
1523             case( 0x67): /* Low complexity profile */
1524             case( 0x68): /* Scaleable Sampling rate profile */
1525                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','4','a' );
1526                 break;
1527             /* true MPEG 2 audio */
1528             case( 0x69):
1529                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1530                 break;
1531             case( 0x6a): /* MPEG1 video */
1532                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','v' );
1533                 break;
1534             case( 0x6b): /* MPEG1 audio */
1535                 p_track->fmt.i_codec = VLC_FOURCC( 'm','p','g','a' );
1536                 break;
1537             case( 0x6c ): /* jpeg */
1538                 p_track->fmt.i_codec = VLC_FOURCC( 'j','p','e','g' );
1539                 break;
1540
1541             /* Private ID */
1542             case( 0xe0 ): /* NeroDigital: dvd subs */
1543                 if( p_track->fmt.i_cat == SPU_ES )
1544                 {
1545                     p_track->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1546                     if( p_track->i_width > 0 )
1547                         p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
1548                     if( p_track->i_height > 0 )
1549                         p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
1550                     break;
1551                 }
1552             /* Fallback */
1553             default:
1554                 /* Unknown entry, but don't touch i_fourcc */
1555                 msg_Warn( p_demux,
1556                           "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
1557                           p_decconfig->i_objectTypeIndication,
1558                           p_track->i_track_ID );
1559                 break;
1560         }
1561         p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
1562         if( p_track->fmt.i_extra > 0 )
1563         {
1564             p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1565             memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
1566                     p_track->fmt.i_extra );
1567         }
1568     }
1569     else
1570     {
1571         switch( p_sample->i_type )
1572         {
1573             /* qt decoder, send the complete chunk */
1574             case VLC_FOURCC( 'S', 'V', 'Q', '3' ):
1575             case VLC_FOURCC( 'S', 'V', 'Q', '1' ):
1576             case VLC_FOURCC( 'V', 'P', '3', '1' ):
1577             case VLC_FOURCC( '3', 'I', 'V', '1' ):
1578             case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
1579                 p_track->fmt.i_extra =
1580                     p_sample->data.p_sample_vide->i_qt_image_description;
1581                 if( p_track->fmt.i_extra > 0 )
1582                 {
1583                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1584                     memcpy( p_track->fmt.p_extra,
1585                             p_sample->data.p_sample_vide->p_qt_image_description,
1586                             p_track->fmt.i_extra);
1587                 }
1588                 break;
1589             case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
1590             case VLC_FOURCC( 'Q', 'D', 'M', '2' ):
1591             case VLC_FOURCC( 'Q', 'c', 'l', 'p' ):
1592             case VLC_FOURCC( 's', 'a', 'm', 'r' ):
1593             case VLC_FOURCC( 'a', 'l', 'a', 'c' ):
1594                 p_track->fmt.i_extra =
1595                     p_sample->data.p_sample_soun->i_qt_description;
1596                 if( p_track->fmt.i_extra > 0 )
1597                 {
1598                     p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
1599                     memcpy( p_track->fmt.p_extra,
1600                             p_sample->data.p_sample_soun->p_qt_description,
1601                             p_track->fmt.i_extra);
1602                 }
1603                 break;
1604
1605             /* avc1: send avcC (h264 without annexe B, ie without start code)*/
1606             case VLC_FOURCC( 'a', 'v', 'c', '1' ):
1607             {
1608                 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
1609
1610                 if( p_avcC )
1611                 {
1612                     p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
1613                     p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
1614                     memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
1615                             p_track->fmt.i_extra );
1616                 }
1617                 else
1618                 {
1619                     msg_Err( p_demux, "missing avcC" );
1620                 }
1621                 break;
1622             }
1623
1624             default:
1625                 break;
1626         }
1627     }
1628
1629 #undef p_decconfig
1630
1631     /* some last initialisation */
1632     switch( p_track->fmt.i_cat )
1633     {
1634     case( VIDEO_ES ):
1635         p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1636         p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1637         p_track->fmt.video.i_bits_per_pixel =
1638             p_sample->data.p_sample_vide->i_depth;
1639
1640         /* fall on display size */
1641         if( p_track->fmt.video.i_width <= 0 )
1642             p_track->fmt.video.i_width = p_track->i_width;
1643         if( p_track->fmt.video.i_height <= 0 )
1644             p_track->fmt.video.i_height = p_track->i_height;
1645
1646         /* Find out apect ratio from display size */
1647         if( p_track->i_width > 0 && p_track->i_height > 0 &&
1648             /* Work-around buggy muxed files */
1649             p_sample->data.p_sample_vide->i_width != p_track->i_width )
1650             p_track->fmt.video.i_aspect =
1651                 VOUT_ASPECT_FACTOR * p_track->i_width / p_track->i_height;
1652
1653         /* Support for cropping (eg. in H263 files) */
1654         p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1655         p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1656
1657         /* Frame rate */
1658         p_track->fmt.video.i_frame_rate = p_track->i_timescale;
1659         p_track->fmt.video.i_frame_rate_base = 1;
1660
1661         if( p_track->fmt.video.i_frame_rate &&
1662             (p_box = MP4_BoxGet( p_track->p_stbl, "stts" )) &&
1663             p_box->data.p_stts->i_entry_count >= 1 )
1664         {
1665             p_track->fmt.video.i_frame_rate_base =
1666                 p_box->data.p_stts->i_sample_delta[0];
1667         }
1668
1669         break;
1670
1671     case( AUDIO_ES ):
1672         p_track->fmt.audio.i_channels =
1673             p_sample->data.p_sample_soun->i_channelcount;
1674         p_track->fmt.audio.i_rate =
1675             p_sample->data.p_sample_soun->i_sampleratehi;
1676         p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1677             p_sample->data.p_sample_soun->i_sampleratehi *
1678                 p_sample->data.p_sample_soun->i_samplesize;
1679         p_track->fmt.audio.i_bitspersample =
1680             p_sample->data.p_sample_soun->i_samplesize;
1681         break;
1682
1683     default:
1684         break;
1685     }
1686
1687     if( pp_es )
1688         *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
1689
1690     return VLC_SUCCESS;
1691 }
1692
1693 /* given a time it return sample/chunk
1694  * it also update elst field of the track
1695  */
1696 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
1697                                    int64_t i_start, uint32_t *pi_chunk,
1698                                    uint32_t *pi_sample )
1699 {
1700     demux_sys_t *p_sys = p_demux->p_sys;
1701     MP4_Box_t   *p_stss;
1702     uint64_t     i_dts;
1703     unsigned int i_sample;
1704     unsigned int i_chunk;
1705     int          i_index;
1706
1707     /* FIXME see if it's needed to check p_track->i_chunk_count */
1708     if( p_track->i_chunk_count == 0 )
1709         return( VLC_EGENERIC );
1710
1711     /* handle elst (find the correct one) */
1712     MP4_TrackSetELST( p_demux, p_track, i_start );
1713     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
1714     {
1715         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
1716         int64_t i_mvt= i_start * p_sys->i_timescale / (int64_t)1000000;
1717
1718         /* now calculate i_start for this elst */
1719         /* offset */
1720         i_start -= p_track->i_elst_time * I64C(1000000) / p_sys->i_timescale;
1721         if( i_start < 0 )
1722         {
1723             *pi_chunk = 0;
1724             *pi_sample= 0;
1725
1726             return VLC_SUCCESS;
1727         }
1728         /* to track time scale */
1729         i_start  = i_start * p_track->i_timescale / (int64_t)1000000;
1730         /* add elst offset */
1731         if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
1732              elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
1733             elst->i_media_time[p_track->i_elst] > 0 )
1734         {
1735             i_start += elst->i_media_time[p_track->i_elst];
1736         }
1737
1738         msg_Dbg( p_demux, "elst (%d) gives "I64Fd"ms (movie)-> "I64Fd
1739                  "ms (track)", p_track->i_elst,
1740                  i_mvt * 1000 / p_sys->i_timescale,
1741                  i_start * 1000 / p_track->i_timescale );
1742     }
1743     else
1744     {
1745         /* convert absolute time to in timescale unit */
1746         i_start = i_start * p_track->i_timescale / (int64_t)1000000;
1747     }
1748
1749     /* we start from sample 0/chunk 0, hope it won't take too much time */
1750     /* *** find good chunk *** */
1751     for( i_chunk = 0; ; i_chunk++ )
1752     {
1753         if( i_chunk + 1 >= p_track->i_chunk_count )
1754         {
1755             /* at the end and can't check if i_start in this chunk,
1756                it will be check while searching i_sample */
1757             i_chunk = p_track->i_chunk_count - 1;
1758             break;
1759         }
1760
1761         if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
1762             (uint64_t)i_start <  p_track->chunk[i_chunk + 1].i_first_dts )
1763         {
1764             break;
1765         }
1766     }
1767
1768     /* *** find sample in the chunk *** */
1769     i_sample = p_track->chunk[i_chunk].i_sample_first;
1770     i_dts    = p_track->chunk[i_chunk].i_first_dts;
1771     for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
1772     {
1773         if( i_dts +
1774             p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1775             p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
1776         {
1777             i_dts    +=
1778                 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
1779                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1780
1781             i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
1782             i_index++;
1783         }
1784         else
1785         {
1786             if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
1787             {
1788                 break;
1789             }
1790             i_sample += ( i_start - i_dts ) /
1791                 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
1792             break;
1793         }
1794     }
1795
1796     if( i_sample >= p_track->i_sample_count )
1797     {
1798         msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
1799                   "(seeking too far) chunk=%d sample=%d",
1800                   p_track->i_track_ID, i_chunk, i_sample );
1801         return( VLC_EGENERIC );
1802     }
1803
1804
1805     /* *** Try to find nearest sync points *** */
1806     if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
1807     {
1808         unsigned int i_index;
1809         msg_Dbg( p_demux,
1810                     "track[Id 0x%x] using Sync Sample Box (stss)",
1811                     p_track->i_track_ID );
1812         for( i_index = 0; i_index < p_stss->data.p_stss->i_entry_count; i_index++ )
1813         {
1814             if( p_stss->data.p_stss->i_sample_number[i_index] >= i_sample )
1815             {
1816                 if( i_index > 0 )
1817                 {
1818                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1819                             i_sample,
1820                             p_stss->data.p_stss->i_sample_number[i_index-1] );
1821                     i_sample = p_stss->data.p_stss->i_sample_number[i_index-1];
1822                     /* new i_sample is less than old so i_chunk can only decreased */
1823                     while( i_chunk > 0 &&
1824                             i_sample < p_track->chunk[i_chunk].i_sample_first )
1825                     {
1826                         i_chunk--;
1827                     }
1828                 }
1829                 else
1830                 {
1831                     msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
1832                             i_sample,
1833                             p_stss->data.p_stss->i_sample_number[i_index] );
1834                     i_sample = p_stss->data.p_stss->i_sample_number[i_index];
1835                     /* new i_sample is more than old so i_chunk can only increased */
1836                     while( i_chunk < p_track->i_chunk_count - 1 &&
1837                            i_sample >= p_track->chunk[i_chunk].i_sample_first +
1838                              p_track->chunk[i_chunk].i_sample_count )
1839                     {
1840                         i_chunk++;
1841                     }
1842                 }
1843                 break;
1844             }
1845         }
1846     }
1847     else
1848     {
1849         msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
1850                  "Sample Box (stss)", p_track->i_track_ID );
1851     }
1852
1853     *pi_chunk  = i_chunk;
1854     *pi_sample = i_sample;
1855
1856     return VLC_SUCCESS;
1857 }
1858
1859 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
1860                                  unsigned int i_chunk, unsigned int i_sample )
1861 {
1862     vlc_bool_t b_reselect = VLC_FALSE;
1863
1864     /* now see if actual es is ok */
1865     if( (p_track->i_chunk >= p_track->i_chunk_count - 1) ||
1866         (p_track->chunk[p_track->i_chunk].i_sample_description_index !=
1867             p_track->chunk[i_chunk].i_sample_description_index) )
1868     {
1869         msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
1870                   p_track->i_track_ID );
1871
1872         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
1873                         p_track->p_es, &b_reselect );
1874
1875         es_out_Del( p_demux->out, p_track->p_es );
1876
1877         p_track->p_es = NULL;
1878
1879         if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
1880         {
1881             msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
1882                      p_track->i_track_ID );
1883
1884             p_track->b_ok       = VLC_FALSE;
1885             p_track->b_selected = VLC_FALSE;
1886             return VLC_EGENERIC;
1887         }
1888     }
1889
1890     /* select again the new decoder */
1891     if( b_reselect )
1892     {
1893         es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
1894     }
1895
1896     p_track->i_chunk    = i_chunk;
1897     p_track->i_sample   = i_sample;
1898
1899     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
1900 }
1901
1902 /****************************************************************************
1903  * MP4_TrackCreate:
1904  ****************************************************************************
1905  * Parse track information and create all needed data to run a track
1906  * If it succeed b_ok is set to 1 else to 0
1907  ****************************************************************************/
1908 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
1909                              MP4_Box_t *p_box_trak )
1910 {
1911     demux_sys_t *p_sys = p_demux->p_sys;
1912
1913     MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
1914     MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
1915     MP4_Box_t *p_elst;
1916
1917     MP4_Box_t *p_mdhd;
1918     MP4_Box_t *p_udta;
1919     MP4_Box_t *p_hdlr;
1920
1921     MP4_Box_t *p_vmhd;
1922     MP4_Box_t *p_smhd;
1923
1924     MP4_Box_t *p_drms;
1925
1926     unsigned int i;
1927     char language[4];
1928
1929     /* hint track unsupported */
1930
1931     /* set default value (-> track unusable) */
1932     p_track->b_ok       = VLC_FALSE;
1933     p_track->b_enable   = VLC_FALSE;
1934     p_track->b_selected = VLC_FALSE;
1935     p_track->b_chapter  = VLC_FALSE;
1936
1937     es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
1938
1939     if( !p_tkhd )
1940     {
1941         return;
1942     }
1943
1944     /* do we launch this track by default ? */
1945     p_track->b_enable =
1946         ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
1947
1948     p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
1949     p_track->i_width = p_tkhd->data.p_tkhd->i_width / 65536;
1950     p_track->i_height = p_tkhd->data.p_tkhd->i_height / 65536;
1951
1952     if( p_tref )
1953     {
1954 /*        msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
1955     }
1956
1957     p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
1958     p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
1959
1960     if( ( !p_mdhd )||( !p_hdlr ) )
1961     {
1962         return;
1963     }
1964
1965     p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
1966
1967     for( i = 0; i < 3; i++ )
1968     {
1969         language[i] = p_mdhd->data.p_mdhd->i_language[i];
1970     }
1971     language[3] = '\0';
1972
1973     switch( p_hdlr->data.p_hdlr->i_handler_type )
1974     {
1975         case( FOURCC_soun ):
1976             if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
1977             {
1978                 return;
1979             }
1980             p_track->fmt.i_cat = AUDIO_ES;
1981             break;
1982
1983         case( FOURCC_vide ):
1984             if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
1985             {
1986                 return;
1987             }
1988             p_track->fmt.i_cat = VIDEO_ES;
1989             break;
1990
1991         case( FOURCC_text ):
1992         case( FOURCC_subp ):
1993         case( FOURCC_tx3g ):
1994             p_track->fmt.i_cat = SPU_ES;
1995             break;
1996
1997         default:
1998             return;
1999     }
2000
2001     p_track->i_elst = 0;
2002     p_track->i_elst_time = 0;
2003     if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2004     {
2005         MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2006         unsigned int i;
2007
2008         msg_Warn( p_demux, "elst box found" );
2009         for( i = 0; i < elst->i_entry_count; i++ )
2010         {
2011             msg_Dbg( p_demux, "   - [%d] duration="I64Fd"ms media time="I64Fd
2012                      "ms) rate=%d.%d", i,
2013                      elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2014                      elst->i_media_time[i] >= 0 ?
2015                      (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2016                      I64C(-1),
2017                      elst->i_media_rate_integer[i],
2018                      elst->i_media_rate_fraction[i] );
2019         }
2020     }
2021
2022
2023 /*  TODO
2024     add support for:
2025     p_dinf = MP4_BoxGet( p_minf, "dinf" );
2026 */
2027     if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2028         !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2029     {
2030         return;
2031     }
2032
2033     p_drms = MP4_BoxGet( p_track->p_stsd, "drms" );
2034     p_track->b_drms = p_drms != NULL;
2035     p_track->p_drms = p_track->b_drms ?
2036         p_drms->data.p_sample_soun->p_drms : NULL;
2037
2038     /* Set language */
2039     if( strcmp( language, "```" ) && strcmp( language, "und" ) )
2040     {
2041         p_track->fmt.psz_language = strdup( language );
2042     }
2043
2044     p_udta = MP4_BoxGet( p_box_trak, "udta" );
2045     if( p_udta )
2046     {
2047         MP4_Box_t *p_0xa9xxx;
2048         for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
2049                  p_0xa9xxx = p_0xa9xxx->p_next )
2050         {
2051             switch( p_0xa9xxx->i_type )
2052             {
2053                 case FOURCC_0xa9nam:
2054                     p_track->fmt.psz_description =
2055                         strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text );
2056                     break;
2057             }
2058         }
2059     }
2060
2061     /* Create chunk index table and sample index table */
2062     if( TrackCreateChunksIndex( p_demux,p_track  ) ||
2063         TrackCreateSamplesIndex( p_demux, p_track ) )
2064     {
2065         return; /* cannot create chunks index */
2066     }
2067
2068     p_track->i_chunk  = 0;
2069     p_track->i_sample = 0;
2070
2071     /* Mark chapter only track */
2072     if( !p_track->b_enable && p_sys->p_tref_chap )
2073     {
2074         MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2075         unsigned int i;
2076
2077         for( i = 0; i < p_chap->i_entry_count; i++ )
2078         {
2079             if( p_track->i_track_ID == p_chap->i_track_ID[i] )
2080             {
2081                 p_track->b_chapter = VLC_TRUE;
2082                 break;
2083             }
2084         }
2085     }
2086
2087     /* now create es */
2088     p_track->p_es = NULL;
2089     if( TrackCreateES( p_demux,
2090                        p_track, p_track->i_chunk,
2091                        p_track->b_chapter ? NULL : &p_track->p_es ) )
2092     {
2093         msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2094                  p_track->i_track_ID );
2095         return;
2096     }
2097     p_track->b_ok = VLC_TRUE;
2098 #if 0
2099     {
2100         int i;
2101         for( i = 0; i < p_track->i_chunk_count; i++ )
2102         {
2103             fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2104                      i, p_track->chunk[i].i_sample_count,
2105                      p_track->chunk[i].i_first_dts );
2106
2107         }
2108     }
2109 #endif
2110 }
2111
2112 /****************************************************************************
2113  * MP4_TrackDestroy:
2114  ****************************************************************************
2115  * Destroy a track created by MP4_TrackCreate.
2116  ****************************************************************************/
2117 static void MP4_TrackDestroy( demux_t *p_demux, mp4_track_t *p_track )
2118 {
2119     unsigned int i_chunk;
2120
2121     p_track->b_ok = VLC_FALSE;
2122     p_track->b_enable   = VLC_FALSE;
2123     p_track->b_selected = VLC_FALSE;
2124
2125     es_format_Clean( &p_track->fmt );
2126
2127     for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2128     {
2129         if( p_track->chunk )
2130         {
2131            FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2132            FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2133
2134            FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2135            FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2136         }
2137     }
2138     FREENULL( p_track->chunk );
2139
2140     if( !p_track->i_sample_size )
2141     {
2142         FREENULL( p_track->p_sample_size );
2143     }
2144 }
2145
2146 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2147                             mtime_t i_start )
2148 {
2149     if( !p_track->b_ok || p_track->b_chapter )
2150     {
2151         return VLC_EGENERIC;
2152     }
2153
2154     if( p_track->b_selected )
2155     {
2156         msg_Warn( p_demux, "track[Id 0x%x] already selected",
2157                   p_track->i_track_ID );
2158         return VLC_SUCCESS;
2159     }
2160
2161     return MP4_TrackSeek( p_demux, p_track, i_start );
2162 }
2163
2164 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2165 {
2166     if( !p_track->b_ok || p_track->b_chapter )
2167     {
2168         return;
2169     }
2170
2171     if( !p_track->b_selected )
2172     {
2173         msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2174                   p_track->i_track_ID );
2175         return;
2176     }
2177     if( p_track->p_es )
2178     {
2179         es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2180                         p_track->p_es, VLC_FALSE );
2181     }
2182
2183     p_track->b_selected = VLC_FALSE;
2184 }
2185
2186 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2187                           mtime_t i_start )
2188 {
2189     uint32_t i_chunk;
2190     uint32_t i_sample;
2191
2192     if( !p_track->b_ok || p_track->b_chapter )
2193         return VLC_EGENERIC;
2194
2195     p_track->b_selected = VLC_FALSE;
2196
2197     if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2198                                 &i_chunk, &i_sample ) )
2199     {
2200         msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2201                   p_track->i_track_ID );
2202         return VLC_EGENERIC;
2203     }
2204
2205     p_track->b_selected = VLC_TRUE;
2206
2207     if( TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) ==
2208         VLC_SUCCESS )
2209     {
2210         p_track->b_selected = VLC_TRUE;
2211
2212         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
2213                         p_track->p_es, i_start );
2214     }
2215
2216     return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2217 }
2218
2219
2220 /*
2221  * 3 types: for audio
2222  * 
2223  */
2224 #define QT_V0_MAX_SAMPLES 1024
2225 static int MP4_TrackSampleSize( mp4_track_t *p_track )
2226 {
2227     int i_size;
2228     MP4_Box_data_sample_soun_t *p_soun;
2229
2230     if( p_track->i_sample_size == 0 )
2231     {
2232         /* most simple case */
2233         return p_track->p_sample_size[p_track->i_sample];
2234     }
2235     if( p_track->fmt.i_cat != AUDIO_ES )
2236     {
2237         return p_track->i_sample_size;
2238     }
2239
2240     p_soun = p_track->p_sample->data.p_sample_soun;
2241
2242     if( p_soun->i_qt_version == 1 )
2243     {
2244         i_size = p_track->chunk[p_track->i_chunk].i_sample_count /
2245             p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
2246     }
2247     else if( p_track->i_sample_size > 256 )
2248     {
2249         /* We do that so we don't read too much data
2250          * (in this case we are likely dealing with compressed data) */
2251         i_size = p_track->i_sample_size;
2252     }
2253     else
2254     {
2255         /* Read a bunch of samples at once */
2256         int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count -
2257             ( p_track->i_sample -
2258               p_track->chunk[p_track->i_chunk].i_sample_first );
2259
2260         i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
2261         i_size = i_samples * p_track->i_sample_size;
2262     }
2263
2264     //fprintf( stderr, "size=%d\n", i_size );
2265     return i_size;
2266 }
2267
2268 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
2269 {
2270     unsigned int i_sample;
2271     uint64_t i_pos;
2272
2273     i_pos = p_track->chunk[p_track->i_chunk].i_offset;
2274
2275     if( p_track->i_sample_size )
2276     {
2277         MP4_Box_data_sample_soun_t *p_soun =
2278             p_track->p_sample->data.p_sample_soun;
2279
2280         if( p_soun->i_qt_version == 0 )
2281         {
2282             i_pos += ( p_track->i_sample -
2283                        p_track->chunk[p_track->i_chunk].i_sample_first ) *
2284                      p_track->i_sample_size;
2285         }
2286         else
2287         {
2288             /* we read chunk by chunk */
2289             i_pos += 0;
2290         }
2291     }
2292     else
2293     {
2294         for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
2295              i_sample < p_track->i_sample; i_sample++ )
2296         {
2297             i_pos += p_track->p_sample_size[i_sample];
2298         }
2299     }
2300
2301     return i_pos;
2302 }
2303
2304 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track )
2305 {
2306     if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
2307     {
2308         MP4_Box_data_sample_soun_t *p_soun;
2309
2310         p_soun = p_track->p_sample->data.p_sample_soun;
2311
2312         if( p_soun->i_qt_version == 1 )
2313         {
2314             /* chunk by chunk */
2315             p_track->i_sample =
2316                 p_track->chunk[p_track->i_chunk].i_sample_first +
2317                 p_track->chunk[p_track->i_chunk].i_sample_count;
2318         }
2319         else if( p_track->i_sample_size > 256 )
2320         {
2321             /* We do that so we don't read too much data
2322              * (in this case we are likely dealing with compressed data) */
2323             p_track->i_sample += 1;
2324         }
2325         else
2326         {
2327             /* FIXME */
2328             p_track->i_sample += QT_V0_MAX_SAMPLES;
2329             if( p_track->i_sample >
2330                 p_track->chunk[p_track->i_chunk].i_sample_first +
2331                 p_track->chunk[p_track->i_chunk].i_sample_count )
2332             {
2333                 p_track->i_sample =
2334                     p_track->chunk[p_track->i_chunk].i_sample_first +
2335                     p_track->chunk[p_track->i_chunk].i_sample_count;
2336             }
2337         }
2338     }
2339     else
2340     {
2341         p_track->i_sample++;
2342     }
2343
2344     if( p_track->i_sample >= p_track->i_sample_count )
2345         return VLC_EGENERIC;
2346
2347     /* Have we changed chunk ? */
2348     if( p_track->i_sample >=
2349             p_track->chunk[p_track->i_chunk].i_sample_first +
2350             p_track->chunk[p_track->i_chunk].i_sample_count )
2351     {
2352         if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
2353                                   p_track->i_sample ) )
2354         {
2355             msg_Warn( p_demux, "track[0x%x] will be disabled "
2356                       "(cannot restart decoder)", p_track->i_track_ID );
2357             MP4_TrackUnselect( p_demux, p_track );
2358             return VLC_EGENERIC;
2359         }
2360     }
2361
2362     /* Have we changed elst */
2363     if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2364     {
2365         demux_sys_t *p_sys = p_demux->p_sys;
2366         MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2367         uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
2368                         p_sys->i_timescale / (int64_t)1000000;
2369
2370         if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
2371             i_mvt >= p_track->i_elst_time +
2372                      elst->i_segment_duration[p_track->i_elst] )
2373         {
2374             MP4_TrackSetELST( p_demux, p_track,
2375                               MP4_TrackGetDTS( p_demux, p_track ) );
2376         }
2377     }
2378
2379     return VLC_SUCCESS;
2380 }
2381
2382 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
2383                               int64_t i_time )
2384 {
2385     demux_sys_t *p_sys = p_demux->p_sys;
2386     int         i_elst_last = tk->i_elst;
2387
2388     /* handle elst (find the correct one) */
2389     tk->i_elst      = 0;
2390     tk->i_elst_time = 0;
2391     if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
2392     {
2393         MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
2394         int64_t i_mvt= i_time * p_sys->i_timescale / (int64_t)1000000;
2395
2396         for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
2397         {
2398             mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
2399
2400             if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
2401             {
2402                 break;
2403             }
2404             tk->i_elst_time += i_dur;
2405         }
2406
2407         if( (unsigned int)tk->i_elst >= elst->i_entry_count )
2408         {
2409             /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
2410             tk->i_elst = elst->i_entry_count - 1;
2411             tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
2412         }
2413
2414         if( elst->i_media_time[tk->i_elst] < 0 )
2415         {
2416             /* track offset */
2417             tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
2418         }
2419     }
2420     if( i_elst_last != tk->i_elst )
2421     {
2422         msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
2423     }
2424 }
2425
2426 static vlc_bool_t FindItem( demux_t *p_demux, playlist_t *p_playlist,
2427                             playlist_item_t **pp_item )
2428 {
2429     input_thread_t *p_input = (input_thread_t *)vlc_object_find( p_demux, VLC_OBJECT_INPUT, FIND_PARENT );
2430     vlc_bool_t b_play = var_CreateGetBool( p_demux, "playlist-autostart" );
2431
2432     *pp_item = NULL;
2433     if( p_input )
2434     {
2435         if( b_play && p_playlist->status.p_item &&
2436             p_playlist->status.p_item->p_input == input_GetItem(p_input) )
2437         {
2438             msg_Dbg( p_playlist, "starting playlist playback" );
2439             *pp_item = p_playlist->status.p_item;
2440             b_play = VLC_TRUE;
2441         }
2442         else
2443         {
2444             input_item_t *p_current = input_GetItem( p_input );
2445
2446             *pp_item = playlist_ItemGetByInput( p_playlist, p_current, VLC_FALSE );
2447             if( !*pp_item )
2448                 msg_Dbg( p_playlist, "unable to find item in playlist");
2449
2450             msg_Dbg( p_playlist, "not starting playlist playback");
2451             b_play = VLC_FALSE;
2452         }
2453         vlc_object_release( p_input );
2454     }
2455     return b_play;
2456 }
2457
2458