1 /*****************************************************************************
2 * mp4.c : MP4 file input module for vlc
3 *****************************************************************************
4 * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN
6 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
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 Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 *****************************************************************************/
23 /*****************************************************************************
25 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35 #include <vlc_charset.h> /* EnsureUTF8 */
36 #include <vlc_meta.h> /* vlc_meta_t, vlc_meta_ */
37 #include <vlc_input.h>
41 #include "id3genres.h" /* for ATOM_gnre */
43 /*****************************************************************************
45 *****************************************************************************/
46 static int Open ( vlc_object_t * );
47 static void Close( vlc_object_t * );
50 set_category( CAT_INPUT )
51 set_subcategory( SUBCAT_INPUT_DEMUX )
52 set_description( N_("MP4 stream demuxer") )
53 set_shortname( N_("MP4") )
54 set_capability( "demux", 240 )
55 set_callbacks( Open, Close )
58 /*****************************************************************************
60 *****************************************************************************/
61 static int Demux ( demux_t * );
62 static int DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
63 static int DemuxFrg( demux_t * );
64 static int Seek ( demux_t *, mtime_t );
65 static int Control ( demux_t *, int, va_list );
69 MP4_Box_t *p_root; /* container for the whole file */
73 uint64_t i_time; /* time position of the presentation
74 * in movie timescale */
75 uint64_t i_timescale; /* movie time scale */
76 uint64_t i_duration; /* movie duration */
77 unsigned int i_tracks; /* number of tracks */
78 mp4_track_t *track; /* array of track */
79 float f_fps; /* number of frame per seconds */
81 bool b_fragmented; /* fMP4 */
84 MP4_Box_t *p_tref_chap;
87 input_title_t *p_title;
90 /*****************************************************************************
91 * Declaration of local function
92 *****************************************************************************/
93 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
94 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
95 static void MP4_TrackDestroy( mp4_track_t * );
97 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
98 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
100 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
102 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
103 static uint32_t MP4_TrackSampleSize( mp4_track_t *, uint32_t * );
104 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
105 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
107 static void MP4_UpdateSeekpoint( demux_t * );
108 static const char *MP4_ConvertMacCode( uint16_t );
110 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
112 uint32_t i_return = 0;
113 if ( i_toread > INT32_MAX )
115 i_return = stream_Read( s, p_read, INT32_MAX );
116 if ( i_return < INT32_MAX )
119 i_toread -= INT32_MAX;
121 i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
125 /* Return time in microsecond of a track */
126 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
128 demux_sys_t *p_sys = p_demux->p_sys;
130 if( p_sys->b_fragmented )
131 chunk = *p_track->cchunk;
133 chunk = p_track->chunk[p_track->i_chunk];
135 unsigned int i_index = 0;
136 unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
137 int64_t i_dts = chunk.i_first_dts;
139 while( i_sample > 0 )
141 if( i_sample > chunk.p_sample_count_dts[i_index] )
143 i_dts += chunk.p_sample_count_dts[i_index] *
144 chunk.p_sample_delta_dts[i_index];
145 i_sample -= chunk.p_sample_count_dts[i_index];
150 i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
155 /* now handle elst */
156 if( p_track->p_elst )
158 demux_sys_t *p_sys = p_demux->p_sys;
159 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
161 /* convert to offset */
162 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
163 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
164 elst->i_media_time[p_track->i_elst] > 0 )
166 i_dts -= elst->i_media_time[p_track->i_elst];
169 /* add i_elst_time */
170 i_dts += p_track->i_elst_time * p_track->i_timescale /
173 if( i_dts < 0 ) i_dts = 0;
176 return CLOCK_FREQ * i_dts / p_track->i_timescale;
179 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
181 demux_sys_t *p_sys = p_demux->p_sys;
183 if( p_sys->b_fragmented )
184 ck = p_track->cchunk;
186 ck = &p_track->chunk[p_track->i_chunk];
188 unsigned int i_index = 0;
189 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
191 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
194 for( i_index = 0;; i_index++ )
196 if( i_sample < ck->p_sample_count_pts[i_index] )
197 return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
198 (int64_t)p_track->i_timescale;
200 i_sample -= ck->p_sample_count_pts[i_index];
204 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
206 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
209 static void LoadChapter( demux_t *p_demux );
211 static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
213 demux_sys_t *p_sys = p_demux->p_sys;
215 if( b_smooth ) /* Smooth Streaming */
217 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
219 goto LoadInitFragError;
223 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
224 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
225 goto LoadInitFragError;
226 /* Get number of tracks */
228 for( int i = 0; i < 3; i++ )
230 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
231 if( p_stra && p_stra->data.p_stra->i_track_ID )
233 /* Get timescale and duration of the video track; */
234 if( p_sys->i_timescale == 0 )
236 p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
237 p_sys->i_duration = p_stra->data.p_stra->i_duration;
238 if( p_sys->i_timescale == 0 )
240 msg_Err( p_demux, "bad timescale" );
241 goto LoadInitFragError;
249 /* Load all boxes ( except raw data ) */
250 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
252 goto LoadInitFragError;
258 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
262 static int InitTracks( demux_t *p_demux )
264 demux_sys_t *p_sys = p_demux->p_sys;
266 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
267 if( p_sys->track == NULL )
270 if( p_sys->b_fragmented )
272 mp4_track_t *p_track;
273 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
275 p_track = &p_sys->track[i];
276 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
277 if( unlikely( !p_track->cchunk ) )
279 free( p_sys->track );
287 static void CreateTracksFromSmooBox( demux_t *p_demux )
289 demux_sys_t *p_sys = p_demux->p_sys;
291 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
292 mp4_track_t *p_track;
294 for( int i = 0; i < 3; i++ )
296 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
297 if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
301 p_track = &p_sys->track[j]; j++;
302 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
303 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
308 /*****************************************************************************
309 * Open: check file and initializes MP4 structures
310 *****************************************************************************/
311 static int Open( vlc_object_t * p_this )
313 demux_t *p_demux = (demux_t *)p_this;
316 const uint8_t *p_peek;
327 /* A little test to see if it could be a mp4 */
328 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
330 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
341 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
344 /* We don't yet support f4v, but avformat does. */
345 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
353 stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
356 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
360 /*Set exported functions */
361 p_demux->pf_demux = Demux;
362 p_demux->pf_control = Control;
364 /* create our structure that will contains all data */
365 p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
367 /* Is it Smooth Streaming? */
368 bool b_smooth = false;
369 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
370 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
373 p_sys->b_fragmented = true;
376 if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
379 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
381 p_sys->b_fragmented = true;
383 if( p_sys->b_fragmented )
385 p_demux->pf_demux = DemuxFrg;
388 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
391 if( InitTracks( p_demux ) != VLC_SUCCESS )
393 CreateTracksFromSmooBox( p_demux );
396 else if( p_sys->b_fragmented && b_seekable )
398 /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
399 * box. So if STREAM_CAN_FASTSEEK is true, we're assuming we've got such
400 * a file, and we let avformat do the job. */
401 msg_Warn( p_demux, "MP4 plugin discarded "\
402 "(fast-seekable and fragmented, let avformat demux it)" );
403 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
406 else if( !p_sys->b_fragmented && !b_seekable )
408 msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
409 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
413 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
415 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
417 switch( p_ftyp->data.p_ftyp->i_major_brand )
421 "ISO Media file (isom) version %d.",
422 p_ftyp->data.p_ftyp->i_minor_version );
425 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
426 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
427 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
428 msg_Dbg( p_demux, "3GPP Media file Release: %c",
429 #ifdef WORDS_BIGENDIAN
430 p_ftyp->data.p_ftyp->i_major_brand
432 p_ftyp->data.p_ftyp->i_major_brand >> 24
436 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
437 msg_Dbg( p_demux, "Apple QuickTime file" );
439 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
440 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
444 "unrecognized major file specification (%4.4s).",
445 (char*)&p_ftyp->data.p_ftyp->i_major_brand );
451 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
454 /* the file need to have one moov box */
455 if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
457 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
461 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
464 /* we have a free box as a moov, rename it */
465 p_foov->i_type = ATOM_moov;
468 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
470 int i_count = MP4_BoxCount( p_rmra, "rmda" );
473 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
475 input_thread_t *p_input = demux_GetParentInput( p_demux );
476 input_item_t *p_current = input_GetItem( p_input );
478 input_item_node_t *p_subitems = input_item_node_Create( p_current );
480 for( i = 0; i < i_count; i++ )
482 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
486 if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
490 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
492 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
493 psz_ref, (char*)&i_ref_type );
495 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
497 if( strstr( psz_ref, "qt5gateQT" ) )
499 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
502 if( !strncmp( psz_ref, "http://", 7 ) ||
503 !strncmp( psz_ref, "rtsp://", 7 ) )
510 char *psz_path = strdup( p_demux->psz_location );
511 char *end = strrchr( psz_path, '/' );
512 if( end ) end[1] = '\0';
513 else *psz_path = '\0';
515 if( asprintf( &psz_absolute, "%s://%s%s",
516 p_demux->psz_access, psz_path, psz_ref ) < 0 )
520 input_item_node_Delete( p_subitems );
521 vlc_object_release( p_input) ;
526 psz_ref = psz_absolute;
529 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
530 input_item_t *p_item = input_item_New( psz_ref, NULL );
531 input_item_CopyOptions( p_current, p_item );
532 input_item_node_AppendItem( p_subitems, p_item );
533 vlc_gc_decref( p_item );
537 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
538 (char*)&p_rdrf->data.p_rdrf->i_ref_type );
542 input_item_node_PostAndDelete( p_subitems );
543 vlc_object_release( p_input );
546 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
550 msg_Err( p_demux, "cannot find /moov/mvhd" );
555 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
556 p_demux->pf_demux = DemuxRef;
562 p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
563 if( p_sys->i_timescale == 0 )
565 msg_Err( p_this, "bad timescale" );
568 p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
571 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
573 msg_Err( p_demux, "cannot find any /moov/trak" );
576 msg_Dbg( p_demux, "found %d track%c",
578 p_sys->i_tracks ? 's':' ' );
580 if( InitTracks( p_demux ) != VLC_SUCCESS )
583 /* Search the first chap reference (like quicktime) and
584 * check that at least 1 stream is enabled */
585 p_sys->p_tref_chap = NULL;
586 b_enabled_es = false;
587 for( i = 0; i < p_sys->i_tracks; i++ )
589 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
592 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
593 if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
596 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
597 if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
598 p_sys->p_tref_chap = p_chap;
601 /* now process each track and extract all useful information */
602 for( i = 0; i < p_sys->i_tracks; i++ )
604 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
605 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
607 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
610 switch( p_sys->track[i].fmt.i_cat )
619 psz_cat = "subtitle";
627 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
628 p_sys->track[i].i_track_ID, psz_cat,
629 p_sys->track[i].b_enable ? "enable":"disable",
630 p_sys->track[i].fmt.psz_language ?
631 p_sys->track[i].fmt.psz_language : "undef" );
633 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
635 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
636 p_sys->track[i].i_track_ID,
637 p_sys->track[i].fmt.psz_language ?
638 p_sys->track[i].fmt.psz_language : "undef" );
642 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
643 p_sys->track[i].i_track_ID );
648 LoadChapter( p_demux );
655 MP4_BoxFree( p_demux->s, p_sys->p_root );
661 /*****************************************************************************
662 * Demux: read packet and send them to decoders
663 *****************************************************************************
664 * TODO check for newly selected track (ie audio upt to now )
665 *****************************************************************************/
666 static int Demux( demux_t *p_demux )
668 demux_sys_t *p_sys = p_demux->p_sys;
669 unsigned int i_track;
672 unsigned int i_track_selected;
674 /* check for newly selected/unselected track */
675 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
678 mp4_track_t *tk = &p_sys->track[i_track];
681 if( !tk->b_ok || tk->b_chapter ||
682 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
687 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
689 if( tk->b_selected && !b )
691 MP4_TrackUnselect( p_demux, tk );
693 else if( !tk->b_selected && b)
695 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
704 if( i_track_selected <= 0 )
706 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
707 if( p_sys->i_timescale > 0 )
709 int64_t i_length = CLOCK_FREQ *
710 (mtime_t)p_sys->i_duration /
711 (mtime_t)p_sys->i_timescale;
712 if( MP4_GetMoviePTS( p_sys ) >= i_length )
717 msg_Warn( p_demux, "no track selected, exiting..." );
722 MP4_UpdateSeekpoint( p_demux );
724 /* first wait for the good time to read a packet */
725 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
727 /* we will read 100ms for each stream so ...*/
728 mtime_t i_targettime = p_sys->i_pcr + CLOCK_FREQ/10;
729 bool b_data_sent = false;
731 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
733 mp4_track_t *tk = &p_sys->track[i_track];
735 if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
738 while( MP4_TrackGetDTS( p_demux, tk ) < i_targettime
739 || ( p_sys->i_pcr == VLC_TS_INVALID && !b_data_sent ) )
742 msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
743 MP4_TrackGetDTS( p_demux, tk ),
744 MP4_GetMoviePTS( p_sys ) );
746 uint32_t i_nb_samples = 0;
747 uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
748 if( i_samplessize > 0 )
751 int64_t i_delta, i_newpos;
754 i_newpos = MP4_TrackGetPos( tk );
755 if( stream_Tell( p_demux->s ) != i_newpos )
757 if( stream_Seek( p_demux->s, i_newpos ) )
759 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
761 MP4_TrackUnselect( p_demux, tk );
767 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
769 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
771 MP4_TrackUnselect( p_demux, tk );
774 else if( tk->fmt.i_cat == SPU_ES )
776 if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
777 tk->fmt.i_codec != VLC_CODEC_SPU )
778 p_block->i_buffer = 0;
782 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
784 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
786 p_block->i_pts = p_block->i_dts + i_delta;
787 else if( tk->fmt.i_cat != VIDEO_ES )
788 p_block->i_pts = p_block->i_dts;
790 p_block->i_pts = VLC_TS_INVALID;
794 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
797 es_out_Send( p_demux->out, tk->p_es, p_block );
801 if( MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
808 p_sys->i_pcr = INT64_MAX;
809 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
811 mp4_track_t *tk = &p_sys->track[i_track];
812 if ( !tk->b_ok || !tk->b_selected ) continue;
813 p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
814 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
821 static void MP4_UpdateSeekpoint( demux_t *p_demux )
823 demux_sys_t *p_sys = p_demux->p_sys;
826 if( !p_sys->p_title )
828 i_time = MP4_GetMoviePTS( p_sys );
829 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
831 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
836 if( i != p_demux->info.i_seekpoint && i >= 0 )
838 p_demux->info.i_seekpoint = i;
839 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
842 /*****************************************************************************
844 ******************************************************************************/
845 static int Seek( demux_t *p_demux, mtime_t i_date )
847 demux_sys_t *p_sys = p_demux->p_sys;
848 unsigned int i_track;
850 /* First update global time */
851 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
852 p_sys->i_pcr = VLC_TS_INVALID;
854 /* Now for each stream try to go to this time */
855 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
857 mp4_track_t *tk = &p_sys->track[i_track];
858 MP4_TrackSeek( p_demux, tk, i_date );
860 MP4_UpdateSeekpoint( p_demux );
862 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
867 static int MP4_frg_Seek( demux_t *p_demux, double f )
869 demux_sys_t *p_sys = p_demux->p_sys;
871 int64_t i64 = stream_Size( p_demux->s );
872 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
878 /* update global time */
879 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
880 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
882 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
884 mp4_track_t *tk = &p_sys->track[i_track];
886 /* We don't want the current chunk to be flushed */
887 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
889 /* reset/update some values */
890 tk->i_sample = tk->i_sample_first = 0;
891 tk->i_first_dts = p_sys->i_time;
893 /* We want to discard the current chunk and get the next one at once */
894 tk->b_has_non_empty_cchunk = false;
896 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
901 /*****************************************************************************
903 *****************************************************************************/
904 static int Control( demux_t *p_demux, int i_query, va_list args )
906 demux_sys_t *p_sys = p_demux->p_sys;
913 case DEMUX_GET_POSITION:
914 pf = (double*)va_arg( args, double * );
915 if( p_sys->i_duration > 0 )
917 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
925 case DEMUX_SET_POSITION:
926 f = (double)va_arg( args, double );
927 if( p_sys->b_fragmented )
929 return MP4_frg_Seek( p_demux, f );
931 else if( p_sys->i_timescale > 0 )
933 i64 = (int64_t)( f * CLOCK_FREQ *
934 (double)p_sys->i_duration /
935 (double)p_sys->i_timescale );
936 return Seek( p_demux, i64 );
938 else return VLC_SUCCESS;
941 pi64 = (int64_t*)va_arg( args, int64_t * );
942 if( p_sys->i_timescale > 0 )
945 (mtime_t)p_sys->i_time /
946 (mtime_t)p_sys->i_timescale;
952 i64 = (int64_t)va_arg( args, int64_t );
953 return Seek( p_demux, i64 );
955 case DEMUX_GET_LENGTH:
956 pi64 = (int64_t*)va_arg( args, int64_t * );
957 if( p_sys->i_timescale > 0 )
960 (mtime_t)p_sys->i_duration /
961 (mtime_t)p_sys->i_timescale;
967 pf = (double*)va_arg( args, double* );
971 case DEMUX_GET_ATTACHMENTS:
973 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
974 int *pi_int = va_arg( args, int * );
976 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
977 if ( !p_covr ) return VLC_EGENERIC;
981 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
983 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
990 *ppp_attach = (input_attachment_t**)
991 malloc( sizeof(input_attachment_t*) * i_count );
992 if( !(*ppp_attach) ) return VLC_ENOMEM;
996 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
998 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1001 if ( !memcmp( p_box->data.p_data->p_blob,
1002 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1004 psz_mime = strdup( "image/png" );
1006 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1008 psz_mime = strdup( "image/jpeg" );
1015 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1017 (*ppp_attach)[i_count++] =
1018 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1019 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1020 free( psz_filename );
1028 free( *ppp_attach );
1029 return VLC_EGENERIC;
1037 case DEMUX_GET_META:
1039 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1040 MP4_Box_t *p_0xa9xxx;
1042 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1044 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1046 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1047 if( p_udta == NULL )
1049 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1050 if( p_udta == NULL && p_covr == NULL )
1051 return VLC_EGENERIC;
1056 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1057 p_0xa9xxx = p_0xa9xxx->p_next )
1060 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
1063 /* FIXME FIXME: should convert from whatever the character
1064 * encoding of MP4 meta data is to UTF-8. */
1065 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
1066 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1067 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1069 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1070 switch( p_0xa9xxx->i_type )
1072 case ATOM_0xa9nam: /* Full name */
1073 SET( vlc_meta_SetTitle );
1076 SET( vlc_meta_SetArtist );
1079 SET( vlc_meta_SetArtist );
1082 SET( vlc_meta_SetCopyright );
1084 case ATOM_0xa9day: /* Creation Date */
1085 SET( vlc_meta_SetDate );
1087 case ATOM_0xa9des: /* Description */
1088 SET( vlc_meta_SetDescription );
1090 case ATOM_0xa9gen: /* Genre */
1091 SET( vlc_meta_SetGenre );
1095 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1096 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1099 case ATOM_0xa9alb: /* Album */
1100 SET( vlc_meta_SetAlbum );
1103 case ATOM_0xa9trk: /* Track */
1104 SET( vlc_meta_SetTrackNum );
1109 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1110 p_0xa9xxx->data.p_trkn->i_track_number );
1111 vlc_meta_SetTrackNum( p_meta, psz_trck );
1112 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1114 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1115 p_0xa9xxx->data.p_trkn->i_track_total );
1116 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1120 case ATOM_0xa9cmt: /* Commment */
1121 SET( vlc_meta_SetDescription );
1124 case ATOM_0xa9url: /* URL */
1125 SET( vlc_meta_SetURL );
1128 case ATOM_0xa9too: /* Encoder Tool */
1129 case ATOM_0xa9enc: /* Encoded By */
1130 SET( vlc_meta_SetEncodedBy );
1134 SET( vlc_meta_SetPublisher );
1138 SET( vlc_meta_SetDirector );
1145 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1147 { ATOM_0xa9wrt, N_("Writer") },
1148 { ATOM_0xa9com, N_("Composer") },
1149 { ATOM_0xa9prd, N_("Producer") },
1150 { ATOM_0xa9inf, N_("Information") },
1151 { ATOM_0xa9dis, N_("Disclaimer") },
1152 { ATOM_0xa9req, N_("Requirements") },
1153 { ATOM_0xa9fmt, N_("Original Format") },
1154 { ATOM_0xa9dsa, N_("Display Source As") },
1155 { ATOM_0xa9hst, N_("Host Computer") },
1156 { ATOM_0xa9prf, N_("Performers") },
1157 { ATOM_0xa9ope, N_("Original Performer") },
1158 { ATOM_0xa9src, N_("Providers Source Content") },
1159 { ATOM_0xa9wrn, N_("Warning") },
1160 { ATOM_0xa9swr, N_("Software") },
1161 { ATOM_0xa9lyr, N_("Lyrics") },
1162 { ATOM_0xa9mak, N_("Record Company") },
1163 { ATOM_0xa9mod, N_("Model") },
1164 { ATOM_0xa9PRD, N_("Product") },
1165 { ATOM_0xa9grp, N_("Grouping") },
1166 { ATOM_0xa9gen, N_("Genre") },
1167 { ATOM_0xa9st3, N_("Sub-Title") },
1168 { ATOM_0xa9arg, N_("Arranger") },
1169 { ATOM_0xa9ard, N_("Art Director") },
1170 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1171 { ATOM_0xa9con, N_("Conductor") },
1172 { ATOM_0xa9des, N_("Song Description") },
1173 { ATOM_0xa9lnt, N_("Liner Notes") },
1174 { ATOM_0xa9phg, N_("Phonogram Rights") },
1175 { ATOM_0xa9pub, N_("Publisher") },
1176 { ATOM_0xa9sne, N_("Sound Engineer") },
1177 { ATOM_0xa9sol, N_("Soloist") },
1178 { ATOM_0xa9thx, N_("Thanks") },
1179 { ATOM_0xa9xpd, N_("Executive Producer") },
1182 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1184 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1186 char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1189 EnsureUTF8( psz_utf );
1190 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1200 case DEMUX_GET_TITLE_INFO:
1202 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1203 int *pi_int = (int*)va_arg( args, int* );
1204 int *pi_title_offset = (int*)va_arg( args, int* );
1205 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1207 if( !p_sys->p_title )
1208 return VLC_EGENERIC;
1211 *ppp_title = malloc( sizeof( input_title_t*) );
1212 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1213 *pi_title_offset = 0;
1214 *pi_seekpoint_offset = 0;
1217 case DEMUX_SET_TITLE:
1219 const int i_title = (int)va_arg( args, int );
1220 if( !p_sys->p_title || i_title != 0 )
1221 return VLC_EGENERIC;
1224 case DEMUX_SET_SEEKPOINT:
1226 const int i_seekpoint = (int)va_arg( args, int );
1227 if( !p_sys->p_title )
1228 return VLC_EGENERIC;
1229 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1232 case DEMUX_SET_NEXT_DEMUX_TIME:
1233 case DEMUX_SET_GROUP:
1234 case DEMUX_HAS_UNSUPPORTED_META:
1235 case DEMUX_GET_PTS_DELAY:
1236 case DEMUX_CAN_RECORD:
1237 return VLC_EGENERIC;
1240 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1241 return VLC_EGENERIC;
1245 /*****************************************************************************
1246 * Close: frees unused data
1247 *****************************************************************************/
1248 static void Close ( vlc_object_t * p_this )
1250 demux_t * p_demux = (demux_t *)p_this;
1251 demux_sys_t *p_sys = p_demux->p_sys;
1252 unsigned int i_track;
1254 msg_Dbg( p_demux, "freeing all memory" );
1256 MP4_BoxFree( p_demux->s, p_sys->p_root );
1257 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1259 MP4_TrackDestroy( &p_sys->track[i_track] );
1261 FREENULL( p_sys->track );
1263 if( p_sys->p_title )
1264 vlc_input_title_Delete( p_sys->p_title );
1271 /****************************************************************************
1272 * Local functions, specific to vlc
1273 ****************************************************************************/
1275 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1277 demux_sys_t *p_sys = p_demux->p_sys;
1280 p_sys->p_title = vlc_input_title_New();
1281 for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1283 seekpoint_t *s = vlc_seekpoint_New();
1285 s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1286 EnsureUTF8( s->psz_name );
1287 s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1288 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1291 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1293 demux_sys_t *p_sys = p_demux->p_sys;
1295 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1297 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1298 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1299 uint32_t i_nb_samples = 0;
1300 const uint32_t i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
1302 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1305 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1306 __MIN( sizeof(p_buffer), i_size ) );
1307 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1311 seekpoint_t *s = vlc_seekpoint_New();
1313 s->psz_name = strndup( &p_buffer[2], i_len );
1314 EnsureUTF8( s->psz_name );
1316 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1318 if( !p_sys->p_title )
1319 p_sys->p_title = vlc_input_title_New();
1320 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1323 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1324 tk->chunk[tk->i_chunk].i_sample_count )
1328 static void LoadChapter( demux_t *p_demux )
1330 demux_sys_t *p_sys = p_demux->p_sys;
1333 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1335 LoadChapterGpac( p_demux, p_chpl );
1337 else if( p_sys->p_tref_chap )
1339 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1342 /* Load the first subtitle track like quicktime */
1343 for( i = 0; i < p_chap->i_entry_count; i++ )
1345 for( j = 0; j < p_sys->i_tracks; j++ )
1347 mp4_track_t *tk = &p_sys->track[j];
1348 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1349 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1352 if( j < p_sys->i_tracks )
1354 LoadChapterApple( p_demux, &p_sys->track[j] );
1360 /* Add duration if titles are enabled */
1361 if( p_sys->p_title )
1363 p_sys->p_title->i_length = CLOCK_FREQ *
1364 (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1368 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1369 static int TrackCreateChunksIndex( demux_t *p_demux,
1370 mp4_track_t *p_demux_track )
1372 demux_sys_t *p_sys = p_demux->p_sys;
1373 if( p_sys->b_fragmented )
1376 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1379 unsigned int i_chunk;
1380 unsigned int i_index, i_last;
1382 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1383 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1384 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1386 return( VLC_EGENERIC );
1389 p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1390 if( !p_demux_track->i_chunk_count )
1392 msg_Warn( p_demux, "no chunk defined" );
1393 return( VLC_EGENERIC );
1395 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1396 sizeof( mp4_chunk_t ) );
1397 if( p_demux_track->chunk == NULL )
1402 /* first we read chunk offset */
1403 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1405 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1407 ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1409 ck->i_first_dts = 0;
1410 ck->p_sample_count_dts = NULL;
1411 ck->p_sample_delta_dts = NULL;
1412 ck->p_sample_count_pts = NULL;
1413 ck->p_sample_offset_pts = NULL;
1416 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1417 to be used for the sample XXX begin to 1
1418 We construct it begining at the end */
1419 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1420 i_index = p_stsc->data.p_stsc->i_entry_count;
1423 msg_Warn( p_demux, "cannot read chunk table or table empty" );
1424 return( VLC_EGENERIC );
1429 for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1430 i_chunk < i_last; i_chunk++ )
1432 if( i_chunk >= p_demux_track->i_chunk_count )
1434 msg_Warn( p_demux, "corrupted chunk table" );
1435 return VLC_EGENERIC;
1438 p_demux_track->chunk[i_chunk].i_sample_description_index =
1439 p_stsc->data.p_stsc->i_sample_description_index[i_index];
1440 p_demux_track->chunk[i_chunk].i_sample_count =
1441 p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1443 i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1446 p_demux_track->chunk[0].i_sample_first = 0;
1447 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1449 p_demux_track->chunk[i_chunk].i_sample_first =
1450 p_demux_track->chunk[i_chunk-1].i_sample_first +
1451 p_demux_track->chunk[i_chunk-1].i_sample_count;
1454 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1455 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1460 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1461 const uint32_t i_index,
1462 uint32_t i_index_samples_left,
1463 uint32_t i_sample_count,
1464 const uint32_t *pi_index_sample_count,
1465 const uint32_t i_table_count )
1467 uint32_t i_array_offset;
1468 while( i_sample_count > 0 )
1470 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1471 i_array_offset = i_index + *pi_entry;
1473 return VLC_EGENERIC;
1475 if ( i_array_offset >= i_table_count )
1477 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1478 return VLC_EGENERIC;
1481 if ( i_index_samples_left )
1483 if ( i_index_samples_left > i_sample_count )
1485 i_index_samples_left -= i_sample_count;
1487 *pi_entry +=1; /* No samples left, go copy */
1492 i_sample_count -= i_index_samples_left;
1493 i_index_samples_left = 0;
1500 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1508 static int TrackCreateSamplesIndex( demux_t *p_demux,
1509 mp4_track_t *p_demux_track )
1511 demux_sys_t *p_sys = p_demux->p_sys;
1512 if( p_sys->b_fragmented )
1516 MP4_Box_data_stsz_t *stsz;
1517 /* TODO use also stss and stsh table for seeking */
1518 /* FIXME use edit table */
1521 * Gives the sample size for each samples. There is also a stz2 table
1522 * (compressed form) that we need to implement TODO */
1523 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1526 /* FIXME and stz2 */
1527 msg_Warn( p_demux, "cannot find STSZ box" );
1528 return VLC_EGENERIC;
1530 stsz = p_box->data.p_stsz;
1532 /* Use stsz table to create a sample number -> sample size table */
1533 p_demux_track->i_sample_count = stsz->i_sample_count;
1534 if( stsz->i_sample_size )
1536 /* 1: all sample have the same size, so no need to construct a table */
1537 p_demux_track->i_sample_size = stsz->i_sample_size;
1538 p_demux_track->p_sample_size = NULL;
1542 /* 2: each sample can have a different size */
1543 p_demux_track->i_sample_size = 0;
1544 p_demux_track->p_sample_size =
1545 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1546 if( p_demux_track->p_sample_size == NULL )
1549 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1551 p_demux_track->p_sample_size[i_sample] =
1552 stsz->i_entry_size[i_sample];
1556 /* Use stts table to create a sample number -> dts table.
1557 * XXX: if we don't want to waste too much memory, we can't expand
1558 * the box! so each chunk will contain an "extract" of this table
1559 * for fast research (problem with raw stream where a sample is sometime
1560 * just channels*bits_per_sample/8 */
1562 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1563 * differing in 2/2 fields and 1 signedness */
1565 mtime_t i_next_dts = 0;
1567 * Gives mapping between sample and decoding time
1569 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1572 msg_Warn( p_demux, "cannot find STTS box" );
1573 return VLC_EGENERIC;
1577 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
1579 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
1581 /* Create sample -> dts table per chunk */
1582 uint32_t i_index = 0;
1583 uint32_t i_current_index_samples_left = 0;
1585 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1587 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1588 uint32_t i_entry, i_sample_count;
1590 /* save first dts */
1591 ck->i_first_dts = i_next_dts;
1592 ck->i_last_dts = i_next_dts;
1594 /* count how many entries are needed for this chunk
1595 * for p_sample_delta_dts and p_sample_count_dts */
1598 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1599 i_current_index_samples_left,
1601 stts->pi_sample_count,
1602 stts->i_entry_count );
1603 if ( i_ret != VLC_SUCCESS )
1607 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1608 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1609 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1611 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1616 i_sample_count = ck->i_sample_count;
1618 for( uint32_t i = 0; i < i_entry; i++ )
1620 if ( i_current_index_samples_left )
1622 if ( i_current_index_samples_left > i_sample_count )
1624 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1625 ck->p_sample_count_dts[i] = i_sample_count;
1626 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1627 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1628 i_current_index_samples_left -= i_sample_count;
1630 assert( i == i_entry - 1 );
1635 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
1636 ck->p_sample_count_dts[i] = i_current_index_samples_left;
1637 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1638 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1639 i_sample_count -= i_current_index_samples_left;
1640 i_current_index_samples_left = 0;
1646 if ( stts->pi_sample_count[i_index] > i_sample_count )
1648 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1649 ck->p_sample_count_dts[i] = i_sample_count;
1650 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1651 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1652 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
1654 assert( i == i_entry - 1 );
1655 // keep building from same index
1659 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
1660 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
1661 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1662 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1663 i_sample_count -= stts->pi_sample_count[i_index];
1674 * Gives the delta between decoding time (dts) and composition table (pts)
1676 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1679 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1681 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
1683 /* Create pts-dts table per chunk */
1684 uint32_t i_index = 0;
1685 uint32_t i_current_index_samples_left = 0;
1687 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1689 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1690 uint32_t i_entry, i_sample_count;
1692 /* count how many entries are needed for this chunk
1693 * for p_sample_offset_pts and p_sample_count_pts */
1695 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1696 i_current_index_samples_left,
1698 ctts->pi_sample_count,
1699 ctts->i_entry_count );
1700 if ( i_ret != VLC_SUCCESS )
1704 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1705 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1706 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1708 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1713 i_sample_count = ck->i_sample_count;
1715 for( uint32_t i = 0; i < i_entry; i++ )
1717 if ( i_current_index_samples_left )
1719 if ( i_current_index_samples_left > i_sample_count )
1721 ck->p_sample_count_pts[i] = i_sample_count;
1722 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1723 i_current_index_samples_left -= i_sample_count;
1725 assert( i == i_entry - 1 );
1730 ck->p_sample_count_pts[i] = i_current_index_samples_left;
1731 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1732 i_sample_count -= i_current_index_samples_left;
1733 i_current_index_samples_left = 0;
1739 if ( ctts->pi_sample_count[i_index] > i_sample_count )
1741 ck->p_sample_count_pts[i] = i_sample_count;
1742 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1743 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
1745 assert( i == i_entry - 1 );
1746 // keep building from same index
1750 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
1751 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1752 i_sample_count -= ctts->pi_sample_count[i_index];
1762 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
1763 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1764 i_next_dts / p_demux_track->i_timescale );
1771 * It computes the sample rate for a video track using the given sample
1774 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1775 const mp4_track_t *p_track,
1776 unsigned i_sd_index,
1782 if( p_track->i_chunk_count <= 0 )
1786 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1787 while( p_chunk > &p_track->chunk[0] &&
1788 p_chunk[-1].i_sample_description_index == i_sd_index )
1793 uint64_t i_sample = 0;
1794 uint64_t i_first_dts = p_chunk->i_first_dts;
1795 uint64_t i_last_dts;
1798 i_sample += p_chunk->i_sample_count;
1799 i_last_dts = p_chunk->i_last_dts;
1802 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1803 p_chunk->i_sample_description_index == i_sd_index );
1805 if( i_sample > 1 && i_first_dts < i_last_dts )
1806 vlc_ureduce( pi_num, pi_den,
1807 ( i_sample - 1) * p_track->i_timescale,
1808 i_last_dts - i_first_dts,
1814 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1816 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1817 unsigned int i_chunk, es_out_id_t **pp_es )
1819 demux_sys_t *p_sys = p_demux->p_sys;
1820 unsigned int i_sample_description_index;
1822 if( p_sys->b_fragmented )
1823 i_sample_description_index = 1; /* XXX */
1825 i_sample_description_index =
1826 p_track->chunk[i_chunk].i_sample_description_index;
1828 MP4_Box_t *p_sample;
1837 if( !i_sample_description_index )
1839 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1840 p_track->i_track_ID );
1841 return VLC_EGENERIC;
1844 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
1845 i_sample_description_index - 1 );
1848 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
1850 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1851 p_track->i_track_ID );
1852 return VLC_EGENERIC;
1855 p_track->p_sample = p_sample;
1857 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1859 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1861 p_sample->i_type = p_frma->data.p_frma->i_type;
1864 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1866 p_enda = MP4_BoxGet( p_sample, "enda" );
1868 p_pasp = MP4_BoxGet( p_sample, "pasp" );
1871 switch( p_track->fmt.i_cat )
1874 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1875 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1876 p_track->fmt.video.i_bits_per_pixel =
1877 p_sample->data.p_sample_vide->i_depth;
1879 /* fall on display size */
1880 if( p_track->fmt.video.i_width <= 0 )
1881 p_track->fmt.video.i_width = p_track->i_width;
1882 if( p_track->fmt.video.i_height <= 0 )
1883 p_track->fmt.video.i_height = p_track->i_height;
1885 /* Find out apect ratio from display size */
1886 if( p_track->i_width > 0 && p_track->i_height > 0 &&
1887 /* Work-around buggy muxed files */
1888 p_sample->data.p_sample_vide->i_width != p_track->i_width )
1890 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
1891 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1893 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1894 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1896 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1897 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1900 /* Support for cropping (eg. in H263 files) */
1901 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1902 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1905 TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1906 &p_track->fmt.video.i_frame_rate_base,
1907 p_track, i_sample_description_index, i_chunk );
1908 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1909 (float)p_track->fmt.video.i_frame_rate_base;
1912 switch( (int)p_track->f_rotation ) {
1914 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1917 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1920 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1927 p_track->fmt.audio.i_channels =
1928 p_sample->data.p_sample_soun->i_channelcount;
1929 p_track->fmt.audio.i_rate =
1930 p_sample->data.p_sample_soun->i_sampleratehi;
1931 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1932 p_sample->data.p_sample_soun->i_sampleratehi *
1933 p_sample->data.p_sample_soun->i_samplesize;
1934 p_track->fmt.audio.i_bitspersample =
1935 p_sample->data.p_sample_soun->i_samplesize;
1937 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1939 MP4_Box_data_sample_soun_t *p_soun;
1940 p_soun = p_sample->data.p_sample_soun;
1942 if( p_soun->i_qt_version == 0 )
1944 switch( p_sample->i_type )
1946 case VLC_CODEC_ADPCM_IMA_QT:
1947 p_soun->i_qt_version = 1;
1948 p_soun->i_sample_per_packet = 64;
1949 p_soun->i_bytes_per_packet = 34;
1950 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
1951 p_soun->i_bytes_per_sample = 2;
1953 case VLC_CODEC_MACE3:
1954 p_soun->i_qt_version = 1;
1955 p_soun->i_sample_per_packet = 6;
1956 p_soun->i_bytes_per_packet = 2;
1957 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1958 p_soun->i_bytes_per_sample = 2;
1960 case VLC_CODEC_MACE6:
1961 p_soun->i_qt_version = 1;
1962 p_soun->i_sample_per_packet = 12;
1963 p_soun->i_bytes_per_packet = 2;
1964 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1965 p_soun->i_bytes_per_sample = 2;
1967 case VLC_CODEC_ALAW:
1968 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1969 p_soun->i_samplesize = 8;
1970 p_track->i_sample_size = p_soun->i_channelcount;
1972 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1973 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1974 case VLC_FOURCC( 't', 'w', 'o', 's' ):
1975 case VLC_FOURCC( 's', 'o', 'w', 't' ):
1976 /* What would be the fun if you could trust the .mov */
1977 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1984 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1986 p_soun->i_qt_version = 0;
1989 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1991 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1993 switch( p_sample->i_type )
1995 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1996 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1998 if( p_track->i_sample_size > 1 )
1999 p_soun->i_qt_version = 0;
2002 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2003 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2004 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2005 p_soun->i_qt_version = 0;
2012 if( p_track->i_sample_size != 0 &&
2013 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2014 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2016 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2017 p_sample->data.p_sample_soun->i_qt_version = 0;
2026 /* It's a little ugly but .. there are special cases */
2027 switch( p_sample->i_type )
2029 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2030 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2032 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2035 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2037 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2039 p_track->fmt.i_codec = VLC_CODEC_A52;
2042 static const int pi_bitrate[] = {
2049 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2050 p_track->fmt.audio.i_channels = 0;
2051 p_track->fmt.i_bitrate = 0;
2052 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2053 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2054 p_track->fmt.audio.i_bitspersample = 0;
2058 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2060 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2064 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2065 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2067 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2069 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2070 p_track->fmt.i_codec = VLC_CODEC_U8;
2072 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2074 /* Buggy files workaround */
2075 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2076 p_sample->data.p_sample_soun->i_sampleratehi) )
2078 MP4_Box_data_sample_soun_t *p_soun =
2079 p_sample->data.p_sample_soun;
2081 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
2082 "(%u), making both equal (report any problem).",
2083 p_track->i_timescale, p_soun->i_sampleratehi );
2085 if( p_soun->i_sampleratehi != 0 )
2086 p_track->i_timescale = p_soun->i_sampleratehi;
2088 p_soun->i_sampleratehi = p_track->i_timescale;
2093 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2094 p_track->fmt.i_codec = VLC_CODEC_H263;
2097 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2098 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2100 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2101 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2104 text_style_t *p_style = text_style_New();
2107 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2108 p_style->i_font_size = p_text->i_font_size;
2109 if ( p_text->i_font_color )
2111 p_style->i_font_color = p_text->i_font_color >> 8;
2112 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2114 if ( p_text->i_background_color[3] >> 8 )
2116 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2117 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2118 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2119 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2122 p_track->fmt.subs.p_style = p_style;
2124 /* FIXME UTF-8 doesn't work here ? */
2125 if( p_track->b_mac_encoding )
2126 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2128 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2131 case VLC_FOURCC('y','v','1','2'):
2132 p_track->fmt.i_codec = VLC_CODEC_YV12;
2134 case VLC_FOURCC('y','u','v','2'):
2135 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2138 case VLC_FOURCC('i','n','2','4'):
2139 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2140 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2142 case VLC_FOURCC('i','n','3','2'):
2143 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2144 VLC_CODEC_S32L : VLC_CODEC_S32B;
2146 case VLC_FOURCC('f','l','3','2'):
2147 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2148 VLC_CODEC_F32L : VLC_CODEC_F32B;
2150 case VLC_FOURCC('f','l','6','4'):
2151 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2152 VLC_CODEC_F64L : VLC_CODEC_F64B;
2154 case VLC_CODEC_DVD_LPCM:
2156 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2157 if( p_soun->i_qt_version == 2 &&
2158 p_soun->i_qt_description > 20 + 28 )
2165 static const struct {
2169 vlc_fourcc_t i_codec;
2171 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2172 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2173 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2174 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2176 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2177 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2179 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2180 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2181 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2182 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2184 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2185 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2186 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2187 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2189 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2190 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2191 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2192 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2196 uint32_t i_bits = GetDWBE(&p_soun->p_qt_description[20 + 20]);
2197 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
2199 for( int i = 0; p_formats[i].i_codec; i++ )
2201 if( p_formats[i].i_bits == i_bits &&
2202 (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
2204 p_track->fmt.i_codec = p_formats[i].i_codec;
2205 p_track->fmt.audio.i_bitspersample = i_bits;
2206 p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
2207 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2209 p_soun->i_qt_version = 0;
2217 p_track->fmt.i_codec = p_sample->i_type;
2221 /* now see if esds is present and if so create a data packet
2222 with decoder_specific_info */
2223 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2224 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2225 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2226 ( p_esds->data.p_esds )&&
2229 /* First update information based on i_objectTypeIndication */
2230 switch( p_decconfig->i_objectTypeIndication )
2232 case( 0x20 ): /* MPEG4 VIDEO */
2233 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2235 case( 0x21 ): /* H.264 */
2236 p_track->fmt.i_codec = VLC_CODEC_H264;
2239 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2240 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2241 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2242 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2244 p_track->fmt.i_codec = VLC_CODEC_ALS;
2252 case( 0x65): /* MPEG2 video */
2253 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2255 /* Theses are MPEG2-AAC */
2256 case( 0x66): /* main profile */
2257 case( 0x67): /* Low complexity profile */
2258 case( 0x68): /* Scaleable Sampling rate profile */
2259 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2261 /* True MPEG 2 audio */
2263 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2265 case( 0x6a): /* MPEG1 video */
2266 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2268 case( 0x6b): /* MPEG1 audio */
2269 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2271 case( 0x6c ): /* jpeg */
2272 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2274 case( 0x6d ): /* png */
2275 p_track->fmt.i_codec = VLC_CODEC_PNG;
2277 case( 0x6e ): /* jpeg2000 */
2278 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2280 case( 0xa3 ): /* vc1 */
2281 p_track->fmt.i_codec = VLC_CODEC_VC1;
2284 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2287 p_track->fmt.i_codec = VLC_CODEC_A52;
2290 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2292 case( 0xa9 ): /* dts */
2293 case( 0xaa ): /* DTS-HD HRA */
2294 case( 0xab ): /* DTS-HD Master Audio */
2295 p_track->fmt.i_codec = VLC_CODEC_DTS;
2298 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2302 case( 0xe0 ): /* NeroDigital: dvd subs */
2303 if( p_track->fmt.i_cat == SPU_ES )
2305 p_track->fmt.i_codec = VLC_CODEC_SPU;
2306 if( p_track->i_width > 0 )
2307 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2308 if( p_track->i_height > 0 )
2309 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2312 case( 0xe1 ): /* QCelp for 3gp */
2313 if( p_track->fmt.i_cat == AUDIO_ES )
2315 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2321 /* Unknown entry, but don't touch i_fourcc */
2323 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2324 p_decconfig->i_objectTypeIndication,
2325 p_track->i_track_ID );
2328 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2329 if( p_track->fmt.i_extra > 0 )
2331 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2332 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2333 p_track->fmt.i_extra );
2335 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2336 p_track->fmt.i_extra >= 16 * 4 )
2338 for( int i = 0; i < 16; i++ )
2340 p_track->fmt.subs.spu.palette[1 + i] =
2341 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2343 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2348 switch( p_sample->i_type )
2350 /* qt decoder, send the complete chunk */
2351 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2352 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2353 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2354 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2355 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2356 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2357 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2358 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2359 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2360 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2361 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2362 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2363 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2365 /* qt decoder, send the complete chunk */
2366 case VLC_CODEC_SVQ1:
2367 case VLC_CODEC_SVQ3:
2368 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2369 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2370 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2371 p_track->fmt.i_extra =
2372 p_sample->data.p_sample_vide->i_qt_image_description;
2373 if( p_track->fmt.i_extra > 0 )
2375 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2376 memcpy( p_track->fmt.p_extra,
2377 p_sample->data.p_sample_vide->p_qt_image_description,
2378 p_track->fmt.i_extra);
2382 case VLC_CODEC_AMR_NB:
2383 p_track->fmt.audio.i_rate = 8000;
2385 case VLC_CODEC_AMR_WB:
2386 p_track->fmt.audio.i_rate = 16000;
2388 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2389 case VLC_CODEC_QDM2:
2390 case VLC_CODEC_ALAC:
2391 p_track->fmt.i_extra =
2392 p_sample->data.p_sample_soun->i_qt_description;
2393 if( p_track->fmt.i_extra > 0 )
2395 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2396 memcpy( p_track->fmt.p_extra,
2397 p_sample->data.p_sample_soun->p_qt_description,
2398 p_track->fmt.i_extra);
2400 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2402 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2403 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2407 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2409 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2412 p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2413 if( p_track->fmt.i_extra > 0 )
2415 p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2416 memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2417 p_track->fmt.i_extra );
2422 msg_Err( p_demux, "missing dvc1" );
2427 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2428 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2430 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2434 p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2435 if( p_track->fmt.i_extra > 0 )
2437 p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2438 memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2439 p_track->fmt.i_extra );
2444 msg_Err( p_demux, "missing avcC" );
2448 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2449 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2451 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2455 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2456 if( p_track->fmt.i_extra > 0 )
2458 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2459 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2460 p_track->fmt.i_extra );
2462 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2466 msg_Err( p_demux, "missing hvcC" );
2472 case VLC_CODEC_ADPCM_MS:
2473 case VLC_CODEC_ADPCM_IMA_WAV:
2474 case VLC_CODEC_QCELP:
2475 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2479 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2487 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2492 /* given a time it return sample/chunk
2493 * it also update elst field of the track
2495 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2496 int64_t i_start, uint32_t *pi_chunk,
2497 uint32_t *pi_sample )
2499 demux_sys_t *p_sys = p_demux->p_sys;
2500 MP4_Box_t *p_box_stss;
2502 unsigned int i_sample;
2503 unsigned int i_chunk;
2506 /* FIXME see if it's needed to check p_track->i_chunk_count */
2507 if( p_track->i_chunk_count == 0 )
2508 return( VLC_EGENERIC );
2510 /* handle elst (find the correct one) */
2511 MP4_TrackSetELST( p_demux, p_track, i_start );
2512 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2514 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2515 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2517 /* now calculate i_start for this elst */
2519 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2527 /* to track time scale */
2528 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2529 /* add elst offset */
2530 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2531 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2532 elst->i_media_time[p_track->i_elst] > 0 )
2534 i_start += elst->i_media_time[p_track->i_elst];
2537 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2538 "ms (track)", p_track->i_elst,
2539 i_mvt * 1000 / p_sys->i_timescale,
2540 i_start * 1000 / p_track->i_timescale );
2544 /* convert absolute time to in timescale unit */
2545 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2548 /* we start from sample 0/chunk 0, hope it won't take too much time */
2549 /* *** find good chunk *** */
2550 for( i_chunk = 0; ; i_chunk++ )
2552 if( i_chunk + 1 >= p_track->i_chunk_count )
2554 /* at the end and can't check if i_start in this chunk,
2555 it will be check while searching i_sample */
2556 i_chunk = p_track->i_chunk_count - 1;
2560 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2561 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2567 /* *** find sample in the chunk *** */
2568 i_sample = p_track->chunk[i_chunk].i_sample_first;
2569 i_dts = p_track->chunk[i_chunk].i_first_dts;
2570 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2573 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2574 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2577 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2578 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2580 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2585 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2589 i_sample += ( i_start - i_dts ) /
2590 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2595 if( i_sample >= p_track->i_sample_count )
2597 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2598 "(seeking too far) chunk=%d sample=%d",
2599 p_track->i_track_ID, i_chunk, i_sample );
2600 return( VLC_EGENERIC );
2604 /* *** Try to find nearest sync points *** */
2605 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2607 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2608 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2609 p_track->i_track_ID );
2610 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2612 if( i_index >= p_stss->i_entry_count - 1 ||
2613 i_sample < p_stss->i_sample_number[i_index+1] )
2615 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2616 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2617 i_sample, i_sync_sample );
2619 if( i_sync_sample <= i_sample )
2621 while( i_chunk > 0 &&
2622 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2627 while( i_chunk < p_track->i_chunk_count - 1 &&
2628 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2629 p_track->chunk[i_chunk].i_sample_count )
2632 i_sample = i_sync_sample;
2639 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2640 "Sample Box (stss)", p_track->i_track_ID );
2643 *pi_chunk = i_chunk;
2644 *pi_sample = i_sample;
2649 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2650 unsigned int i_chunk, unsigned int i_sample )
2652 bool b_reselect = false;
2654 /* now see if actual es is ok */
2655 if( p_track->i_chunk >= p_track->i_chunk_count ||
2656 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2657 p_track->chunk[i_chunk].i_sample_description_index )
2659 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2660 p_track->i_track_ID );
2662 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2663 p_track->p_es, &b_reselect );
2665 es_out_Del( p_demux->out, p_track->p_es );
2667 p_track->p_es = NULL;
2669 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2671 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2672 p_track->i_track_ID );
2674 p_track->b_ok = false;
2675 p_track->b_selected = false;
2676 return VLC_EGENERIC;
2680 /* select again the new decoder */
2683 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2686 p_track->i_chunk = i_chunk;
2687 p_track->i_sample = i_sample;
2689 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2692 /****************************************************************************
2694 ****************************************************************************
2695 * Parse track information and create all needed data to run a track
2696 * If it succeed b_ok is set to 1 else to 0
2697 ****************************************************************************/
2698 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2699 MP4_Box_t *p_box_trak,
2700 bool b_force_enable )
2702 demux_sys_t *p_sys = p_demux->p_sys;
2704 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2705 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2715 char language[4] = { '\0' };
2717 /* hint track unsupported */
2719 /* set default value (-> track unusable) */
2720 p_track->b_ok = false;
2721 p_track->b_enable = false;
2722 p_track->b_selected = false;
2723 p_track->b_chapter = false;
2724 p_track->b_mac_encoding = false;
2726 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2733 /* do we launch this track by default ? */
2735 ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2736 if( !p_track->b_enable )
2737 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2739 p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2741 p_track->i_width = p_tkhd->data.p_tkhd->i_width / BLOCK16x16;
2742 p_track->i_height = p_tkhd->data.p_tkhd->i_height / BLOCK16x16;
2743 p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2747 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2750 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2751 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2753 if( ( !p_mdhd )||( !p_hdlr ) )
2758 p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2759 if( p_track->i_timescale == 0 )
2762 if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2764 strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2765 p_track->b_mac_encoding = true;
2767 else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2768 p_track->b_mac_encoding = true;
2771 for( unsigned i = 0; i < 3; i++ )
2772 language[i] = p_mdhd->data.p_mdhd->i_language[i];
2776 switch( p_hdlr->data.p_hdlr->i_handler_type )
2779 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2783 p_track->fmt.i_cat = AUDIO_ES;
2787 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2791 p_track->fmt.i_cat = VIDEO_ES;
2798 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2799 p_track->fmt.i_cat = SPU_ES;
2806 p_track->i_elst = 0;
2807 p_track->i_elst_time = 0;
2808 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2810 MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2813 msg_Warn( p_demux, "elst box found" );
2814 for( i = 0; i < elst->i_entry_count; i++ )
2816 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2817 "ms) rate=%d.%d", i,
2818 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2819 elst->i_media_time[i] >= 0 ?
2820 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2822 elst->i_media_rate_integer[i],
2823 elst->i_media_rate_fraction[i] );
2830 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2832 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2833 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2839 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2841 p_track->fmt.psz_language = strdup( language );
2844 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2847 MP4_Box_t *p_box_iter;
2848 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2849 p_box_iter = p_box_iter->p_next )
2851 switch( p_box_iter->i_type )
2854 p_track->fmt.psz_description =
2855 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2858 p_track->fmt.psz_description =
2859 strdup( p_box_iter->data.p_name->psz_text );
2865 /* Create chunk index table and sample index table */
2866 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2867 TrackCreateSamplesIndex( p_demux, p_track ) )
2869 return; /* cannot create chunks index */
2872 p_track->i_chunk = 0;
2873 p_track->i_sample = 0;
2875 /* Mark chapter only track */
2876 if( p_sys->p_tref_chap )
2878 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2881 for( i = 0; i < p_chap->i_entry_count; i++ )
2883 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2884 p_track->fmt.i_cat == UNKNOWN_ES )
2886 p_track->b_chapter = true;
2887 p_track->b_enable = false;
2894 if( b_force_enable &&
2895 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2897 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2898 p_track->i_track_ID );
2899 p_track->b_enable = true;
2900 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2903 p_track->p_es = NULL;
2904 if( TrackCreateES( p_demux,
2905 p_track, p_track->i_chunk,
2906 p_track->b_chapter ? NULL : &p_track->p_es ) )
2908 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2909 p_track->i_track_ID );
2912 p_track->b_ok = true;
2916 for( i = 0; i < p_track->i_chunk_count; i++ )
2918 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2919 i, p_track->chunk[i].i_sample_count,
2920 p_track->chunk[i].i_first_dts );
2927 static void FreeAndResetChunk( mp4_chunk_t *ck )
2929 free( ck->p_sample_count_dts );
2930 free( ck->p_sample_delta_dts );
2931 free( ck->p_sample_count_pts );
2932 free( ck->p_sample_offset_pts );
2933 free( ck->p_sample_size );
2934 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2935 free( ck->p_sample_data[i] );
2936 free( ck->p_sample_data );
2937 memset( ck, 0, sizeof( mp4_chunk_t ) );
2940 /****************************************************************************
2942 ****************************************************************************
2943 * Destroy a track created by MP4_TrackCreate.
2944 ****************************************************************************/
2945 static void MP4_TrackDestroy( mp4_track_t *p_track )
2947 unsigned int i_chunk;
2949 p_track->b_ok = false;
2950 p_track->b_enable = false;
2951 p_track->b_selected = false;
2953 es_format_Clean( &p_track->fmt );
2955 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2957 if( p_track->chunk )
2959 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2960 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2962 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2963 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2966 FREENULL( p_track->chunk );
2967 if( p_track->cchunk ) {
2968 FreeAndResetChunk( p_track->cchunk );
2969 FREENULL( p_track->cchunk );
2972 if( !p_track->i_sample_size )
2974 FREENULL( p_track->p_sample_size );
2978 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2981 if( !p_track->b_ok || p_track->b_chapter )
2983 return VLC_EGENERIC;
2986 if( p_track->b_selected )
2988 msg_Warn( p_demux, "track[Id 0x%x] already selected",
2989 p_track->i_track_ID );
2993 return MP4_TrackSeek( p_demux, p_track, i_start );
2996 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2998 if( !p_track->b_ok || p_track->b_chapter )
3003 if( !p_track->b_selected )
3005 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3006 p_track->i_track_ID );
3011 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3012 p_track->p_es, false );
3015 p_track->b_selected = false;
3018 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3024 if( !p_track->b_ok || p_track->b_chapter )
3025 return VLC_EGENERIC;
3027 p_track->b_selected = false;
3029 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3030 &i_chunk, &i_sample ) )
3032 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3033 p_track->i_track_ID );
3034 return VLC_EGENERIC;
3037 p_track->b_selected = true;
3039 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3040 p_track->b_selected = true;
3042 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3047 * 3 types: for audio
3050 #define QT_V0_MAX_SAMPLES 1024
3051 static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3054 MP4_Box_data_sample_soun_t *p_soun;
3056 if( p_track->i_sample_size == 0 )
3058 /* most simple case */
3059 return p_track->p_sample_size[p_track->i_sample];
3061 if( p_track->fmt.i_cat != AUDIO_ES )
3063 return p_track->i_sample_size;
3066 p_soun = p_track->p_sample->data.p_sample_soun;
3068 if( p_soun->i_qt_version == 1 )
3070 uint32_t i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
3071 if( p_track->fmt.audio.i_blockalign > 1 )
3072 i_samples = p_soun->i_sample_per_packet;
3074 i_size = i_samples / p_soun->i_sample_per_packet;
3075 if ( UINT32_MAX / i_size < p_soun->i_bytes_per_frame )
3076 i_size *= p_soun->i_bytes_per_frame;
3078 i_size = UINT32_MAX;
3080 else if( p_track->i_sample_size > 256 )
3082 /* We do that so we don't read too much data
3083 * (in this case we are likely dealing with compressed data) */
3084 i_size = p_track->i_sample_size;
3088 mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3089 int64_t i_length = CLOCK_FREQ / 10;
3090 uint32_t i_samples = 0;
3091 uint32_t i_maxsamples = 0;
3092 for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
3094 i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
3095 if ( i_length < 0 ) break;
3099 i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
3100 i_samples = __MIN( i_maxsamples, i_samples );
3101 if ( i_samples == 0 ) i_samples = 1;
3102 i_size = i_samples * p_track->i_sample_size;
3103 *pi_nb_samples = i_samples;
3106 //fprintf( stderr, "size=%d\n", i_size );
3110 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3112 unsigned int i_sample;
3115 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3117 if( p_track->i_sample_size )
3119 MP4_Box_data_sample_soun_t *p_soun =
3120 p_track->p_sample->data.p_sample_soun;
3122 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3124 i_pos += ( p_track->i_sample -
3125 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3126 p_track->i_sample_size;
3130 /* we read chunk by chunk unless a blockalign is requested */
3131 if( p_track->fmt.audio.i_blockalign > 1 )
3132 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3133 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3138 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3139 i_sample < p_track->i_sample; i_sample++ )
3141 i_pos += p_track->p_sample_size[i_sample];
3148 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3150 if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
3152 MP4_Box_data_sample_soun_t *p_soun;
3154 p_soun = p_track->p_sample->data.p_sample_soun;
3156 if( p_soun->i_qt_version == 1 )
3158 /* we read chunk by chunk unless a blockalign is requested */
3159 if( p_track->fmt.audio.i_blockalign > 1 )
3160 p_track->i_sample += p_soun->i_sample_per_packet;
3162 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
3164 else if( p_track->i_sample_size > 256 )
3166 /* We do that so we don't read too much data
3167 * (in this case we are likely dealing with compressed data) */
3168 p_track->i_sample += 1;
3173 p_track->i_sample += i_samples;
3174 if( p_track->i_sample >
3175 p_track->chunk[p_track->i_chunk].i_sample_first +
3176 p_track->chunk[p_track->i_chunk].i_sample_count )
3179 p_track->chunk[p_track->i_chunk].i_sample_first +
3180 p_track->chunk[p_track->i_chunk].i_sample_count;
3186 p_track->i_sample++;
3189 if( p_track->i_sample >= p_track->i_sample_count )
3190 return VLC_EGENERIC;
3192 /* Have we changed chunk ? */
3193 if( p_track->i_sample >=
3194 p_track->chunk[p_track->i_chunk].i_sample_first +
3195 p_track->chunk[p_track->i_chunk].i_sample_count )
3197 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3198 p_track->i_sample ) )
3200 msg_Warn( p_demux, "track[0x%x] will be disabled "
3201 "(cannot restart decoder)", p_track->i_track_ID );
3202 MP4_TrackUnselect( p_demux, p_track );
3203 return VLC_EGENERIC;
3207 /* Have we changed elst */
3208 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
3210 demux_sys_t *p_sys = p_demux->p_sys;
3211 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
3212 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3213 p_sys->i_timescale / CLOCK_FREQ;
3215 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3216 i_mvt >= p_track->i_elst_time +
3217 elst->i_segment_duration[p_track->i_elst] )
3219 MP4_TrackSetELST( p_demux, p_track,
3220 MP4_TrackGetDTS( p_demux, p_track ) );
3227 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3230 demux_sys_t *p_sys = p_demux->p_sys;
3231 int i_elst_last = tk->i_elst;
3233 /* handle elst (find the correct one) */
3235 tk->i_elst_time = 0;
3236 if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
3238 MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
3239 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3241 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3243 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3245 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3249 tk->i_elst_time += i_dur;
3252 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3254 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3255 tk->i_elst = elst->i_entry_count - 1;
3256 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3259 if( elst->i_media_time[tk->i_elst] < 0 )
3262 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3265 if( i_elst_last != tk->i_elst )
3267 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3272 static const char *MP4_ConvertMacCode( uint16_t i_code )
3274 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3275 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3276 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3277 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3278 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3279 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3280 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3281 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3282 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3283 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3284 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3285 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3286 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3287 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3288 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3289 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3290 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3291 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3292 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3293 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3295 { "cy", 128 }, { "eu", 129 },
3296 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3297 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3298 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3299 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3304 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3306 if( p_cvt[i].i_code == i_code )
3307 return p_cvt[i].psz_iso639_1;
3312 /******************************************************************************
3313 * Here are the functions used for fragmented MP4
3314 *****************************************************************************/
3317 * It computes the sample rate for a video track using current video chunk
3319 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3320 const mp4_track_t *p_track )
3322 if( p_track->cchunk->i_last_dts == 0 )
3329 const mp4_chunk_t *p_chunk = p_track->cchunk;
3331 uint32_t i_sample = p_chunk->i_sample_count;
3332 uint64_t i_first_dts = p_chunk->i_first_dts;
3333 uint64_t i_last_dts = p_chunk->i_last_dts;
3335 if( i_sample > 1 && i_first_dts < i_last_dts )
3336 vlc_ureduce( pi_num, pi_den,
3337 ( i_sample - 1) * p_track->i_timescale,
3338 i_last_dts - i_first_dts,
3343 * Build raw avcC box (without the 8 bytes header)
3344 * \return The size of the box.
3346 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3347 const unsigned cpd_len )
3350 unsigned sps_len = 0, pps_len = 0;
3351 const uint32_t mark = 0x00000001;
3353 assert( CodecPrivateData[0] == 0 );
3354 assert( CodecPrivateData[1] == 0 );
3355 assert( CodecPrivateData[2] == 0 );
3356 assert( CodecPrivateData[3] == 1 );
3358 uint32_t length = cpd_len + 3;
3359 avcC = calloc( length, 1 );
3360 if( unlikely( avcC == NULL ) )
3363 uint8_t *sps = avcC + 8;
3365 uint32_t candidate = ~mark;
3366 CodecPrivateData += 4;
3367 for( unsigned i = 0; i < cpd_len - 4; i++ )
3369 sps[i] = CodecPrivateData[i];
3370 candidate = (candidate << 8) | CodecPrivateData[i];
3371 if( candidate == mark )
3382 uint8_t *pps = sps + sps_len + 3;
3383 pps_len = cpd_len - sps_len - 4 * 2;
3384 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3387 uint8_t AVCProfileIndication = 0x64;
3388 uint8_t profile_compatibility = 0x40;
3389 uint8_t AVCLevelIndication = 0x1f;
3390 uint8_t lengthSizeMinusOne = 0x03;
3393 avcC[1] = AVCProfileIndication;
3394 avcC[2] = profile_compatibility;
3395 avcC[3] = AVCLevelIndication;
3396 avcC[4] = 0xfc + lengthSizeMinusOne;
3398 avcC[6] = (sps_len & 0xff00)>>8;
3399 avcC[7] = sps_len & 0xff;
3401 avcC[8+sps_len] = 1;
3402 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3403 avcC[10+sps_len] = pps_len & 0xff;
3410 * Build a mp4_track_t from a StraBox
3413 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3415 fmt->i_extra = p_data->cpd_len;
3416 fmt->p_extra = malloc( p_data->cpd_len );
3417 if( unlikely( !fmt->p_extra ) )
3419 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3423 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3425 demux_sys_t *p_sys = p_demux->p_sys;
3427 MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3429 return VLC_EGENERIC;
3431 p_track->b_ok = true;
3432 p_track->b_selected = false;
3433 p_track->i_sample_count = UINT32_MAX;
3435 p_track->i_timescale = p_sys->i_timescale;
3436 p_track->i_width = p_data->MaxWidth;
3437 p_track->i_height = p_data->MaxHeight;
3438 p_track->i_track_ID = p_data->i_track_ID;
3440 es_format_t *fmt = &p_track->fmt;
3442 return VLC_EGENERIC;
3444 es_format_Init( fmt, p_data->i_es_cat, 0 );
3446 /* Set language FIXME */
3447 fmt->psz_language = strdup( "en" );
3449 fmt->i_original_fourcc = p_data->FourCC;
3450 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3452 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3453 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3454 * for MS weird use of FourCC*/
3455 switch( fmt->i_cat )
3458 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3459 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3460 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3462 fmt->i_extra = build_raw_avcC( p_extra,
3463 p_data->CodecPrivateData, p_data->cpd_len );
3467 ret = MP4_SetCodecExtraData( fmt, p_data );
3468 if( ret != VLC_SUCCESS )
3472 fmt->video.i_width = p_data->MaxWidth;
3473 fmt->video.i_height = p_data->MaxHeight;
3474 fmt->video.i_bits_per_pixel = 0x18;
3475 fmt->video.i_visible_width = p_data->MaxWidth;
3476 fmt->video.i_visible_height = p_data->MaxHeight;
3479 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3480 &fmt->video.i_frame_rate_base, p_track );
3482 if( fmt->video.i_frame_rate_base != 0 )
3484 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3485 (float)fmt->video.i_frame_rate_base;
3488 p_demux->p_sys->f_fps = 24;
3493 fmt->audio.i_channels = p_data->Channels;
3494 fmt->audio.i_rate = p_data->SamplingRate;
3495 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3496 fmt->audio.i_blockalign = p_data->nBlockAlign;
3498 fmt->i_bitrate = p_data->Bitrate;
3500 ret = MP4_SetCodecExtraData( fmt, p_data );
3501 if( ret != VLC_SUCCESS )
3514 * Return the track identified by tid
3516 static mp4_track_t *MP4_frg_GetTrack( demux_t *p_demux, const uint32_t tid )
3518 demux_sys_t *p_sys = p_demux->p_sys;
3520 mp4_track_t *ret = NULL;
3521 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3523 ret = &p_sys->track[i];
3526 if( ret->i_track_ID == tid )
3529 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3533 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3535 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3536 mp4_chunk_t *ck = tk->cchunk;
3537 while( ck->i_sample < ck->i_sample_count )
3542 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3545 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3546 assert( sample_size > 0 );
3547 p_block = block_Alloc( sample_size );
3548 if( unlikely( !p_block ) )
3551 uint8_t *src = ck->p_sample_data[ck->i_sample];
3552 memcpy( p_block->p_buffer, src, sample_size );
3556 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3558 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3560 p_block->i_pts = p_block->i_dts + i_delta;
3561 else if( tk->fmt.i_cat != VIDEO_ES )
3562 p_block->i_pts = p_block->i_dts;
3564 p_block->i_pts = VLC_TS_INVALID;
3566 es_out_Send( p_demux->out, tk->p_es, p_block );
3574 * \Note If we call that function too soon,
3575 * before the track has been selected by MP4_TrackSelect
3576 * (during the first execution of Demux), then the track gets disabled
3578 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3580 demux_sys_t *p_sys = p_demux->p_sys;
3582 uint32_t i_sample = 0;
3583 bool b_smooth = false;
3584 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3586 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3591 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3592 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3593 return VLC_EGENERIC;
3597 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3599 return VLC_EGENERIC;
3602 i_sample = p_track->i_sample;
3603 es_out_Del( p_demux->out, p_track->p_es );
3604 es_format_Clean( &p_track->fmt );
3607 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3609 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3611 p_track->i_sample = i_sample;
3613 /* Temporary hack until we support track selection */
3614 p_track->b_selected = true;
3615 p_track->b_ok = true;
3616 p_track->b_enable = true;
3618 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3619 p_track->b_codec_need_restart = false;
3625 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3626 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3627 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3628 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3630 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3632 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3633 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3636 msg_Warn( p_demux, "no moof box found!" );
3637 return VLC_EGENERIC;
3640 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3643 msg_Warn( p_demux, "no traf box found!" );
3644 return VLC_EGENERIC;
3647 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3650 msg_Warn( p_demux, "no tfhd box found!" );
3651 return VLC_EGENERIC;
3654 uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3655 *i_tk_id = i_track_ID;
3656 assert( i_track_ID > 0 );
3657 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3659 mp4_track_t *p_track = MP4_frg_GetTrack( p_demux, i_track_ID );
3661 return VLC_EGENERIC;
3663 mp4_chunk_t *ret = p_track->cchunk;
3665 if( p_tfhd->data.p_tfhd->b_empty )
3666 msg_Warn( p_demux, "No samples in this chunk!" );
3668 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3669 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3670 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3671 * and so on. Finally, suppose that we get the chunks the other way around,
3672 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3673 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3674 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3675 * flush it, i.e. send to the decoder the samples not yet sent.
3676 * Note that all the samples to be flushed should worth less than 100 ms,
3677 * (though I did not do the formal proof) and thus this flushing mechanism
3678 * should not cause A/V sync issues, or delays or whatever.
3680 if( ret->i_sample < ret->i_sample_count )
3681 FlushChunk( p_demux, p_track );
3683 if( ret->i_sample_count )
3684 FreeAndResetChunk( ret );
3686 uint32_t default_duration = 0;
3687 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3688 default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3690 uint32_t default_size = 0;
3691 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3692 default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3694 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3697 msg_Warn( p_demux, "no trun box found!" );
3698 return VLC_EGENERIC;
3700 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3702 ret->i_sample_count = p_trun_data->i_sample_count;
3703 assert( ret->i_sample_count > 0 );
3704 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3705 ret->i_sample_first = p_track->i_sample_first;
3706 p_track->i_sample_first += ret->i_sample_count;
3708 ret->i_first_dts = p_track->i_first_dts;
3710 /* XXX I already saw DASH content with no default_duration and no
3711 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3712 * This chunk of code might be buggy with segments having
3713 * more than one subsegment. */
3714 if( !default_duration )
3716 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
3719 while( p_trex && p_trex->data.p_trex->i_track_ID != i_track_ID )
3720 p_trex = p_trex->p_next;
3722 default_duration = p_trex->data.p_trex->i_default_sample_duration * p_track->i_timescale;
3726 MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3727 assert( p_sidx_data->i_reference_count == 1 );
3729 if( p_sidx_data->i_timescale == 0 )
3730 return VLC_EGENERIC;
3732 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3733 p_sidx_data->i_timescale;
3734 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3739 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3741 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3742 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3744 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3747 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3748 if( !ret->p_sample_count_pts )
3751 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3753 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3754 if( !ret->p_sample_offset_pts )
3758 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3759 if( !ret->p_sample_size )
3762 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3763 if( !ret->p_sample_data )
3766 uint32_t dur = 0, len;
3767 uint32_t chunk_duration = 0, chunk_size = 0;
3769 /* Skip header of mdat */
3770 stream_Read( p_demux->s, NULL, 8 );
3772 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3774 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3775 dur = p_trun_data->p_samples[i].i_duration;
3777 dur = default_duration;
3778 ret->p_sample_delta_dts[i] = dur;
3779 chunk_duration += dur;
3781 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3783 if( ret->p_sample_offset_pts )
3785 ret->p_sample_offset_pts[i] =
3786 p_trun_data->p_samples[i].i_composition_time_offset;
3789 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3790 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3792 len = ret->p_sample_size[i] = default_size;
3794 ret->p_sample_data[i] = malloc( len );
3795 if( ret->p_sample_data[i] == NULL )
3797 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
3799 return VLC_EGENERIC;
3802 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3803 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3805 if( p_track->b_codec_need_restart &&
3806 p_track->fmt.i_cat == VIDEO_ES )
3807 ReInitDecoder( p_demux, p_track );
3809 p_track->b_has_non_empty_cchunk = true;
3814 * Get the next chunk of the track identified by i_tk_id.
3815 * \Note We don't want to seek all the time, so if the first chunk given by the
3816 * input method doesn't belong to the right track, we don't throw it away,
3817 * and so, in general, this function fetch more than one chunk.
3818 * Not to mention that a new init segment might be put everywhere
3819 * between two chunks by the input method.
3821 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3823 demux_sys_t *p_sys = p_demux->p_sys;
3824 mp4_track_t *p_track;
3826 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3828 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3830 return VLC_EGENERIC;
3832 if( !p_chunk->p_first )
3833 goto MP4_frg_GetChunks_Error;
3834 uint32_t i_type = p_chunk->p_first->i_type;
3836 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3838 MP4_BoxFree( p_demux->s, p_sys->p_root );
3839 p_sys->p_root = p_chunk;
3841 if( i_type == ATOM_ftyp ) /* DASH */
3843 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3846 msg_Warn( p_demux, "No tkhd found!" );
3847 goto MP4_frg_GetChunks_Error;
3849 tid = p_tkhd->data.p_tkhd->i_track_ID;
3851 else /* Smooth Streaming */
3853 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3854 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3855 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3857 msg_Warn( p_demux, "No StraBox found!" );
3858 goto MP4_frg_GetChunks_Error;
3860 tid = p_stra->data.p_stra->i_track_ID;
3863 p_track = MP4_frg_GetTrack( p_demux, tid );
3865 goto MP4_frg_GetChunks_Error;
3866 p_track->b_codec_need_restart = true;
3868 return MP4_frg_GetChunks( p_demux, i_tk_id );
3871 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3872 goto MP4_frg_GetChunks_Error;
3874 MP4_BoxFree( p_demux->s, p_chunk );
3876 if( tid == i_tk_id )
3881 MP4_frg_GetChunks_Error:
3882 MP4_BoxFree( p_demux->s, p_chunk );
3883 return VLC_EGENERIC;
3889 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3891 if( !p_track->b_ok || p_track->b_chapter )
3893 return VLC_EGENERIC;
3896 if( p_track->b_selected )
3898 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3902 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3903 p_track->b_selected = true;
3908 * DemuxFrg: read packet and send them to decoders
3909 * \return 1 on success, 0 on error.
3910 * TODO check for newly selected track
3912 int DemuxFrg( demux_t *p_demux )
3914 demux_sys_t *p_sys = p_demux->p_sys;
3916 unsigned i_track_selected;
3918 /* check for newly selected/unselected track */
3919 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3921 mp4_track_t *tk = &p_sys->track[i_track];
3924 if( !tk->b_ok || tk->b_chapter )
3927 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3928 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3930 if( tk->b_selected && !b )
3932 MP4_TrackUnselect( p_demux, tk );
3934 else if( !tk->b_selected && b)
3936 MP4_frg_TrackSelect( p_demux, tk );
3939 if( tk->b_selected )
3943 if( i_track_selected <= 0 )
3945 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3946 if( p_sys->i_timescale > 0 )
3948 int64_t i_length = CLOCK_FREQ *
3949 (mtime_t)p_sys->i_duration /
3950 (mtime_t)p_sys->i_timescale;
3951 if( MP4_GetMoviePTS( p_sys ) >= i_length )
3956 msg_Warn( p_demux, "no track selected, exiting..." );
3960 /* first wait for the good time to read a packet */
3961 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3963 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3965 /* we will read 100ms for each stream so ...*/
3966 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3968 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3970 mp4_track_t *tk = &p_sys->track[i_track];
3972 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3974 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3978 if( !tk->b_has_non_empty_cchunk )
3980 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
3982 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
3987 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
3992 mp4_chunk_t *ck = tk->cchunk;
3993 if( ck->i_sample >= ck->i_sample_count )
3995 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
3996 ck->i_sample, ck->i_sample_count );
4000 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4001 p_block = block_Alloc( sample_size );
4002 uint8_t *src = ck->p_sample_data[ck->i_sample];
4003 memcpy( p_block->p_buffer, src, sample_size );
4006 if( ck->i_sample == ck->i_sample_count )
4007 tk->b_has_non_empty_cchunk = false;
4010 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4012 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4014 p_block->i_pts = p_block->i_dts + i_delta;
4015 else if( tk->fmt.i_cat != VIDEO_ES )
4016 p_block->i_pts = p_block->i_dts;
4018 p_block->i_pts = VLC_TS_INVALID;
4020 es_out_Send( p_demux->out, tk->p_es, p_block );
4024 if( !tk->b_has_non_empty_cchunk )