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 /* Try in mehd if fragmented */
572 if ( p_sys->i_duration == 0 )
574 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
576 p_sys->i_duration = p_mehd->data.p_mehd->i_fragment_duration;
579 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
581 msg_Err( p_demux, "cannot find any /moov/trak" );
584 msg_Dbg( p_demux, "found %d track%c",
586 p_sys->i_tracks ? 's':' ' );
588 if( InitTracks( p_demux ) != VLC_SUCCESS )
591 /* Search the first chap reference (like quicktime) and
592 * check that at least 1 stream is enabled */
593 p_sys->p_tref_chap = NULL;
594 b_enabled_es = false;
595 for( i = 0; i < p_sys->i_tracks; i++ )
597 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
600 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
601 if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
604 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
605 if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
606 p_sys->p_tref_chap = p_chap;
609 /* now process each track and extract all useful information */
610 for( i = 0; i < p_sys->i_tracks; i++ )
612 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
613 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
615 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
618 switch( p_sys->track[i].fmt.i_cat )
627 psz_cat = "subtitle";
635 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
636 p_sys->track[i].i_track_ID, psz_cat,
637 p_sys->track[i].b_enable ? "enable":"disable",
638 p_sys->track[i].fmt.psz_language ?
639 p_sys->track[i].fmt.psz_language : "undef" );
641 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
643 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
644 p_sys->track[i].i_track_ID,
645 p_sys->track[i].fmt.psz_language ?
646 p_sys->track[i].fmt.psz_language : "undef" );
650 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
651 p_sys->track[i].i_track_ID );
656 LoadChapter( p_demux );
663 MP4_BoxFree( p_demux->s, p_sys->p_root );
669 /*****************************************************************************
670 * Demux: read packet and send them to decoders
671 *****************************************************************************
672 * TODO check for newly selected track (ie audio upt to now )
673 *****************************************************************************/
674 static int Demux( demux_t *p_demux )
676 demux_sys_t *p_sys = p_demux->p_sys;
677 unsigned int i_track;
680 unsigned int i_track_selected;
682 /* check for newly selected/unselected track */
683 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
686 mp4_track_t *tk = &p_sys->track[i_track];
689 if( !tk->b_ok || tk->b_chapter ||
690 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
695 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
697 if( tk->b_selected && !b )
699 MP4_TrackUnselect( p_demux, tk );
701 else if( !tk->b_selected && b)
703 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
712 if( i_track_selected <= 0 )
714 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
715 if( p_sys->i_timescale > 0 )
717 int64_t i_length = CLOCK_FREQ *
718 (mtime_t)p_sys->i_duration /
719 (mtime_t)p_sys->i_timescale;
720 if( MP4_GetMoviePTS( p_sys ) >= i_length )
725 msg_Warn( p_demux, "no track selected, exiting..." );
730 MP4_UpdateSeekpoint( p_demux );
732 /* first wait for the good time to read a packet */
733 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
735 /* we will read 100ms for each stream so ...*/
736 mtime_t i_targettime = p_sys->i_pcr + CLOCK_FREQ/10;
737 bool b_data_sent = false;
739 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
741 mp4_track_t *tk = &p_sys->track[i_track];
743 if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
746 while( MP4_TrackGetDTS( p_demux, tk ) < i_targettime
747 || ( p_sys->i_pcr == VLC_TS_INVALID && !b_data_sent ) )
750 msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
751 MP4_TrackGetDTS( p_demux, tk ),
752 MP4_GetMoviePTS( p_sys ) );
754 uint32_t i_nb_samples = 0;
755 uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
756 if( i_samplessize > 0 )
759 int64_t i_delta, i_newpos;
762 i_newpos = MP4_TrackGetPos( tk );
763 if( stream_Tell( p_demux->s ) != i_newpos )
765 if( stream_Seek( p_demux->s, i_newpos ) )
767 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
769 MP4_TrackUnselect( p_demux, tk );
775 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
777 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
779 MP4_TrackUnselect( p_demux, tk );
782 else if( tk->fmt.i_cat == SPU_ES )
784 if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
785 tk->fmt.i_codec != VLC_CODEC_SPU )
786 p_block->i_buffer = 0;
790 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
792 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
794 p_block->i_pts = p_block->i_dts + i_delta;
795 else if( tk->fmt.i_cat != VIDEO_ES )
796 p_block->i_pts = p_block->i_dts;
798 p_block->i_pts = VLC_TS_INVALID;
802 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
805 es_out_Send( p_demux->out, tk->p_es, p_block );
809 if( MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
816 p_sys->i_pcr = INT64_MAX;
817 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
819 mp4_track_t *tk = &p_sys->track[i_track];
820 if ( !tk->b_ok || !tk->b_selected ) continue;
821 p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
822 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
829 static void MP4_UpdateSeekpoint( demux_t *p_demux )
831 demux_sys_t *p_sys = p_demux->p_sys;
834 if( !p_sys->p_title )
836 i_time = MP4_GetMoviePTS( p_sys );
837 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
839 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
844 if( i != p_demux->info.i_seekpoint && i >= 0 )
846 p_demux->info.i_seekpoint = i;
847 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
850 /*****************************************************************************
852 ******************************************************************************/
853 static int Seek( demux_t *p_demux, mtime_t i_date )
855 demux_sys_t *p_sys = p_demux->p_sys;
856 unsigned int i_track;
858 /* First update global time */
859 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
860 p_sys->i_pcr = VLC_TS_INVALID;
862 /* Now for each stream try to go to this time */
863 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
865 mp4_track_t *tk = &p_sys->track[i_track];
866 MP4_TrackSeek( p_demux, tk, i_date );
868 MP4_UpdateSeekpoint( p_demux );
870 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
875 static int MP4_frg_Seek( demux_t *p_demux, double f )
877 demux_sys_t *p_sys = p_demux->p_sys;
879 int64_t i64 = stream_Size( p_demux->s );
880 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
886 /* update global time */
887 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
888 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
890 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
892 mp4_track_t *tk = &p_sys->track[i_track];
894 /* We don't want the current chunk to be flushed */
895 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
897 /* reset/update some values */
898 tk->i_sample = tk->i_sample_first = 0;
899 tk->i_first_dts = p_sys->i_time;
901 /* We want to discard the current chunk and get the next one at once */
902 tk->b_has_non_empty_cchunk = false;
904 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
909 /*****************************************************************************
911 *****************************************************************************/
912 static int Control( demux_t *p_demux, int i_query, va_list args )
914 demux_sys_t *p_sys = p_demux->p_sys;
921 case DEMUX_GET_POSITION:
922 pf = (double*)va_arg( args, double * );
923 if( p_sys->i_duration > 0 )
925 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
933 case DEMUX_SET_POSITION:
934 f = (double)va_arg( args, double );
935 if( p_sys->b_fragmented )
937 return MP4_frg_Seek( p_demux, f );
939 else if( p_sys->i_timescale > 0 )
941 i64 = (int64_t)( f * CLOCK_FREQ *
942 (double)p_sys->i_duration /
943 (double)p_sys->i_timescale );
944 return Seek( p_demux, i64 );
946 else return VLC_SUCCESS;
949 pi64 = (int64_t*)va_arg( args, int64_t * );
950 if( p_sys->i_timescale > 0 )
953 (mtime_t)p_sys->i_time /
954 (mtime_t)p_sys->i_timescale;
960 i64 = (int64_t)va_arg( args, int64_t );
961 return Seek( p_demux, i64 );
963 case DEMUX_GET_LENGTH:
964 pi64 = (int64_t*)va_arg( args, int64_t * );
965 if( p_sys->i_timescale > 0 )
968 (mtime_t)p_sys->i_duration /
969 (mtime_t)p_sys->i_timescale;
975 pf = (double*)va_arg( args, double* );
979 case DEMUX_GET_ATTACHMENTS:
981 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
982 int *pi_int = va_arg( args, int * );
984 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
985 if ( !p_covr ) return VLC_EGENERIC;
989 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
991 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
998 *ppp_attach = (input_attachment_t**)
999 malloc( sizeof(input_attachment_t*) * i_count );
1000 if( !(*ppp_attach) ) return VLC_ENOMEM;
1004 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1006 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1009 if ( !memcmp( p_box->data.p_data->p_blob,
1010 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1012 psz_mime = strdup( "image/png" );
1014 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1016 psz_mime = strdup( "image/jpeg" );
1023 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1025 (*ppp_attach)[i_count++] =
1026 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1027 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1028 free( psz_filename );
1036 free( *ppp_attach );
1037 return VLC_EGENERIC;
1045 case DEMUX_GET_META:
1047 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1048 MP4_Box_t *p_0xa9xxx;
1050 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1052 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1054 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1055 if( p_udta == NULL )
1057 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1058 if( p_udta == NULL && p_covr == NULL )
1059 return VLC_EGENERIC;
1064 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1065 p_0xa9xxx = p_0xa9xxx->p_next )
1068 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
1071 /* FIXME FIXME: should convert from whatever the character
1072 * encoding of MP4 meta data is to UTF-8. */
1073 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
1074 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1075 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1077 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1078 switch( p_0xa9xxx->i_type )
1080 case ATOM_0xa9nam: /* Full name */
1081 SET( vlc_meta_SetTitle );
1084 SET( vlc_meta_SetArtist );
1087 SET( vlc_meta_SetArtist );
1090 SET( vlc_meta_SetCopyright );
1092 case ATOM_0xa9day: /* Creation Date */
1093 SET( vlc_meta_SetDate );
1095 case ATOM_0xa9des: /* Description */
1096 SET( vlc_meta_SetDescription );
1098 case ATOM_0xa9gen: /* Genre */
1099 SET( vlc_meta_SetGenre );
1103 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1104 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1107 case ATOM_0xa9alb: /* Album */
1108 SET( vlc_meta_SetAlbum );
1111 case ATOM_0xa9trk: /* Track */
1112 SET( vlc_meta_SetTrackNum );
1117 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1118 p_0xa9xxx->data.p_trkn->i_track_number );
1119 vlc_meta_SetTrackNum( p_meta, psz_trck );
1120 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1122 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1123 p_0xa9xxx->data.p_trkn->i_track_total );
1124 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1128 case ATOM_0xa9cmt: /* Commment */
1129 SET( vlc_meta_SetDescription );
1132 case ATOM_0xa9url: /* URL */
1133 SET( vlc_meta_SetURL );
1136 case ATOM_0xa9too: /* Encoder Tool */
1137 case ATOM_0xa9enc: /* Encoded By */
1138 SET( vlc_meta_SetEncodedBy );
1142 SET( vlc_meta_SetPublisher );
1146 SET( vlc_meta_SetDirector );
1153 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1155 { ATOM_0xa9wrt, N_("Writer") },
1156 { ATOM_0xa9com, N_("Composer") },
1157 { ATOM_0xa9prd, N_("Producer") },
1158 { ATOM_0xa9inf, N_("Information") },
1159 { ATOM_0xa9dis, N_("Disclaimer") },
1160 { ATOM_0xa9req, N_("Requirements") },
1161 { ATOM_0xa9fmt, N_("Original Format") },
1162 { ATOM_0xa9dsa, N_("Display Source As") },
1163 { ATOM_0xa9hst, N_("Host Computer") },
1164 { ATOM_0xa9prf, N_("Performers") },
1165 { ATOM_0xa9ope, N_("Original Performer") },
1166 { ATOM_0xa9src, N_("Providers Source Content") },
1167 { ATOM_0xa9wrn, N_("Warning") },
1168 { ATOM_0xa9swr, N_("Software") },
1169 { ATOM_0xa9lyr, N_("Lyrics") },
1170 { ATOM_0xa9mak, N_("Record Company") },
1171 { ATOM_0xa9mod, N_("Model") },
1172 { ATOM_0xa9PRD, N_("Product") },
1173 { ATOM_0xa9grp, N_("Grouping") },
1174 { ATOM_0xa9gen, N_("Genre") },
1175 { ATOM_0xa9st3, N_("Sub-Title") },
1176 { ATOM_0xa9arg, N_("Arranger") },
1177 { ATOM_0xa9ard, N_("Art Director") },
1178 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1179 { ATOM_0xa9con, N_("Conductor") },
1180 { ATOM_0xa9des, N_("Song Description") },
1181 { ATOM_0xa9lnt, N_("Liner Notes") },
1182 { ATOM_0xa9phg, N_("Phonogram Rights") },
1183 { ATOM_0xa9pub, N_("Publisher") },
1184 { ATOM_0xa9sne, N_("Sound Engineer") },
1185 { ATOM_0xa9sol, N_("Soloist") },
1186 { ATOM_0xa9thx, N_("Thanks") },
1187 { ATOM_0xa9xpd, N_("Executive Producer") },
1190 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1192 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1194 char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1197 EnsureUTF8( psz_utf );
1198 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1208 case DEMUX_GET_TITLE_INFO:
1210 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1211 int *pi_int = (int*)va_arg( args, int* );
1212 int *pi_title_offset = (int*)va_arg( args, int* );
1213 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1215 if( !p_sys->p_title )
1216 return VLC_EGENERIC;
1219 *ppp_title = malloc( sizeof( input_title_t*) );
1220 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1221 *pi_title_offset = 0;
1222 *pi_seekpoint_offset = 0;
1225 case DEMUX_SET_TITLE:
1227 const int i_title = (int)va_arg( args, int );
1228 if( !p_sys->p_title || i_title != 0 )
1229 return VLC_EGENERIC;
1232 case DEMUX_SET_SEEKPOINT:
1234 const int i_seekpoint = (int)va_arg( args, int );
1235 if( !p_sys->p_title )
1236 return VLC_EGENERIC;
1237 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1240 case DEMUX_SET_NEXT_DEMUX_TIME:
1241 case DEMUX_SET_GROUP:
1242 case DEMUX_HAS_UNSUPPORTED_META:
1243 case DEMUX_GET_PTS_DELAY:
1244 case DEMUX_CAN_RECORD:
1245 return VLC_EGENERIC;
1248 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1249 return VLC_EGENERIC;
1253 /*****************************************************************************
1254 * Close: frees unused data
1255 *****************************************************************************/
1256 static void Close ( vlc_object_t * p_this )
1258 demux_t * p_demux = (demux_t *)p_this;
1259 demux_sys_t *p_sys = p_demux->p_sys;
1260 unsigned int i_track;
1262 msg_Dbg( p_demux, "freeing all memory" );
1264 MP4_BoxFree( p_demux->s, p_sys->p_root );
1265 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1267 MP4_TrackDestroy( &p_sys->track[i_track] );
1269 FREENULL( p_sys->track );
1271 if( p_sys->p_title )
1272 vlc_input_title_Delete( p_sys->p_title );
1279 /****************************************************************************
1280 * Local functions, specific to vlc
1281 ****************************************************************************/
1283 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1285 demux_sys_t *p_sys = p_demux->p_sys;
1288 p_sys->p_title = vlc_input_title_New();
1289 for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1291 seekpoint_t *s = vlc_seekpoint_New();
1293 s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1294 EnsureUTF8( s->psz_name );
1295 s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1296 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1299 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1301 demux_sys_t *p_sys = p_demux->p_sys;
1303 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1305 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1306 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1307 uint32_t i_nb_samples = 0;
1308 const uint32_t i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
1310 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1313 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1314 __MIN( sizeof(p_buffer), i_size ) );
1315 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1319 seekpoint_t *s = vlc_seekpoint_New();
1321 s->psz_name = strndup( &p_buffer[2], i_len );
1322 EnsureUTF8( s->psz_name );
1324 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1326 if( !p_sys->p_title )
1327 p_sys->p_title = vlc_input_title_New();
1328 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1331 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1332 tk->chunk[tk->i_chunk].i_sample_count )
1336 static void LoadChapter( demux_t *p_demux )
1338 demux_sys_t *p_sys = p_demux->p_sys;
1341 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1343 LoadChapterGpac( p_demux, p_chpl );
1345 else if( p_sys->p_tref_chap )
1347 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1350 /* Load the first subtitle track like quicktime */
1351 for( i = 0; i < p_chap->i_entry_count; i++ )
1353 for( j = 0; j < p_sys->i_tracks; j++ )
1355 mp4_track_t *tk = &p_sys->track[j];
1356 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1357 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1360 if( j < p_sys->i_tracks )
1362 LoadChapterApple( p_demux, &p_sys->track[j] );
1368 /* Add duration if titles are enabled */
1369 if( p_sys->p_title )
1371 p_sys->p_title->i_length = CLOCK_FREQ *
1372 (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1376 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1377 static int TrackCreateChunksIndex( demux_t *p_demux,
1378 mp4_track_t *p_demux_track )
1380 demux_sys_t *p_sys = p_demux->p_sys;
1381 if( p_sys->b_fragmented )
1384 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1387 unsigned int i_chunk;
1388 unsigned int i_index, i_last;
1390 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1391 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1392 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1394 return( VLC_EGENERIC );
1397 p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1398 if( !p_demux_track->i_chunk_count )
1400 msg_Warn( p_demux, "no chunk defined" );
1401 return( VLC_EGENERIC );
1403 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1404 sizeof( mp4_chunk_t ) );
1405 if( p_demux_track->chunk == NULL )
1410 /* first we read chunk offset */
1411 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1413 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1415 ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1417 ck->i_first_dts = 0;
1418 ck->p_sample_count_dts = NULL;
1419 ck->p_sample_delta_dts = NULL;
1420 ck->p_sample_count_pts = NULL;
1421 ck->p_sample_offset_pts = NULL;
1424 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1425 to be used for the sample XXX begin to 1
1426 We construct it begining at the end */
1427 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1428 i_index = p_stsc->data.p_stsc->i_entry_count;
1431 msg_Warn( p_demux, "cannot read chunk table or table empty" );
1432 return( VLC_EGENERIC );
1437 for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1438 i_chunk < i_last; i_chunk++ )
1440 if( i_chunk >= p_demux_track->i_chunk_count )
1442 msg_Warn( p_demux, "corrupted chunk table" );
1443 return VLC_EGENERIC;
1446 p_demux_track->chunk[i_chunk].i_sample_description_index =
1447 p_stsc->data.p_stsc->i_sample_description_index[i_index];
1448 p_demux_track->chunk[i_chunk].i_sample_count =
1449 p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1451 i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1454 p_demux_track->chunk[0].i_sample_first = 0;
1455 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1457 p_demux_track->chunk[i_chunk].i_sample_first =
1458 p_demux_track->chunk[i_chunk-1].i_sample_first +
1459 p_demux_track->chunk[i_chunk-1].i_sample_count;
1462 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1463 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1468 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1469 const uint32_t i_index,
1470 uint32_t i_index_samples_left,
1471 uint32_t i_sample_count,
1472 const uint32_t *pi_index_sample_count,
1473 const uint32_t i_table_count )
1475 uint32_t i_array_offset;
1476 while( i_sample_count > 0 )
1478 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1479 i_array_offset = i_index + *pi_entry;
1481 return VLC_EGENERIC;
1483 if ( i_array_offset >= i_table_count )
1485 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1486 return VLC_EGENERIC;
1489 if ( i_index_samples_left )
1491 if ( i_index_samples_left > i_sample_count )
1493 i_index_samples_left -= i_sample_count;
1495 *pi_entry +=1; /* No samples left, go copy */
1500 i_sample_count -= i_index_samples_left;
1501 i_index_samples_left = 0;
1508 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1516 static int TrackCreateSamplesIndex( demux_t *p_demux,
1517 mp4_track_t *p_demux_track )
1519 demux_sys_t *p_sys = p_demux->p_sys;
1520 if( p_sys->b_fragmented )
1524 MP4_Box_data_stsz_t *stsz;
1525 /* TODO use also stss and stsh table for seeking */
1526 /* FIXME use edit table */
1529 * Gives the sample size for each samples. There is also a stz2 table
1530 * (compressed form) that we need to implement TODO */
1531 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1534 /* FIXME and stz2 */
1535 msg_Warn( p_demux, "cannot find STSZ box" );
1536 return VLC_EGENERIC;
1538 stsz = p_box->data.p_stsz;
1540 /* Use stsz table to create a sample number -> sample size table */
1541 p_demux_track->i_sample_count = stsz->i_sample_count;
1542 if( stsz->i_sample_size )
1544 /* 1: all sample have the same size, so no need to construct a table */
1545 p_demux_track->i_sample_size = stsz->i_sample_size;
1546 p_demux_track->p_sample_size = NULL;
1550 /* 2: each sample can have a different size */
1551 p_demux_track->i_sample_size = 0;
1552 p_demux_track->p_sample_size =
1553 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1554 if( p_demux_track->p_sample_size == NULL )
1557 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1559 p_demux_track->p_sample_size[i_sample] =
1560 stsz->i_entry_size[i_sample];
1564 /* Use stts table to create a sample number -> dts table.
1565 * XXX: if we don't want to waste too much memory, we can't expand
1566 * the box! so each chunk will contain an "extract" of this table
1567 * for fast research (problem with raw stream where a sample is sometime
1568 * just channels*bits_per_sample/8 */
1570 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1571 * differing in 2/2 fields and 1 signedness */
1573 mtime_t i_next_dts = 0;
1575 * Gives mapping between sample and decoding time
1577 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1580 msg_Warn( p_demux, "cannot find STTS box" );
1581 return VLC_EGENERIC;
1585 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
1587 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
1589 /* Create sample -> dts table per chunk */
1590 uint32_t i_index = 0;
1591 uint32_t i_current_index_samples_left = 0;
1593 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1595 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1596 uint32_t i_entry, i_sample_count;
1598 /* save first dts */
1599 ck->i_first_dts = i_next_dts;
1600 ck->i_last_dts = i_next_dts;
1602 /* count how many entries are needed for this chunk
1603 * for p_sample_delta_dts and p_sample_count_dts */
1606 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1607 i_current_index_samples_left,
1609 stts->pi_sample_count,
1610 stts->i_entry_count );
1611 if ( i_ret != VLC_SUCCESS )
1615 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1616 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1617 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1619 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1624 i_sample_count = ck->i_sample_count;
1626 for( uint32_t i = 0; i < i_entry; i++ )
1628 if ( i_current_index_samples_left )
1630 if ( i_current_index_samples_left > i_sample_count )
1632 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1633 ck->p_sample_count_dts[i] = i_sample_count;
1634 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1635 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1636 i_current_index_samples_left -= i_sample_count;
1638 assert( i == i_entry - 1 );
1643 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
1644 ck->p_sample_count_dts[i] = i_current_index_samples_left;
1645 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1646 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1647 i_sample_count -= i_current_index_samples_left;
1648 i_current_index_samples_left = 0;
1654 if ( stts->pi_sample_count[i_index] > i_sample_count )
1656 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1657 ck->p_sample_count_dts[i] = i_sample_count;
1658 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1659 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1660 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
1662 assert( i == i_entry - 1 );
1663 // keep building from same index
1667 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
1668 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
1669 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1670 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1671 i_sample_count -= stts->pi_sample_count[i_index];
1682 * Gives the delta between decoding time (dts) and composition table (pts)
1684 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1687 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1689 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
1691 /* Create pts-dts table per chunk */
1692 uint32_t i_index = 0;
1693 uint32_t i_current_index_samples_left = 0;
1695 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1697 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1698 uint32_t i_entry, i_sample_count;
1700 /* count how many entries are needed for this chunk
1701 * for p_sample_offset_pts and p_sample_count_pts */
1703 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1704 i_current_index_samples_left,
1706 ctts->pi_sample_count,
1707 ctts->i_entry_count );
1708 if ( i_ret != VLC_SUCCESS )
1712 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1713 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1714 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1716 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1721 i_sample_count = ck->i_sample_count;
1723 for( uint32_t i = 0; i < i_entry; i++ )
1725 if ( i_current_index_samples_left )
1727 if ( i_current_index_samples_left > i_sample_count )
1729 ck->p_sample_count_pts[i] = i_sample_count;
1730 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1731 i_current_index_samples_left -= i_sample_count;
1733 assert( i == i_entry - 1 );
1738 ck->p_sample_count_pts[i] = i_current_index_samples_left;
1739 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1740 i_sample_count -= i_current_index_samples_left;
1741 i_current_index_samples_left = 0;
1747 if ( ctts->pi_sample_count[i_index] > i_sample_count )
1749 ck->p_sample_count_pts[i] = i_sample_count;
1750 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1751 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
1753 assert( i == i_entry - 1 );
1754 // keep building from same index
1758 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
1759 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1760 i_sample_count -= ctts->pi_sample_count[i_index];
1770 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
1771 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1772 i_next_dts / p_demux_track->i_timescale );
1779 * It computes the sample rate for a video track using the given sample
1782 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1783 const mp4_track_t *p_track,
1784 unsigned i_sd_index,
1790 if( p_track->i_chunk_count <= 0 )
1794 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1795 while( p_chunk > &p_track->chunk[0] &&
1796 p_chunk[-1].i_sample_description_index == i_sd_index )
1801 uint64_t i_sample = 0;
1802 uint64_t i_first_dts = p_chunk->i_first_dts;
1803 uint64_t i_last_dts;
1806 i_sample += p_chunk->i_sample_count;
1807 i_last_dts = p_chunk->i_last_dts;
1810 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1811 p_chunk->i_sample_description_index == i_sd_index );
1813 if( i_sample > 1 && i_first_dts < i_last_dts )
1814 vlc_ureduce( pi_num, pi_den,
1815 ( i_sample - 1) * p_track->i_timescale,
1816 i_last_dts - i_first_dts,
1822 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1824 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1825 unsigned int i_chunk, es_out_id_t **pp_es )
1827 demux_sys_t *p_sys = p_demux->p_sys;
1828 unsigned int i_sample_description_index;
1830 if( p_sys->b_fragmented )
1831 i_sample_description_index = 1; /* XXX */
1833 i_sample_description_index =
1834 p_track->chunk[i_chunk].i_sample_description_index;
1836 MP4_Box_t *p_sample;
1845 if( !i_sample_description_index )
1847 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1848 p_track->i_track_ID );
1849 return VLC_EGENERIC;
1852 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
1853 i_sample_description_index - 1 );
1856 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
1858 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1859 p_track->i_track_ID );
1860 return VLC_EGENERIC;
1863 p_track->p_sample = p_sample;
1865 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1867 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1869 p_sample->i_type = p_frma->data.p_frma->i_type;
1872 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1874 p_enda = MP4_BoxGet( p_sample, "enda" );
1876 p_pasp = MP4_BoxGet( p_sample, "pasp" );
1879 switch( p_track->fmt.i_cat )
1882 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1883 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1884 p_track->fmt.video.i_bits_per_pixel =
1885 p_sample->data.p_sample_vide->i_depth;
1887 /* fall on display size */
1888 if( p_track->fmt.video.i_width <= 0 )
1889 p_track->fmt.video.i_width = p_track->i_width;
1890 if( p_track->fmt.video.i_height <= 0 )
1891 p_track->fmt.video.i_height = p_track->i_height;
1893 /* Find out apect ratio from display size */
1894 if( p_track->i_width > 0 && p_track->i_height > 0 &&
1895 /* Work-around buggy muxed files */
1896 p_sample->data.p_sample_vide->i_width != p_track->i_width )
1898 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
1899 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1901 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1902 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1904 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1905 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1908 /* Support for cropping (eg. in H263 files) */
1909 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1910 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1913 TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1914 &p_track->fmt.video.i_frame_rate_base,
1915 p_track, i_sample_description_index, i_chunk );
1916 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1917 (float)p_track->fmt.video.i_frame_rate_base;
1920 switch( (int)p_track->f_rotation ) {
1922 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1925 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1928 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1935 p_track->fmt.audio.i_channels =
1936 p_sample->data.p_sample_soun->i_channelcount;
1937 p_track->fmt.audio.i_rate =
1938 p_sample->data.p_sample_soun->i_sampleratehi;
1939 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1940 p_sample->data.p_sample_soun->i_sampleratehi *
1941 p_sample->data.p_sample_soun->i_samplesize;
1942 p_track->fmt.audio.i_bitspersample =
1943 p_sample->data.p_sample_soun->i_samplesize;
1945 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1947 MP4_Box_data_sample_soun_t *p_soun;
1948 p_soun = p_sample->data.p_sample_soun;
1950 if( p_soun->i_qt_version == 0 )
1952 switch( p_sample->i_type )
1954 case VLC_CODEC_ADPCM_IMA_QT:
1955 p_soun->i_qt_version = 1;
1956 p_soun->i_sample_per_packet = 64;
1957 p_soun->i_bytes_per_packet = 34;
1958 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
1959 p_soun->i_bytes_per_sample = 2;
1961 case VLC_CODEC_MACE3:
1962 p_soun->i_qt_version = 1;
1963 p_soun->i_sample_per_packet = 6;
1964 p_soun->i_bytes_per_packet = 2;
1965 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1966 p_soun->i_bytes_per_sample = 2;
1968 case VLC_CODEC_MACE6:
1969 p_soun->i_qt_version = 1;
1970 p_soun->i_sample_per_packet = 12;
1971 p_soun->i_bytes_per_packet = 2;
1972 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1973 p_soun->i_bytes_per_sample = 2;
1975 case VLC_CODEC_ALAW:
1976 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1977 p_soun->i_samplesize = 8;
1978 p_track->i_sample_size = p_soun->i_channelcount;
1980 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1981 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1982 case VLC_FOURCC( 't', 'w', 'o', 's' ):
1983 case VLC_FOURCC( 's', 'o', 'w', 't' ):
1984 /* What would be the fun if you could trust the .mov */
1985 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1992 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1994 p_soun->i_qt_version = 0;
1997 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1999 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2001 switch( p_sample->i_type )
2003 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2004 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2006 if( p_track->i_sample_size > 1 )
2007 p_soun->i_qt_version = 0;
2010 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2011 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2012 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2013 p_soun->i_qt_version = 0;
2020 if( p_track->i_sample_size != 0 &&
2021 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2022 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2024 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2025 p_sample->data.p_sample_soun->i_qt_version = 0;
2034 /* It's a little ugly but .. there are special cases */
2035 switch( p_sample->i_type )
2037 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2038 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2040 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2043 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2045 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2047 p_track->fmt.i_codec = VLC_CODEC_A52;
2050 static const int pi_bitrate[] = {
2057 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2058 p_track->fmt.audio.i_channels = 0;
2059 p_track->fmt.i_bitrate = 0;
2060 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2061 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2062 p_track->fmt.audio.i_bitspersample = 0;
2066 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2068 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2072 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2073 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2075 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2077 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2078 p_track->fmt.i_codec = VLC_CODEC_U8;
2080 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2082 /* Buggy files workaround */
2083 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2084 p_sample->data.p_sample_soun->i_sampleratehi) )
2086 MP4_Box_data_sample_soun_t *p_soun =
2087 p_sample->data.p_sample_soun;
2089 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
2090 "(%u), making both equal (report any problem).",
2091 p_track->i_timescale, p_soun->i_sampleratehi );
2093 if( p_soun->i_sampleratehi != 0 )
2094 p_track->i_timescale = p_soun->i_sampleratehi;
2096 p_soun->i_sampleratehi = p_track->i_timescale;
2101 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2102 p_track->fmt.i_codec = VLC_CODEC_H263;
2105 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2106 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2108 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2109 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2112 text_style_t *p_style = text_style_New();
2115 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2116 p_style->i_font_size = p_text->i_font_size;
2117 if ( p_text->i_font_color )
2119 p_style->i_font_color = p_text->i_font_color >> 8;
2120 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2122 if ( p_text->i_background_color[3] >> 8 )
2124 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2125 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2126 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2127 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2130 p_track->fmt.subs.p_style = p_style;
2132 /* FIXME UTF-8 doesn't work here ? */
2133 if( p_track->b_mac_encoding )
2134 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2136 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2139 case VLC_FOURCC('y','v','1','2'):
2140 p_track->fmt.i_codec = VLC_CODEC_YV12;
2142 case VLC_FOURCC('y','u','v','2'):
2143 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2146 case VLC_FOURCC('i','n','2','4'):
2147 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2148 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2150 case VLC_FOURCC('i','n','3','2'):
2151 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2152 VLC_CODEC_S32L : VLC_CODEC_S32B;
2154 case VLC_FOURCC('f','l','3','2'):
2155 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2156 VLC_CODEC_F32L : VLC_CODEC_F32B;
2158 case VLC_FOURCC('f','l','6','4'):
2159 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2160 VLC_CODEC_F64L : VLC_CODEC_F64B;
2162 case VLC_CODEC_DVD_LPCM:
2164 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2165 if( p_soun->i_qt_version == 2 &&
2166 p_soun->i_qt_description > 20 + 28 )
2173 static const struct {
2177 vlc_fourcc_t i_codec;
2179 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2180 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2181 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2182 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2184 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2185 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2187 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2188 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2189 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2190 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2192 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2193 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2194 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2195 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2197 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2198 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2199 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2200 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2204 uint32_t i_bits = GetDWBE(&p_soun->p_qt_description[20 + 20]);
2205 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
2207 for( int i = 0; p_formats[i].i_codec; i++ )
2209 if( p_formats[i].i_bits == i_bits &&
2210 (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
2212 p_track->fmt.i_codec = p_formats[i].i_codec;
2213 p_track->fmt.audio.i_bitspersample = i_bits;
2214 p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
2215 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2217 p_soun->i_qt_version = 0;
2225 p_track->fmt.i_codec = p_sample->i_type;
2229 /* now see if esds is present and if so create a data packet
2230 with decoder_specific_info */
2231 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2232 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2233 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2234 ( p_esds->data.p_esds )&&
2237 /* First update information based on i_objectTypeIndication */
2238 switch( p_decconfig->i_objectTypeIndication )
2240 case( 0x20 ): /* MPEG4 VIDEO */
2241 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2243 case( 0x21 ): /* H.264 */
2244 p_track->fmt.i_codec = VLC_CODEC_H264;
2247 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2248 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2249 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2250 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2252 p_track->fmt.i_codec = VLC_CODEC_ALS;
2260 case( 0x65): /* MPEG2 video */
2261 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2263 /* Theses are MPEG2-AAC */
2264 case( 0x66): /* main profile */
2265 case( 0x67): /* Low complexity profile */
2266 case( 0x68): /* Scaleable Sampling rate profile */
2267 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2269 /* True MPEG 2 audio */
2271 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2273 case( 0x6a): /* MPEG1 video */
2274 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2276 case( 0x6b): /* MPEG1 audio */
2277 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2279 case( 0x6c ): /* jpeg */
2280 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2282 case( 0x6d ): /* png */
2283 p_track->fmt.i_codec = VLC_CODEC_PNG;
2285 case( 0x6e ): /* jpeg2000 */
2286 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2288 case( 0xa3 ): /* vc1 */
2289 p_track->fmt.i_codec = VLC_CODEC_VC1;
2292 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2295 p_track->fmt.i_codec = VLC_CODEC_A52;
2298 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2300 case( 0xa9 ): /* dts */
2301 case( 0xaa ): /* DTS-HD HRA */
2302 case( 0xab ): /* DTS-HD Master Audio */
2303 p_track->fmt.i_codec = VLC_CODEC_DTS;
2306 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2310 case( 0xe0 ): /* NeroDigital: dvd subs */
2311 if( p_track->fmt.i_cat == SPU_ES )
2313 p_track->fmt.i_codec = VLC_CODEC_SPU;
2314 if( p_track->i_width > 0 )
2315 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2316 if( p_track->i_height > 0 )
2317 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2320 case( 0xe1 ): /* QCelp for 3gp */
2321 if( p_track->fmt.i_cat == AUDIO_ES )
2323 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2329 /* Unknown entry, but don't touch i_fourcc */
2331 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2332 p_decconfig->i_objectTypeIndication,
2333 p_track->i_track_ID );
2336 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2337 if( p_track->fmt.i_extra > 0 )
2339 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2340 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2341 p_track->fmt.i_extra );
2343 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2344 p_track->fmt.i_extra >= 16 * 4 )
2346 for( int i = 0; i < 16; i++ )
2348 p_track->fmt.subs.spu.palette[1 + i] =
2349 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2351 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2356 switch( p_sample->i_type )
2358 /* qt decoder, send the complete chunk */
2359 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2360 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2361 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2362 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2363 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2364 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2365 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2366 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2367 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2368 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2369 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2370 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2371 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2373 /* qt decoder, send the complete chunk */
2374 case VLC_CODEC_SVQ1:
2375 case VLC_CODEC_SVQ3:
2376 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2377 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2378 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2379 p_track->fmt.i_extra =
2380 p_sample->data.p_sample_vide->i_qt_image_description;
2381 if( p_track->fmt.i_extra > 0 )
2383 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2384 memcpy( p_track->fmt.p_extra,
2385 p_sample->data.p_sample_vide->p_qt_image_description,
2386 p_track->fmt.i_extra);
2390 case VLC_CODEC_AMR_NB:
2391 p_track->fmt.audio.i_rate = 8000;
2393 case VLC_CODEC_AMR_WB:
2394 p_track->fmt.audio.i_rate = 16000;
2396 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2397 case VLC_CODEC_QDM2:
2398 case VLC_CODEC_ALAC:
2399 p_track->fmt.i_extra =
2400 p_sample->data.p_sample_soun->i_qt_description;
2401 if( p_track->fmt.i_extra > 0 )
2403 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2404 memcpy( p_track->fmt.p_extra,
2405 p_sample->data.p_sample_soun->p_qt_description,
2406 p_track->fmt.i_extra);
2408 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2410 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2411 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2415 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2417 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2420 p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2421 if( p_track->fmt.i_extra > 0 )
2423 p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2424 memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2425 p_track->fmt.i_extra );
2430 msg_Err( p_demux, "missing dvc1" );
2435 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2436 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2438 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2442 p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2443 if( p_track->fmt.i_extra > 0 )
2445 p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2446 memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2447 p_track->fmt.i_extra );
2452 msg_Err( p_demux, "missing avcC" );
2456 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2457 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2459 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2463 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2464 if( p_track->fmt.i_extra > 0 )
2466 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2467 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2468 p_track->fmt.i_extra );
2470 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2474 msg_Err( p_demux, "missing hvcC" );
2480 case VLC_CODEC_ADPCM_MS:
2481 case VLC_CODEC_ADPCM_IMA_WAV:
2482 case VLC_CODEC_QCELP:
2483 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2487 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2495 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2500 /* given a time it return sample/chunk
2501 * it also update elst field of the track
2503 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2504 int64_t i_start, uint32_t *pi_chunk,
2505 uint32_t *pi_sample )
2507 demux_sys_t *p_sys = p_demux->p_sys;
2508 MP4_Box_t *p_box_stss;
2510 unsigned int i_sample;
2511 unsigned int i_chunk;
2514 /* FIXME see if it's needed to check p_track->i_chunk_count */
2515 if( p_track->i_chunk_count == 0 )
2516 return( VLC_EGENERIC );
2518 /* handle elst (find the correct one) */
2519 MP4_TrackSetELST( p_demux, p_track, i_start );
2520 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2522 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2523 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2525 /* now calculate i_start for this elst */
2527 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2535 /* to track time scale */
2536 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2537 /* add elst offset */
2538 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2539 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2540 elst->i_media_time[p_track->i_elst] > 0 )
2542 i_start += elst->i_media_time[p_track->i_elst];
2545 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2546 "ms (track)", p_track->i_elst,
2547 i_mvt * 1000 / p_sys->i_timescale,
2548 i_start * 1000 / p_track->i_timescale );
2552 /* convert absolute time to in timescale unit */
2553 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2556 /* we start from sample 0/chunk 0, hope it won't take too much time */
2557 /* *** find good chunk *** */
2558 for( i_chunk = 0; ; i_chunk++ )
2560 if( i_chunk + 1 >= p_track->i_chunk_count )
2562 /* at the end and can't check if i_start in this chunk,
2563 it will be check while searching i_sample */
2564 i_chunk = p_track->i_chunk_count - 1;
2568 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2569 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2575 /* *** find sample in the chunk *** */
2576 i_sample = p_track->chunk[i_chunk].i_sample_first;
2577 i_dts = p_track->chunk[i_chunk].i_first_dts;
2578 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2581 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2582 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2585 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2586 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2588 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2593 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2597 i_sample += ( i_start - i_dts ) /
2598 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2603 if( i_sample >= p_track->i_sample_count )
2605 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2606 "(seeking too far) chunk=%d sample=%d",
2607 p_track->i_track_ID, i_chunk, i_sample );
2608 return( VLC_EGENERIC );
2612 /* *** Try to find nearest sync points *** */
2613 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2615 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2616 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2617 p_track->i_track_ID );
2618 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2620 if( i_index >= p_stss->i_entry_count - 1 ||
2621 i_sample < p_stss->i_sample_number[i_index+1] )
2623 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2624 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2625 i_sample, i_sync_sample );
2627 if( i_sync_sample <= i_sample )
2629 while( i_chunk > 0 &&
2630 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2635 while( i_chunk < p_track->i_chunk_count - 1 &&
2636 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2637 p_track->chunk[i_chunk].i_sample_count )
2640 i_sample = i_sync_sample;
2647 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2648 "Sample Box (stss)", p_track->i_track_ID );
2651 *pi_chunk = i_chunk;
2652 *pi_sample = i_sample;
2657 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2658 unsigned int i_chunk, unsigned int i_sample )
2660 bool b_reselect = false;
2662 /* now see if actual es is ok */
2663 if( p_track->i_chunk >= p_track->i_chunk_count ||
2664 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2665 p_track->chunk[i_chunk].i_sample_description_index )
2667 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2668 p_track->i_track_ID );
2670 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2671 p_track->p_es, &b_reselect );
2673 es_out_Del( p_demux->out, p_track->p_es );
2675 p_track->p_es = NULL;
2677 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2679 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2680 p_track->i_track_ID );
2682 p_track->b_ok = false;
2683 p_track->b_selected = false;
2684 return VLC_EGENERIC;
2688 /* select again the new decoder */
2691 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2694 p_track->i_chunk = i_chunk;
2695 p_track->i_sample = i_sample;
2697 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2700 /****************************************************************************
2702 ****************************************************************************
2703 * Parse track information and create all needed data to run a track
2704 * If it succeed b_ok is set to 1 else to 0
2705 ****************************************************************************/
2706 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2707 MP4_Box_t *p_box_trak,
2708 bool b_force_enable )
2710 demux_sys_t *p_sys = p_demux->p_sys;
2712 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2713 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2723 char language[4] = { '\0' };
2725 /* hint track unsupported */
2727 /* set default value (-> track unusable) */
2728 p_track->b_ok = false;
2729 p_track->b_enable = false;
2730 p_track->b_selected = false;
2731 p_track->b_chapter = false;
2732 p_track->b_mac_encoding = false;
2734 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2741 /* do we launch this track by default ? */
2743 ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2744 if( !p_track->b_enable )
2745 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2747 p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2749 p_track->i_width = p_tkhd->data.p_tkhd->i_width / BLOCK16x16;
2750 p_track->i_height = p_tkhd->data.p_tkhd->i_height / BLOCK16x16;
2751 p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2755 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2758 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2759 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2761 if( ( !p_mdhd )||( !p_hdlr ) )
2766 p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2767 if( p_track->i_timescale == 0 )
2770 if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2772 strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2773 p_track->b_mac_encoding = true;
2775 else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2776 p_track->b_mac_encoding = true;
2779 for( unsigned i = 0; i < 3; i++ )
2780 language[i] = p_mdhd->data.p_mdhd->i_language[i];
2784 switch( p_hdlr->data.p_hdlr->i_handler_type )
2787 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2791 p_track->fmt.i_cat = AUDIO_ES;
2795 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2799 p_track->fmt.i_cat = VIDEO_ES;
2806 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2807 p_track->fmt.i_cat = SPU_ES;
2814 p_track->i_elst = 0;
2815 p_track->i_elst_time = 0;
2816 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2818 MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2821 msg_Warn( p_demux, "elst box found" );
2822 for( i = 0; i < elst->i_entry_count; i++ )
2824 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2825 "ms) rate=%d.%d", i,
2826 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2827 elst->i_media_time[i] >= 0 ?
2828 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2830 elst->i_media_rate_integer[i],
2831 elst->i_media_rate_fraction[i] );
2838 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2840 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2841 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2847 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2849 p_track->fmt.psz_language = strdup( language );
2852 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2855 MP4_Box_t *p_box_iter;
2856 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2857 p_box_iter = p_box_iter->p_next )
2859 switch( p_box_iter->i_type )
2862 p_track->fmt.psz_description =
2863 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2866 p_track->fmt.psz_description =
2867 strdup( p_box_iter->data.p_name->psz_text );
2873 /* Create chunk index table and sample index table */
2874 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2875 TrackCreateSamplesIndex( p_demux, p_track ) )
2877 return; /* cannot create chunks index */
2880 p_track->i_chunk = 0;
2881 p_track->i_sample = 0;
2883 /* Mark chapter only track */
2884 if( p_sys->p_tref_chap )
2886 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2889 for( i = 0; i < p_chap->i_entry_count; i++ )
2891 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2892 p_track->fmt.i_cat == UNKNOWN_ES )
2894 p_track->b_chapter = true;
2895 p_track->b_enable = false;
2902 if( b_force_enable &&
2903 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2905 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2906 p_track->i_track_ID );
2907 p_track->b_enable = true;
2908 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2911 p_track->p_es = NULL;
2912 if( TrackCreateES( p_demux,
2913 p_track, p_track->i_chunk,
2914 p_track->b_chapter ? NULL : &p_track->p_es ) )
2916 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2917 p_track->i_track_ID );
2920 p_track->b_ok = true;
2924 for( i = 0; i < p_track->i_chunk_count; i++ )
2926 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2927 i, p_track->chunk[i].i_sample_count,
2928 p_track->chunk[i].i_first_dts );
2935 static void FreeAndResetChunk( mp4_chunk_t *ck )
2937 free( ck->p_sample_count_dts );
2938 free( ck->p_sample_delta_dts );
2939 free( ck->p_sample_count_pts );
2940 free( ck->p_sample_offset_pts );
2941 free( ck->p_sample_size );
2942 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2943 free( ck->p_sample_data[i] );
2944 free( ck->p_sample_data );
2945 memset( ck, 0, sizeof( mp4_chunk_t ) );
2948 /****************************************************************************
2950 ****************************************************************************
2951 * Destroy a track created by MP4_TrackCreate.
2952 ****************************************************************************/
2953 static void MP4_TrackDestroy( mp4_track_t *p_track )
2955 unsigned int i_chunk;
2957 p_track->b_ok = false;
2958 p_track->b_enable = false;
2959 p_track->b_selected = false;
2961 es_format_Clean( &p_track->fmt );
2963 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2965 if( p_track->chunk )
2967 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2968 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2970 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2971 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2974 FREENULL( p_track->chunk );
2975 if( p_track->cchunk ) {
2976 FreeAndResetChunk( p_track->cchunk );
2977 FREENULL( p_track->cchunk );
2980 if( !p_track->i_sample_size )
2982 FREENULL( p_track->p_sample_size );
2986 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2989 if( !p_track->b_ok || p_track->b_chapter )
2991 return VLC_EGENERIC;
2994 if( p_track->b_selected )
2996 msg_Warn( p_demux, "track[Id 0x%x] already selected",
2997 p_track->i_track_ID );
3001 return MP4_TrackSeek( p_demux, p_track, i_start );
3004 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3006 if( !p_track->b_ok || p_track->b_chapter )
3011 if( !p_track->b_selected )
3013 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3014 p_track->i_track_ID );
3019 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3020 p_track->p_es, false );
3023 p_track->b_selected = false;
3026 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3032 if( !p_track->b_ok || p_track->b_chapter )
3033 return VLC_EGENERIC;
3035 p_track->b_selected = false;
3037 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3038 &i_chunk, &i_sample ) )
3040 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3041 p_track->i_track_ID );
3042 return VLC_EGENERIC;
3045 p_track->b_selected = true;
3047 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3048 p_track->b_selected = true;
3050 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3055 * 3 types: for audio
3058 #define QT_V0_MAX_SAMPLES 1024
3059 static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3062 MP4_Box_data_sample_soun_t *p_soun;
3064 if( p_track->i_sample_size == 0 )
3066 /* most simple case */
3067 return p_track->p_sample_size[p_track->i_sample];
3069 if( p_track->fmt.i_cat != AUDIO_ES )
3071 return p_track->i_sample_size;
3074 p_soun = p_track->p_sample->data.p_sample_soun;
3076 if( p_soun->i_qt_version == 1 )
3078 uint32_t i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
3079 if( p_track->fmt.audio.i_blockalign > 1 )
3080 i_samples = p_soun->i_sample_per_packet;
3082 i_size = i_samples / p_soun->i_sample_per_packet;
3083 if ( UINT32_MAX / i_size < p_soun->i_bytes_per_frame )
3084 i_size *= p_soun->i_bytes_per_frame;
3086 i_size = UINT32_MAX;
3088 else if( p_track->i_sample_size > 256 )
3090 /* We do that so we don't read too much data
3091 * (in this case we are likely dealing with compressed data) */
3092 i_size = p_track->i_sample_size;
3096 mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3097 int64_t i_length = CLOCK_FREQ / 10;
3098 uint32_t i_samples = 0;
3099 uint32_t i_maxsamples = 0;
3100 for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
3102 i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
3103 if ( i_length < 0 ) break;
3107 i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
3108 i_samples = __MIN( i_maxsamples, i_samples );
3109 if ( i_samples == 0 ) i_samples = 1;
3110 i_size = i_samples * p_track->i_sample_size;
3111 *pi_nb_samples = i_samples;
3114 //fprintf( stderr, "size=%d\n", i_size );
3118 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3120 unsigned int i_sample;
3123 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3125 if( p_track->i_sample_size )
3127 MP4_Box_data_sample_soun_t *p_soun =
3128 p_track->p_sample->data.p_sample_soun;
3130 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3132 i_pos += ( p_track->i_sample -
3133 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3134 p_track->i_sample_size;
3138 /* we read chunk by chunk unless a blockalign is requested */
3139 if( p_track->fmt.audio.i_blockalign > 1 )
3140 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3141 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3146 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3147 i_sample < p_track->i_sample; i_sample++ )
3149 i_pos += p_track->p_sample_size[i_sample];
3156 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3158 if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
3160 MP4_Box_data_sample_soun_t *p_soun;
3162 p_soun = p_track->p_sample->data.p_sample_soun;
3164 if( p_soun->i_qt_version == 1 )
3166 /* we read chunk by chunk unless a blockalign is requested */
3167 if( p_track->fmt.audio.i_blockalign > 1 )
3168 p_track->i_sample += p_soun->i_sample_per_packet;
3170 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
3172 else if( p_track->i_sample_size > 256 )
3174 /* We do that so we don't read too much data
3175 * (in this case we are likely dealing with compressed data) */
3176 p_track->i_sample += 1;
3181 p_track->i_sample += i_samples;
3182 if( p_track->i_sample >
3183 p_track->chunk[p_track->i_chunk].i_sample_first +
3184 p_track->chunk[p_track->i_chunk].i_sample_count )
3187 p_track->chunk[p_track->i_chunk].i_sample_first +
3188 p_track->chunk[p_track->i_chunk].i_sample_count;
3194 p_track->i_sample++;
3197 if( p_track->i_sample >= p_track->i_sample_count )
3198 return VLC_EGENERIC;
3200 /* Have we changed chunk ? */
3201 if( p_track->i_sample >=
3202 p_track->chunk[p_track->i_chunk].i_sample_first +
3203 p_track->chunk[p_track->i_chunk].i_sample_count )
3205 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3206 p_track->i_sample ) )
3208 msg_Warn( p_demux, "track[0x%x] will be disabled "
3209 "(cannot restart decoder)", p_track->i_track_ID );
3210 MP4_TrackUnselect( p_demux, p_track );
3211 return VLC_EGENERIC;
3215 /* Have we changed elst */
3216 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
3218 demux_sys_t *p_sys = p_demux->p_sys;
3219 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
3220 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3221 p_sys->i_timescale / CLOCK_FREQ;
3223 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3224 i_mvt >= p_track->i_elst_time +
3225 elst->i_segment_duration[p_track->i_elst] )
3227 MP4_TrackSetELST( p_demux, p_track,
3228 MP4_TrackGetDTS( p_demux, p_track ) );
3235 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3238 demux_sys_t *p_sys = p_demux->p_sys;
3239 int i_elst_last = tk->i_elst;
3241 /* handle elst (find the correct one) */
3243 tk->i_elst_time = 0;
3244 if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
3246 MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
3247 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3249 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3251 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3253 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3257 tk->i_elst_time += i_dur;
3260 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3262 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3263 tk->i_elst = elst->i_entry_count - 1;
3264 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3267 if( elst->i_media_time[tk->i_elst] < 0 )
3270 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3273 if( i_elst_last != tk->i_elst )
3275 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3280 static const char *MP4_ConvertMacCode( uint16_t i_code )
3282 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3283 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3284 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3285 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3286 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3287 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3288 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3289 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3290 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3291 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3292 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3293 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3294 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3295 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3296 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3297 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3298 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3299 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3300 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3301 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3303 { "cy", 128 }, { "eu", 129 },
3304 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3305 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3306 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3307 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3312 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3314 if( p_cvt[i].i_code == i_code )
3315 return p_cvt[i].psz_iso639_1;
3320 /******************************************************************************
3321 * Here are the functions used for fragmented MP4
3322 *****************************************************************************/
3325 * It computes the sample rate for a video track using current video chunk
3327 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3328 const mp4_track_t *p_track )
3330 if( p_track->cchunk->i_last_dts == 0 )
3337 const mp4_chunk_t *p_chunk = p_track->cchunk;
3339 uint32_t i_sample = p_chunk->i_sample_count;
3340 uint64_t i_first_dts = p_chunk->i_first_dts;
3341 uint64_t i_last_dts = p_chunk->i_last_dts;
3343 if( i_sample > 1 && i_first_dts < i_last_dts )
3344 vlc_ureduce( pi_num, pi_den,
3345 ( i_sample - 1) * p_track->i_timescale,
3346 i_last_dts - i_first_dts,
3351 * Build raw avcC box (without the 8 bytes header)
3352 * \return The size of the box.
3354 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3355 const unsigned cpd_len )
3358 unsigned sps_len = 0, pps_len = 0;
3359 const uint32_t mark = 0x00000001;
3361 assert( CodecPrivateData[0] == 0 );
3362 assert( CodecPrivateData[1] == 0 );
3363 assert( CodecPrivateData[2] == 0 );
3364 assert( CodecPrivateData[3] == 1 );
3366 uint32_t length = cpd_len + 3;
3367 avcC = calloc( length, 1 );
3368 if( unlikely( avcC == NULL ) )
3371 uint8_t *sps = avcC + 8;
3373 uint32_t candidate = ~mark;
3374 CodecPrivateData += 4;
3375 for( unsigned i = 0; i < cpd_len - 4; i++ )
3377 sps[i] = CodecPrivateData[i];
3378 candidate = (candidate << 8) | CodecPrivateData[i];
3379 if( candidate == mark )
3390 uint8_t *pps = sps + sps_len + 3;
3391 pps_len = cpd_len - sps_len - 4 * 2;
3392 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3395 uint8_t AVCProfileIndication = 0x64;
3396 uint8_t profile_compatibility = 0x40;
3397 uint8_t AVCLevelIndication = 0x1f;
3398 uint8_t lengthSizeMinusOne = 0x03;
3401 avcC[1] = AVCProfileIndication;
3402 avcC[2] = profile_compatibility;
3403 avcC[3] = AVCLevelIndication;
3404 avcC[4] = 0xfc + lengthSizeMinusOne;
3406 avcC[6] = (sps_len & 0xff00)>>8;
3407 avcC[7] = sps_len & 0xff;
3409 avcC[8+sps_len] = 1;
3410 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3411 avcC[10+sps_len] = pps_len & 0xff;
3418 * Build a mp4_track_t from a StraBox
3421 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3423 fmt->i_extra = p_data->cpd_len;
3424 fmt->p_extra = malloc( p_data->cpd_len );
3425 if( unlikely( !fmt->p_extra ) )
3427 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3431 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3433 demux_sys_t *p_sys = p_demux->p_sys;
3435 MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3437 return VLC_EGENERIC;
3439 p_track->b_ok = true;
3440 p_track->b_selected = false;
3441 p_track->i_sample_count = UINT32_MAX;
3443 p_track->i_timescale = p_sys->i_timescale;
3444 p_track->i_width = p_data->MaxWidth;
3445 p_track->i_height = p_data->MaxHeight;
3446 p_track->i_track_ID = p_data->i_track_ID;
3448 es_format_t *fmt = &p_track->fmt;
3450 return VLC_EGENERIC;
3452 es_format_Init( fmt, p_data->i_es_cat, 0 );
3454 /* Set language FIXME */
3455 fmt->psz_language = strdup( "en" );
3457 fmt->i_original_fourcc = p_data->FourCC;
3458 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3460 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3461 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3462 * for MS weird use of FourCC*/
3463 switch( fmt->i_cat )
3466 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3467 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3468 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3470 fmt->i_extra = build_raw_avcC( p_extra,
3471 p_data->CodecPrivateData, p_data->cpd_len );
3475 ret = MP4_SetCodecExtraData( fmt, p_data );
3476 if( ret != VLC_SUCCESS )
3480 fmt->video.i_width = p_data->MaxWidth;
3481 fmt->video.i_height = p_data->MaxHeight;
3482 fmt->video.i_bits_per_pixel = 0x18;
3483 fmt->video.i_visible_width = p_data->MaxWidth;
3484 fmt->video.i_visible_height = p_data->MaxHeight;
3487 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3488 &fmt->video.i_frame_rate_base, p_track );
3490 if( fmt->video.i_frame_rate_base != 0 )
3492 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3493 (float)fmt->video.i_frame_rate_base;
3496 p_demux->p_sys->f_fps = 24;
3501 fmt->audio.i_channels = p_data->Channels;
3502 fmt->audio.i_rate = p_data->SamplingRate;
3503 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3504 fmt->audio.i_blockalign = p_data->nBlockAlign;
3506 fmt->i_bitrate = p_data->Bitrate;
3508 ret = MP4_SetCodecExtraData( fmt, p_data );
3509 if( ret != VLC_SUCCESS )
3522 * Return the track identified by tid
3524 static mp4_track_t *MP4_frg_GetTrack( demux_t *p_demux, const uint32_t tid )
3526 demux_sys_t *p_sys = p_demux->p_sys;
3528 mp4_track_t *ret = NULL;
3529 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3531 ret = &p_sys->track[i];
3534 if( ret->i_track_ID == tid )
3537 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3541 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3543 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3544 mp4_chunk_t *ck = tk->cchunk;
3545 while( ck->i_sample < ck->i_sample_count )
3550 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3553 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3554 assert( sample_size > 0 );
3555 p_block = block_Alloc( sample_size );
3556 if( unlikely( !p_block ) )
3559 uint8_t *src = ck->p_sample_data[ck->i_sample];
3560 memcpy( p_block->p_buffer, src, sample_size );
3564 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3566 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3568 p_block->i_pts = p_block->i_dts + i_delta;
3569 else if( tk->fmt.i_cat != VIDEO_ES )
3570 p_block->i_pts = p_block->i_dts;
3572 p_block->i_pts = VLC_TS_INVALID;
3574 es_out_Send( p_demux->out, tk->p_es, p_block );
3582 * \Note If we call that function too soon,
3583 * before the track has been selected by MP4_TrackSelect
3584 * (during the first execution of Demux), then the track gets disabled
3586 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3588 demux_sys_t *p_sys = p_demux->p_sys;
3590 uint32_t i_sample = 0;
3591 bool b_smooth = false;
3592 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3594 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3599 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3600 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3601 return VLC_EGENERIC;
3605 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3607 return VLC_EGENERIC;
3610 i_sample = p_track->i_sample;
3611 es_out_Del( p_demux->out, p_track->p_es );
3612 es_format_Clean( &p_track->fmt );
3615 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3617 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3619 p_track->i_sample = i_sample;
3621 /* Temporary hack until we support track selection */
3622 p_track->b_selected = true;
3623 p_track->b_ok = true;
3624 p_track->b_enable = true;
3626 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3627 p_track->b_codec_need_restart = false;
3633 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3634 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3635 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3636 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3638 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3640 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3641 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3644 msg_Warn( p_demux, "no moof box found!" );
3645 return VLC_EGENERIC;
3648 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3651 msg_Warn( p_demux, "no traf box found!" );
3652 return VLC_EGENERIC;
3655 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3658 msg_Warn( p_demux, "no tfhd box found!" );
3659 return VLC_EGENERIC;
3662 uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3663 *i_tk_id = i_track_ID;
3664 assert( i_track_ID > 0 );
3665 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3667 mp4_track_t *p_track = MP4_frg_GetTrack( p_demux, i_track_ID );
3669 return VLC_EGENERIC;
3671 mp4_chunk_t *ret = p_track->cchunk;
3673 if( p_tfhd->data.p_tfhd->b_empty )
3674 msg_Warn( p_demux, "No samples in this chunk!" );
3676 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3677 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3678 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3679 * and so on. Finally, suppose that we get the chunks the other way around,
3680 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3681 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3682 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3683 * flush it, i.e. send to the decoder the samples not yet sent.
3684 * Note that all the samples to be flushed should worth less than 100 ms,
3685 * (though I did not do the formal proof) and thus this flushing mechanism
3686 * should not cause A/V sync issues, or delays or whatever.
3688 if( ret->i_sample < ret->i_sample_count )
3689 FlushChunk( p_demux, p_track );
3691 if( ret->i_sample_count )
3692 FreeAndResetChunk( ret );
3694 uint32_t default_duration = 0;
3695 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3696 default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3698 uint32_t default_size = 0;
3699 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3700 default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3702 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3705 msg_Warn( p_demux, "no trun box found!" );
3706 return VLC_EGENERIC;
3708 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3710 ret->i_sample_count = p_trun_data->i_sample_count;
3711 assert( ret->i_sample_count > 0 );
3712 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3713 ret->i_sample_first = p_track->i_sample_first;
3714 p_track->i_sample_first += ret->i_sample_count;
3716 ret->i_first_dts = p_track->i_first_dts;
3718 /* XXX I already saw DASH content with no default_duration and no
3719 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3720 * This chunk of code might be buggy with segments having
3721 * more than one subsegment. */
3722 if( !default_duration )
3724 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
3727 while( p_trex && p_trex->data.p_trex->i_track_ID != i_track_ID )
3728 p_trex = p_trex->p_next;
3730 default_duration = p_trex->data.p_trex->i_default_sample_duration;
3734 MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3735 assert( p_sidx_data->i_reference_count == 1 );
3737 if( p_sidx_data->i_timescale == 0 )
3738 return VLC_EGENERIC;
3740 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3741 p_sidx_data->i_timescale;
3742 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3747 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3749 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3750 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3752 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3755 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3756 if( !ret->p_sample_count_pts )
3759 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3761 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3762 if( !ret->p_sample_offset_pts )
3766 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3767 if( !ret->p_sample_size )
3770 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3771 if( !ret->p_sample_data )
3774 uint32_t dur = 0, i_mdatlen = 0, len;
3775 uint32_t chunk_duration = 0, chunk_size = 0;
3777 /* Skip header of mdat */
3779 int i_read = stream_Read( p_demux->s, &mdat, 8 );
3780 i_mdatlen = GetDWBE( mdat );
3781 if ( i_read < 8 || i_mdatlen < 8 ||
3782 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
3783 return VLC_EGENERIC;
3785 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3787 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3788 dur = p_trun_data->p_samples[i].i_duration;
3790 dur = default_duration;
3791 ret->p_sample_delta_dts[i] = dur;
3792 chunk_duration += dur;
3794 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3796 if( ret->p_sample_offset_pts )
3798 ret->p_sample_offset_pts[i] =
3799 p_trun_data->p_samples[i].i_composition_time_offset;
3802 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3803 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3805 len = ret->p_sample_size[i] = default_size;
3807 if ( chunk_size + len > ( i_mdatlen - 8 ) )
3808 return VLC_EGENERIC;
3810 ret->p_sample_data[i] = malloc( len );
3811 if( ret->p_sample_data[i] == NULL )
3813 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
3815 return VLC_EGENERIC;
3818 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3819 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3821 if( p_track->b_codec_need_restart &&
3822 p_track->fmt.i_cat == VIDEO_ES )
3823 ReInitDecoder( p_demux, p_track );
3825 /* Skip if we didn't reach the end of mdat box */
3826 if ( chunk_size < (i_mdatlen - 8) )
3827 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
3829 p_track->b_has_non_empty_cchunk = true;
3834 * Get the next chunk of the track identified by i_tk_id.
3835 * \Note We don't want to seek all the time, so if the first chunk given by the
3836 * input method doesn't belong to the right track, we don't throw it away,
3837 * and so, in general, this function fetch more than one chunk.
3838 * Not to mention that a new init segment might be put everywhere
3839 * between two chunks by the input method.
3841 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3843 demux_sys_t *p_sys = p_demux->p_sys;
3844 mp4_track_t *p_track;
3846 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3848 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3850 return VLC_EGENERIC;
3852 if( !p_chunk->p_first )
3853 goto MP4_frg_GetChunks_Error;
3854 uint32_t i_type = p_chunk->p_first->i_type;
3856 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3858 MP4_BoxFree( p_demux->s, p_sys->p_root );
3859 p_sys->p_root = p_chunk;
3861 if( i_type == ATOM_ftyp ) /* DASH */
3863 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3866 msg_Warn( p_demux, "No tkhd found!" );
3867 goto MP4_frg_GetChunks_Error;
3869 tid = p_tkhd->data.p_tkhd->i_track_ID;
3871 else /* Smooth Streaming */
3873 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3874 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3875 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3877 msg_Warn( p_demux, "No StraBox found!" );
3878 goto MP4_frg_GetChunks_Error;
3880 tid = p_stra->data.p_stra->i_track_ID;
3883 p_track = MP4_frg_GetTrack( p_demux, tid );
3885 goto MP4_frg_GetChunks_Error;
3886 p_track->b_codec_need_restart = true;
3888 return MP4_frg_GetChunks( p_demux, i_tk_id );
3891 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3892 goto MP4_frg_GetChunks_Error;
3894 MP4_BoxFree( p_demux->s, p_chunk );
3896 if( tid == i_tk_id )
3901 MP4_frg_GetChunks_Error:
3902 MP4_BoxFree( p_demux->s, p_chunk );
3903 return VLC_EGENERIC;
3909 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3911 if( !p_track->b_ok || p_track->b_chapter )
3913 return VLC_EGENERIC;
3916 if( p_track->b_selected )
3918 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3922 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3923 p_track->b_selected = true;
3928 * DemuxFrg: read packet and send them to decoders
3929 * \return 1 on success, 0 on error.
3930 * TODO check for newly selected track
3932 int DemuxFrg( demux_t *p_demux )
3934 demux_sys_t *p_sys = p_demux->p_sys;
3936 unsigned i_track_selected;
3938 /* check for newly selected/unselected track */
3939 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3941 mp4_track_t *tk = &p_sys->track[i_track];
3944 if( !tk->b_ok || tk->b_chapter )
3947 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3948 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3950 if( tk->b_selected && !b )
3952 MP4_TrackUnselect( p_demux, tk );
3954 else if( !tk->b_selected && b)
3956 MP4_frg_TrackSelect( p_demux, tk );
3959 if( tk->b_selected )
3963 if( i_track_selected <= 0 )
3965 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3966 if( p_sys->i_timescale > 0 )
3968 int64_t i_length = CLOCK_FREQ *
3969 (mtime_t)p_sys->i_duration /
3970 (mtime_t)p_sys->i_timescale;
3971 if( MP4_GetMoviePTS( p_sys ) >= i_length )
3976 msg_Warn( p_demux, "no track selected, exiting..." );
3980 /* first wait for the good time to read a packet */
3981 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3983 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3985 /* we will read 100ms for each stream so ...*/
3986 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3988 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3990 mp4_track_t *tk = &p_sys->track[i_track];
3992 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3994 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3998 if( !tk->b_has_non_empty_cchunk )
4000 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4002 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4007 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4012 mp4_chunk_t *ck = tk->cchunk;
4013 if( ck->i_sample >= ck->i_sample_count )
4015 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4016 ck->i_sample, ck->i_sample_count );
4020 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4021 p_block = block_Alloc( sample_size );
4022 uint8_t *src = ck->p_sample_data[ck->i_sample];
4023 memcpy( p_block->p_buffer, src, sample_size );
4026 if( ck->i_sample == ck->i_sample_count )
4027 tk->b_has_non_empty_cchunk = false;
4030 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4032 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4034 p_block->i_pts = p_block->i_dts + i_delta;
4035 else if( tk->fmt.i_cat != VIDEO_ES )
4036 p_block->i_pts = p_block->i_dts;
4038 p_block->i_pts = VLC_TS_INVALID;
4040 es_out_Send( p_demux->out, tk->p_es, p_block );
4044 if( !tk->b_has_non_empty_cchunk )