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 uint32_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 bool b_smooth; /* Is it Smooth Streaming? */
87 MP4_Box_t *p_tref_chap;
90 input_title_t *p_title;
93 #define BOXDATA(type) type->data.type
95 /*****************************************************************************
96 * Declaration of local function
97 *****************************************************************************/
98 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
99 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
100 static void MP4_TrackDestroy( mp4_track_t * );
102 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
103 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
105 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
107 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
108 static uint32_t MP4_TrackSampleSize( mp4_track_t *, uint32_t * );
109 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
110 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
112 static void MP4_UpdateSeekpoint( demux_t * );
113 static const char *MP4_ConvertMacCode( uint16_t );
115 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
117 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
119 uint32_t i_return = 0;
120 if ( i_toread > INT32_MAX )
122 i_return = stream_Read( s, p_read, INT32_MAX );
123 if ( i_return < INT32_MAX )
126 i_toread -= INT32_MAX;
128 i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
132 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
134 MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
137 if ( p_trex->i_type == ATOM_trex && BOXDATA(p_trex)->i_track_ID == i_id )
140 p_trex = p_trex->p_next;
145 /* Return time in microsecond of a track */
146 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
148 demux_sys_t *p_sys = p_demux->p_sys;
150 if( p_sys->b_fragmented )
151 chunk = *p_track->cchunk;
153 chunk = p_track->chunk[p_track->i_chunk];
155 unsigned int i_index = 0;
156 unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
157 int64_t i_dts = chunk.i_first_dts;
159 while( i_sample > 0 )
161 if( i_sample > chunk.p_sample_count_dts[i_index] )
163 i_dts += chunk.p_sample_count_dts[i_index] *
164 chunk.p_sample_delta_dts[i_index];
165 i_sample -= chunk.p_sample_count_dts[i_index];
170 i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
175 /* now handle elst */
176 if( p_track->p_elst )
178 demux_sys_t *p_sys = p_demux->p_sys;
179 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
181 /* convert to offset */
182 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
183 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
184 elst->i_media_time[p_track->i_elst] > 0 )
186 i_dts -= elst->i_media_time[p_track->i_elst];
189 /* add i_elst_time */
190 i_dts += p_track->i_elst_time * p_track->i_timescale /
193 if( i_dts < 0 ) i_dts = 0;
196 return CLOCK_FREQ * i_dts / p_track->i_timescale;
199 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
201 demux_sys_t *p_sys = p_demux->p_sys;
203 if( p_sys->b_fragmented )
204 ck = p_track->cchunk;
206 ck = &p_track->chunk[p_track->i_chunk];
208 unsigned int i_index = 0;
209 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
211 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
214 for( i_index = 0;; i_index++ )
216 if( i_sample < ck->p_sample_count_pts[i_index] )
217 return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
218 (int64_t)p_track->i_timescale;
220 i_sample -= ck->p_sample_count_pts[i_index];
224 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
226 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
229 static void LoadChapter( demux_t *p_demux );
231 static int LoadInitFrag( demux_t *p_demux )
233 demux_sys_t *p_sys = p_demux->p_sys;
235 if( p_sys->b_smooth ) /* Smooth Streaming */
237 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
239 goto LoadInitFragError;
243 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
244 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
245 goto LoadInitFragError;
246 /* Get number of tracks */
248 for( int i = 0; i < 3; i++ )
250 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
251 if( p_stra && BOXDATA(p_stra)->i_track_ID )
253 /* Get timescale and duration of the video track; */
254 if( p_sys->i_timescale == 0 )
256 p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
257 p_sys->i_duration = BOXDATA(p_stra)->i_duration;
258 if( p_sys->i_timescale == 0 )
260 msg_Err( p_demux, "bad timescale" );
261 goto LoadInitFragError;
269 /* Load all boxes ( except raw data ) */
270 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
272 goto LoadInitFragError;
278 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
282 /* Does lookup for remaining boxes */
283 static int ProbeFragments( demux_t *p_demux )
285 demux_sys_t *p_sys = p_demux->p_sys;
287 msg_Dbg( p_demux, "probing fragments from %"PRId64, stream_Tell( p_demux->s ) );
289 MP4_ReadBoxContainerRaw( p_demux->s, p_sys->p_root );
294 static int InitTracks( demux_t *p_demux )
296 demux_sys_t *p_sys = p_demux->p_sys;
298 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
299 if( p_sys->track == NULL )
302 if( p_sys->b_fragmented )
304 mp4_track_t *p_track;
305 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
307 p_track = &p_sys->track[i];
308 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
309 if( unlikely( !p_track->cchunk ) )
311 free( p_sys->track );
319 static void CreateTracksFromSmooBox( demux_t *p_demux )
321 demux_sys_t *p_sys = p_demux->p_sys;
323 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
324 mp4_track_t *p_track;
326 for( int i = 0; i < 3; i++ )
328 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
329 if( !p_stra || BOXDATA(p_stra)->i_track_ID == 0 )
333 p_track = &p_sys->track[j]; j++;
334 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
335 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
340 /*****************************************************************************
341 * Open: check file and initializes MP4 structures
342 *****************************************************************************/
343 static int Open( vlc_object_t * p_this )
345 demux_t *p_demux = (demux_t *)p_this;
348 const uint8_t *p_peek;
358 /* A little test to see if it could be a mp4 */
359 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
361 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
372 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
375 /* We don't yet support f4v, but avformat does. */
376 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
383 /* create our structure that will contains all data */
384 p_sys = calloc( 1, sizeof( demux_sys_t ) );
389 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
390 if( !p_sys->b_seekable )
392 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
396 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
398 /*Set exported functions */
399 p_demux->pf_demux = Demux;
400 p_demux->pf_control = Control;
402 p_demux->p_sys = p_sys;
404 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
405 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
407 p_sys->b_smooth = true;
408 p_sys->b_fragmented = true;
411 if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
414 /* LoadInitFrag early failed */
415 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
417 if ( p_sys->b_seekable )
419 /* Probe remaining to check if there's really fragments
420 or if that file is just ready to append fragments */
421 ProbeFragments( p_demux );
422 p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
425 p_sys->b_fragmented = true;
428 if( p_sys->b_fragmented )
430 p_demux->pf_demux = DemuxFrg;
433 if( p_sys->b_smooth )
435 if( InitTracks( p_demux ) != VLC_SUCCESS )
437 CreateTracksFromSmooBox( p_demux );
440 else if( p_sys->b_fragmented )
442 /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
443 * a file, and we let avformat do the job. */
444 msg_Warn( p_demux, "MP4 plugin discarded "\
445 "(fragmented, let avformat demux it)" );
446 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
450 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
452 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
454 switch( BOXDATA(p_ftyp)->i_major_brand )
458 "ISO Media file (isom) version %d.",
459 BOXDATA(p_ftyp)->i_minor_version );
462 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
463 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
464 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
465 msg_Dbg( p_demux, "3GPP Media file Release: %c",
466 #ifdef WORDS_BIGENDIAN
467 BOXDATA(p_ftyp)->i_major_brand
469 BOXDATA(p_ftyp)->i_major_brand >> 24
473 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
474 msg_Dbg( p_demux, "Apple QuickTime file" );
476 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
477 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
481 "unrecognized major file specification (%4.4s).",
482 (char*)&BOXDATA(p_ftyp)->i_major_brand );
488 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
491 /* the file need to have one moov box */
492 if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
494 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
498 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
501 /* we have a free box as a moov, rename it */
502 p_foov->i_type = ATOM_moov;
505 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
507 int i_count = MP4_BoxCount( p_rmra, "rmda" );
510 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
512 input_thread_t *p_input = demux_GetParentInput( p_demux );
513 input_item_t *p_current = input_GetItem( p_input );
515 input_item_node_t *p_subitems = input_item_node_Create( p_current );
517 for( i = 0; i < i_count; i++ )
519 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
523 if( !p_rdrf || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
527 i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
529 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
530 psz_ref, (char*)&i_ref_type );
532 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
534 if( strstr( psz_ref, "qt5gateQT" ) )
536 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
539 if( !strncmp( psz_ref, "http://", 7 ) ||
540 !strncmp( psz_ref, "rtsp://", 7 ) )
547 char *psz_path = strdup( p_demux->psz_location );
548 char *end = strrchr( psz_path, '/' );
549 if( end ) end[1] = '\0';
550 else *psz_path = '\0';
552 if( asprintf( &psz_absolute, "%s://%s%s",
553 p_demux->psz_access, psz_path, psz_ref ) < 0 )
557 input_item_node_Delete( p_subitems );
558 vlc_object_release( p_input) ;
563 psz_ref = psz_absolute;
566 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
567 input_item_t *p_item = input_item_New( psz_ref, NULL );
568 input_item_CopyOptions( p_current, p_item );
569 input_item_node_AppendItem( p_subitems, p_item );
570 vlc_gc_decref( p_item );
574 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
575 (char*)&BOXDATA(p_rdrf)->i_ref_type );
579 input_item_node_PostAndDelete( p_subitems );
580 vlc_object_release( p_input );
583 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
587 msg_Err( p_demux, "cannot find /moov/mvhd" );
592 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
593 p_demux->pf_demux = DemuxRef;
599 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
600 if( p_sys->i_timescale == 0 )
602 msg_Err( p_this, "bad timescale" );
605 p_sys->i_duration = BOXDATA(p_mvhd)->i_duration;
608 /* Try in mehd if fragmented */
609 if ( p_sys->i_duration == 0 )
611 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
613 p_sys->i_duration = BOXDATA(p_mehd)->i_fragment_duration;
616 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
618 msg_Err( p_demux, "cannot find any /moov/trak" );
621 msg_Dbg( p_demux, "found %d track%c",
623 p_sys->i_tracks ? 's':' ' );
625 if( InitTracks( p_demux ) != VLC_SUCCESS )
628 /* Search the first chap reference (like quicktime) and
629 * check that at least 1 stream is enabled */
630 p_sys->p_tref_chap = NULL;
631 b_enabled_es = false;
632 for( i = 0; i < p_sys->i_tracks; i++ )
634 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
637 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
638 if( p_tkhd && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
641 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
642 if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
643 p_sys->p_tref_chap = p_chap;
646 /* now process each track and extract all useful information */
647 for( i = 0; i < p_sys->i_tracks; i++ )
649 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
650 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
652 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
655 switch( p_sys->track[i].fmt.i_cat )
664 psz_cat = "subtitle";
672 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
673 p_sys->track[i].i_track_ID, psz_cat,
674 p_sys->track[i].b_enable ? "enable":"disable",
675 p_sys->track[i].fmt.psz_language ?
676 p_sys->track[i].fmt.psz_language : "undef" );
678 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
680 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
681 p_sys->track[i].i_track_ID,
682 p_sys->track[i].fmt.psz_language ?
683 p_sys->track[i].fmt.psz_language : "undef" );
687 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
688 p_sys->track[i].i_track_ID );
693 LoadChapter( p_demux );
700 MP4_BoxFree( p_demux->s, p_sys->p_root );
706 /*****************************************************************************
707 * Demux: read packet and send them to decoders
708 *****************************************************************************
709 * TODO check for newly selected track (ie audio upt to now )
710 *****************************************************************************/
711 static int Demux( demux_t *p_demux )
713 demux_sys_t *p_sys = p_demux->p_sys;
714 unsigned int i_track;
717 unsigned int i_track_selected;
719 /* check for newly selected/unselected track */
720 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
723 mp4_track_t *tk = &p_sys->track[i_track];
726 if( !tk->b_ok || tk->b_chapter ||
727 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
732 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
734 if( tk->b_selected && !b )
736 MP4_TrackUnselect( p_demux, tk );
738 else if( !tk->b_selected && b)
740 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
749 if( i_track_selected <= 0 )
751 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
752 if( p_sys->i_timescale > 0 )
754 int64_t i_length = CLOCK_FREQ *
755 (mtime_t)p_sys->i_duration /
756 (mtime_t)p_sys->i_timescale;
757 if( MP4_GetMoviePTS( p_sys ) >= i_length )
762 msg_Warn( p_demux, "no track selected, exiting..." );
767 MP4_UpdateSeekpoint( p_demux );
769 /* first wait for the good time to read a packet */
770 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
772 bool b_data_sent = false;
774 /* Find next track matching contiguous data */
775 mp4_track_t *tk = NULL;
776 uint64_t i_candidate_pos = UINT64_MAX;
777 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
779 mp4_track_t *tk_tmp = &p_sys->track[i_track];
780 if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
783 uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
784 if ( i_pos <= i_candidate_pos )
786 i_candidate_pos = i_pos;
793 msg_Dbg( p_demux, "Could not select track by data position" );
798 msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
799 MP4_TrackGetDTS( p_demux, tk ),
800 MP4_GetMoviePTS( p_sys ), i_candidate_pos );
803 uint32_t i_nb_samples = 0;
804 uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
805 if( i_samplessize > 0 )
811 if( stream_Tell( p_demux->s ) != i_candidate_pos )
813 if( stream_Seek( p_demux->s, i_candidate_pos ) )
815 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
817 MP4_TrackUnselect( p_demux, tk );
823 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
825 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
827 MP4_TrackUnselect( p_demux, tk );
830 else if( tk->fmt.i_cat == SPU_ES )
832 if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
833 tk->fmt.i_codec != VLC_CODEC_SPU )
834 p_block->i_buffer = 0;
838 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
840 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
842 p_block->i_pts = p_block->i_dts + i_delta;
843 else if( tk->fmt.i_cat != VIDEO_ES )
844 p_block->i_pts = p_block->i_dts;
846 p_block->i_pts = VLC_TS_INVALID;
850 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
853 es_out_Send( p_demux->out, tk->p_es, p_block );
856 MP4_TrackNextSample( p_demux, tk, i_nb_samples );
862 p_sys->i_pcr = INT64_MAX;
863 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
865 mp4_track_t *tk = &p_sys->track[i_track];
866 if ( !tk->b_ok || !tk->b_selected ) continue;
867 p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
868 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
875 static void MP4_UpdateSeekpoint( demux_t *p_demux )
877 demux_sys_t *p_sys = p_demux->p_sys;
880 if( !p_sys->p_title )
882 i_time = MP4_GetMoviePTS( p_sys );
883 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
885 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
890 if( i != p_demux->info.i_seekpoint && i >= 0 )
892 p_demux->info.i_seekpoint = i;
893 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
896 /*****************************************************************************
898 ******************************************************************************/
899 static int Seek( demux_t *p_demux, mtime_t i_date )
901 demux_sys_t *p_sys = p_demux->p_sys;
902 unsigned int i_track;
904 /* First update global time */
905 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
906 p_sys->i_pcr = VLC_TS_INVALID;
908 /* Now for each stream try to go to this time */
909 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
911 mp4_track_t *tk = &p_sys->track[i_track];
912 MP4_TrackSeek( p_demux, tk, i_date );
914 MP4_UpdateSeekpoint( p_demux );
916 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
921 static int MP4_frg_Seek( demux_t *p_demux, double f )
923 demux_sys_t *p_sys = p_demux->p_sys;
925 int64_t i64 = stream_Size( p_demux->s );
926 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
932 /* update global time */
933 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
934 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
936 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
938 mp4_track_t *tk = &p_sys->track[i_track];
940 /* We don't want the current chunk to be flushed */
941 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
943 /* reset/update some values */
944 tk->i_sample = tk->i_sample_first = 0;
945 tk->i_first_dts = p_sys->i_time;
947 /* We want to discard the current chunk and get the next one at once */
948 tk->b_has_non_empty_cchunk = false;
950 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
955 /*****************************************************************************
957 *****************************************************************************/
958 static int Control( demux_t *p_demux, int i_query, va_list args )
960 demux_sys_t *p_sys = p_demux->p_sys;
967 case DEMUX_GET_POSITION:
968 pf = (double*)va_arg( args, double * );
969 if( p_sys->i_duration > 0 )
971 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
979 case DEMUX_SET_POSITION:
980 f = (double)va_arg( args, double );
981 if( p_sys->b_fragmented )
983 return MP4_frg_Seek( p_demux, f );
985 else if( p_sys->i_timescale > 0 )
987 i64 = (int64_t)( f * CLOCK_FREQ *
988 (double)p_sys->i_duration /
989 (double)p_sys->i_timescale );
990 return Seek( p_demux, i64 );
992 else return VLC_SUCCESS;
995 pi64 = (int64_t*)va_arg( args, int64_t * );
996 if( p_sys->i_timescale > 0 )
999 (mtime_t)p_sys->i_time /
1000 (mtime_t)p_sys->i_timescale;
1005 case DEMUX_SET_TIME:
1006 i64 = (int64_t)va_arg( args, int64_t );
1007 return Seek( p_demux, i64 );
1009 case DEMUX_GET_LENGTH:
1010 pi64 = (int64_t*)va_arg( args, int64_t * );
1011 if( p_sys->i_timescale > 0 )
1013 *pi64 = CLOCK_FREQ *
1014 (mtime_t)p_sys->i_duration /
1015 (mtime_t)p_sys->i_timescale;
1021 pf = (double*)va_arg( args, double* );
1025 case DEMUX_GET_ATTACHMENTS:
1027 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1028 int *pi_int = va_arg( args, int * );
1030 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
1031 if ( !p_covr ) return VLC_EGENERIC;
1035 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1037 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
1042 return VLC_EGENERIC;
1044 *ppp_attach = (input_attachment_t**)
1045 malloc( sizeof(input_attachment_t*) * i_count );
1046 if( !(*ppp_attach) ) return VLC_ENOMEM;
1050 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1052 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1055 if ( !memcmp( p_box->data.p_data->p_blob,
1056 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1058 psz_mime = strdup( "image/png" );
1060 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1062 psz_mime = strdup( "image/jpeg" );
1069 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1071 (*ppp_attach)[i_count++] =
1072 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1073 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1074 free( psz_filename );
1082 free( *ppp_attach );
1083 return VLC_EGENERIC;
1091 case DEMUX_GET_META:
1093 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1094 MP4_Box_t *p_0xa9xxx;
1096 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1098 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1100 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1101 if( p_udta == NULL )
1103 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1104 if( p_udta == NULL && p_covr == NULL )
1105 return VLC_EGENERIC;
1110 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1111 p_0xa9xxx = p_0xa9xxx->p_next )
1114 if( !p_0xa9xxx || !BOXDATA(p_0xa9xxx) )
1117 /* FIXME FIXME: should convert from whatever the character
1118 * encoding of MP4 meta data is to UTF-8. */
1119 #define SET(fct) do { char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" ); \
1120 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1121 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1123 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1124 switch( p_0xa9xxx->i_type )
1126 case ATOM_0xa9nam: /* Full name */
1127 SET( vlc_meta_SetTitle );
1130 SET( vlc_meta_SetArtist );
1133 SET( vlc_meta_SetArtist );
1136 SET( vlc_meta_SetCopyright );
1138 case ATOM_0xa9day: /* Creation Date */
1139 SET( vlc_meta_SetDate );
1141 case ATOM_0xa9des: /* Description */
1142 SET( vlc_meta_SetDescription );
1144 case ATOM_0xa9gen: /* Genre */
1145 SET( vlc_meta_SetGenre );
1149 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1150 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1153 case ATOM_0xa9alb: /* Album */
1154 SET( vlc_meta_SetAlbum );
1157 case ATOM_0xa9trk: /* Track */
1158 SET( vlc_meta_SetTrackNum );
1163 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1164 p_0xa9xxx->data.p_trkn->i_track_number );
1165 vlc_meta_SetTrackNum( p_meta, psz_trck );
1166 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1168 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1169 p_0xa9xxx->data.p_trkn->i_track_total );
1170 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1174 case ATOM_0xa9cmt: /* Commment */
1175 SET( vlc_meta_SetDescription );
1178 case ATOM_0xa9url: /* URL */
1179 SET( vlc_meta_SetURL );
1182 case ATOM_0xa9too: /* Encoder Tool */
1183 case ATOM_0xa9enc: /* Encoded By */
1184 SET( vlc_meta_SetEncodedBy );
1188 SET( vlc_meta_SetPublisher );
1192 SET( vlc_meta_SetDirector );
1199 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1201 { ATOM_0xa9wrt, N_("Writer") },
1202 { ATOM_0xa9com, N_("Composer") },
1203 { ATOM_0xa9prd, N_("Producer") },
1204 { ATOM_0xa9inf, N_("Information") },
1205 { ATOM_0xa9dis, N_("Disclaimer") },
1206 { ATOM_0xa9req, N_("Requirements") },
1207 { ATOM_0xa9fmt, N_("Original Format") },
1208 { ATOM_0xa9dsa, N_("Display Source As") },
1209 { ATOM_0xa9hst, N_("Host Computer") },
1210 { ATOM_0xa9prf, N_("Performers") },
1211 { ATOM_0xa9ope, N_("Original Performer") },
1212 { ATOM_0xa9src, N_("Providers Source Content") },
1213 { ATOM_0xa9wrn, N_("Warning") },
1214 { ATOM_0xa9swr, N_("Software") },
1215 { ATOM_0xa9lyr, N_("Lyrics") },
1216 { ATOM_0xa9mak, N_("Record Company") },
1217 { ATOM_0xa9mod, N_("Model") },
1218 { ATOM_0xa9PRD, N_("Product") },
1219 { ATOM_0xa9grp, N_("Grouping") },
1220 { ATOM_0xa9gen, N_("Genre") },
1221 { ATOM_0xa9st3, N_("Sub-Title") },
1222 { ATOM_0xa9arg, N_("Arranger") },
1223 { ATOM_0xa9ard, N_("Art Director") },
1224 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1225 { ATOM_0xa9con, N_("Conductor") },
1226 { ATOM_0xa9des, N_("Song Description") },
1227 { ATOM_0xa9lnt, N_("Liner Notes") },
1228 { ATOM_0xa9phg, N_("Phonogram Rights") },
1229 { ATOM_0xa9pub, N_("Publisher") },
1230 { ATOM_0xa9sne, N_("Sound Engineer") },
1231 { ATOM_0xa9sol, N_("Soloist") },
1232 { ATOM_0xa9thx, N_("Thanks") },
1233 { ATOM_0xa9xpd, N_("Executive Producer") },
1236 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1238 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1240 char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" );
1243 EnsureUTF8( psz_utf );
1244 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1254 case DEMUX_GET_TITLE_INFO:
1256 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1257 int *pi_int = (int*)va_arg( args, int* );
1258 int *pi_title_offset = (int*)va_arg( args, int* );
1259 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1261 if( !p_sys->p_title )
1262 return VLC_EGENERIC;
1265 *ppp_title = malloc( sizeof( input_title_t*) );
1266 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1267 *pi_title_offset = 0;
1268 *pi_seekpoint_offset = 0;
1271 case DEMUX_SET_TITLE:
1273 const int i_title = (int)va_arg( args, int );
1274 if( !p_sys->p_title || i_title != 0 )
1275 return VLC_EGENERIC;
1278 case DEMUX_SET_SEEKPOINT:
1280 const int i_seekpoint = (int)va_arg( args, int );
1281 if( !p_sys->p_title )
1282 return VLC_EGENERIC;
1283 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1286 case DEMUX_SET_NEXT_DEMUX_TIME:
1287 case DEMUX_SET_GROUP:
1288 case DEMUX_HAS_UNSUPPORTED_META:
1289 case DEMUX_GET_PTS_DELAY:
1290 case DEMUX_CAN_RECORD:
1291 return VLC_EGENERIC;
1294 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1295 return VLC_EGENERIC;
1299 /*****************************************************************************
1300 * Close: frees unused data
1301 *****************************************************************************/
1302 static void Close ( vlc_object_t * p_this )
1304 demux_t * p_demux = (demux_t *)p_this;
1305 demux_sys_t *p_sys = p_demux->p_sys;
1306 unsigned int i_track;
1308 msg_Dbg( p_demux, "freeing all memory" );
1310 MP4_BoxFree( p_demux->s, p_sys->p_root );
1311 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1313 MP4_TrackDestroy( &p_sys->track[i_track] );
1315 FREENULL( p_sys->track );
1317 if( p_sys->p_title )
1318 vlc_input_title_Delete( p_sys->p_title );
1325 /****************************************************************************
1326 * Local functions, specific to vlc
1327 ****************************************************************************/
1329 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1331 demux_sys_t *p_sys = p_demux->p_sys;
1334 p_sys->p_title = vlc_input_title_New();
1335 for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
1337 seekpoint_t *s = vlc_seekpoint_New();
1339 s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
1340 EnsureUTF8( s->psz_name );
1341 s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
1342 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1345 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1347 demux_sys_t *p_sys = p_demux->p_sys;
1349 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1351 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1352 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1353 uint32_t i_nb_samples = 0;
1354 const uint32_t i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
1356 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1359 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1360 __MIN( sizeof(p_buffer), i_size ) );
1361 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1365 seekpoint_t *s = vlc_seekpoint_New();
1367 s->psz_name = strndup( &p_buffer[2], i_len );
1368 EnsureUTF8( s->psz_name );
1370 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1372 if( !p_sys->p_title )
1373 p_sys->p_title = vlc_input_title_New();
1374 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1377 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1378 tk->chunk[tk->i_chunk].i_sample_count )
1382 static void LoadChapter( demux_t *p_demux )
1384 demux_sys_t *p_sys = p_demux->p_sys;
1387 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && BOXDATA(p_chpl)->i_chapter > 0 )
1389 LoadChapterGpac( p_demux, p_chpl );
1391 else if( p_sys->p_tref_chap )
1393 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1396 /* Load the first subtitle track like quicktime */
1397 for( i = 0; i < p_chap->i_entry_count; i++ )
1399 for( j = 0; j < p_sys->i_tracks; j++ )
1401 mp4_track_t *tk = &p_sys->track[j];
1402 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1403 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1406 if( j < p_sys->i_tracks )
1408 LoadChapterApple( p_demux, &p_sys->track[j] );
1414 /* Add duration if titles are enabled */
1415 if( p_sys->p_title )
1417 p_sys->p_title->i_length = CLOCK_FREQ *
1418 (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1422 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1423 static int TrackCreateChunksIndex( demux_t *p_demux,
1424 mp4_track_t *p_demux_track )
1426 demux_sys_t *p_sys = p_demux->p_sys;
1427 if( p_sys->b_fragmented )
1430 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1433 unsigned int i_chunk;
1434 unsigned int i_index, i_last;
1436 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1437 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1438 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1440 return( VLC_EGENERIC );
1443 p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
1444 if( !p_demux_track->i_chunk_count )
1446 msg_Warn( p_demux, "no chunk defined" );
1447 return( VLC_EGENERIC );
1449 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1450 sizeof( mp4_chunk_t ) );
1451 if( p_demux_track->chunk == NULL )
1456 /* first we read chunk offset */
1457 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1459 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1461 ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
1463 ck->i_first_dts = 0;
1464 ck->p_sample_count_dts = NULL;
1465 ck->p_sample_delta_dts = NULL;
1466 ck->p_sample_count_pts = NULL;
1467 ck->p_sample_offset_pts = NULL;
1470 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1471 to be used for the sample XXX begin to 1
1472 We construct it begining at the end */
1473 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1474 i_index = BOXDATA(p_stsc)->i_entry_count;
1477 msg_Warn( p_demux, "cannot read chunk table or table empty" );
1478 return( VLC_EGENERIC );
1483 for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1484 i_chunk < i_last; i_chunk++ )
1486 if( i_chunk >= p_demux_track->i_chunk_count )
1488 msg_Warn( p_demux, "corrupted chunk table" );
1489 return VLC_EGENERIC;
1492 p_demux_track->chunk[i_chunk].i_sample_description_index =
1493 BOXDATA(p_stsc)->i_sample_description_index[i_index];
1494 p_demux_track->chunk[i_chunk].i_sample_count =
1495 BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
1497 i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1500 p_demux_track->chunk[0].i_sample_first = 0;
1501 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1503 p_demux_track->chunk[i_chunk].i_sample_first =
1504 p_demux_track->chunk[i_chunk-1].i_sample_first +
1505 p_demux_track->chunk[i_chunk-1].i_sample_count;
1508 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1509 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1514 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1515 const uint32_t i_index,
1516 uint32_t i_index_samples_left,
1517 uint32_t i_sample_count,
1518 const uint32_t *pi_index_sample_count,
1519 const uint32_t i_table_count )
1521 uint32_t i_array_offset;
1522 while( i_sample_count > 0 )
1524 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1525 i_array_offset = i_index + *pi_entry;
1527 return VLC_EGENERIC;
1529 if ( i_array_offset >= i_table_count )
1531 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1532 return VLC_EGENERIC;
1535 if ( i_index_samples_left )
1537 if ( i_index_samples_left > i_sample_count )
1539 i_index_samples_left -= i_sample_count;
1541 *pi_entry +=1; /* No samples left, go copy */
1546 i_sample_count -= i_index_samples_left;
1547 i_index_samples_left = 0;
1554 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1562 static int TrackCreateSamplesIndex( demux_t *p_demux,
1563 mp4_track_t *p_demux_track )
1565 demux_sys_t *p_sys = p_demux->p_sys;
1566 if( p_sys->b_fragmented )
1570 MP4_Box_data_stsz_t *stsz;
1571 /* TODO use also stss and stsh table for seeking */
1572 /* FIXME use edit table */
1575 * Gives the sample size for each samples. There is also a stz2 table
1576 * (compressed form) that we need to implement TODO */
1577 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1580 /* FIXME and stz2 */
1581 msg_Warn( p_demux, "cannot find STSZ box" );
1582 return VLC_EGENERIC;
1584 stsz = p_box->data.p_stsz;
1586 /* Use stsz table to create a sample number -> sample size table */
1587 p_demux_track->i_sample_count = stsz->i_sample_count;
1588 if( stsz->i_sample_size )
1590 /* 1: all sample have the same size, so no need to construct a table */
1591 p_demux_track->i_sample_size = stsz->i_sample_size;
1592 p_demux_track->p_sample_size = NULL;
1596 /* 2: each sample can have a different size */
1597 p_demux_track->i_sample_size = 0;
1598 p_demux_track->p_sample_size =
1599 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1600 if( p_demux_track->p_sample_size == NULL )
1603 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1605 p_demux_track->p_sample_size[i_sample] =
1606 stsz->i_entry_size[i_sample];
1610 /* Use stts table to create a sample number -> dts table.
1611 * XXX: if we don't want to waste too much memory, we can't expand
1612 * the box! so each chunk will contain an "extract" of this table
1613 * for fast research (problem with raw stream where a sample is sometime
1614 * just channels*bits_per_sample/8 */
1616 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1617 * differing in 2/2 fields and 1 signedness */
1619 mtime_t i_next_dts = 0;
1621 * Gives mapping between sample and decoding time
1623 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1626 msg_Warn( p_demux, "cannot find STTS box" );
1627 return VLC_EGENERIC;
1631 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
1633 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
1635 /* Create sample -> dts table per chunk */
1636 uint32_t i_index = 0;
1637 uint32_t i_current_index_samples_left = 0;
1639 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1641 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1642 uint32_t i_entry, i_sample_count;
1644 /* save first dts */
1645 ck->i_first_dts = i_next_dts;
1646 ck->i_last_dts = i_next_dts;
1648 /* count how many entries are needed for this chunk
1649 * for p_sample_delta_dts and p_sample_count_dts */
1652 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1653 i_current_index_samples_left,
1655 stts->pi_sample_count,
1656 stts->i_entry_count );
1657 if ( i_ret != VLC_SUCCESS )
1661 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1662 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1663 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1665 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1670 i_sample_count = ck->i_sample_count;
1672 for( uint32_t i = 0; i < i_entry; i++ )
1674 if ( i_current_index_samples_left )
1676 if ( i_current_index_samples_left > i_sample_count )
1678 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1679 ck->p_sample_count_dts[i] = i_sample_count;
1680 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1681 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1682 i_current_index_samples_left -= i_sample_count;
1684 assert( i == i_entry - 1 );
1689 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
1690 ck->p_sample_count_dts[i] = i_current_index_samples_left;
1691 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1692 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1693 i_sample_count -= i_current_index_samples_left;
1694 i_current_index_samples_left = 0;
1700 if ( stts->pi_sample_count[i_index] > i_sample_count )
1702 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1703 ck->p_sample_count_dts[i] = i_sample_count;
1704 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1705 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1706 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
1708 assert( i == i_entry - 1 );
1709 // keep building from same index
1713 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
1714 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
1715 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1716 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1717 i_sample_count -= stts->pi_sample_count[i_index];
1728 * Gives the delta between decoding time (dts) and composition table (pts)
1730 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1733 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1735 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
1737 /* Create pts-dts table per chunk */
1738 uint32_t i_index = 0;
1739 uint32_t i_current_index_samples_left = 0;
1741 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1743 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1744 uint32_t i_entry, i_sample_count;
1746 /* count how many entries are needed for this chunk
1747 * for p_sample_offset_pts and p_sample_count_pts */
1749 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1750 i_current_index_samples_left,
1752 ctts->pi_sample_count,
1753 ctts->i_entry_count );
1754 if ( i_ret != VLC_SUCCESS )
1758 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1759 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1760 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1762 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1767 i_sample_count = ck->i_sample_count;
1769 for( uint32_t i = 0; i < i_entry; i++ )
1771 if ( i_current_index_samples_left )
1773 if ( i_current_index_samples_left > i_sample_count )
1775 ck->p_sample_count_pts[i] = i_sample_count;
1776 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1777 i_current_index_samples_left -= i_sample_count;
1779 assert( i == i_entry - 1 );
1784 ck->p_sample_count_pts[i] = i_current_index_samples_left;
1785 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1786 i_sample_count -= i_current_index_samples_left;
1787 i_current_index_samples_left = 0;
1793 if ( ctts->pi_sample_count[i_index] > i_sample_count )
1795 ck->p_sample_count_pts[i] = i_sample_count;
1796 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1797 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
1799 assert( i == i_entry - 1 );
1800 // keep building from same index
1804 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
1805 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1806 i_sample_count -= ctts->pi_sample_count[i_index];
1816 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
1817 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1818 i_next_dts / p_demux_track->i_timescale );
1825 * It computes the sample rate for a video track using the given sample
1828 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1829 const mp4_track_t *p_track,
1830 unsigned i_sd_index,
1836 if( p_track->i_chunk_count <= 0 )
1840 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1841 while( p_chunk > &p_track->chunk[0] &&
1842 p_chunk[-1].i_sample_description_index == i_sd_index )
1847 uint64_t i_sample = 0;
1848 uint64_t i_first_dts = p_chunk->i_first_dts;
1849 uint64_t i_last_dts;
1852 i_sample += p_chunk->i_sample_count;
1853 i_last_dts = p_chunk->i_last_dts;
1856 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1857 p_chunk->i_sample_description_index == i_sd_index );
1859 if( i_sample > 1 && i_first_dts < i_last_dts )
1860 vlc_ureduce( pi_num, pi_den,
1861 ( i_sample - 1) * p_track->i_timescale,
1862 i_last_dts - i_first_dts,
1868 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1870 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1871 unsigned int i_chunk, es_out_id_t **pp_es )
1873 demux_sys_t *p_sys = p_demux->p_sys;
1874 unsigned int i_sample_description_index;
1876 if( p_sys->b_fragmented )
1877 i_sample_description_index = 1; /* XXX */
1879 i_sample_description_index =
1880 p_track->chunk[i_chunk].i_sample_description_index;
1882 MP4_Box_t *p_sample;
1891 if( !i_sample_description_index )
1893 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1894 p_track->i_track_ID );
1895 return VLC_EGENERIC;
1898 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
1899 i_sample_description_index - 1 );
1902 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
1904 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1905 p_track->i_track_ID );
1906 return VLC_EGENERIC;
1909 p_track->p_sample = p_sample;
1911 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1913 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1915 p_sample->i_type = p_frma->data.p_frma->i_type;
1918 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1920 p_enda = MP4_BoxGet( p_sample, "enda" );
1922 p_pasp = MP4_BoxGet( p_sample, "pasp" );
1925 switch( p_track->fmt.i_cat )
1928 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1929 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1930 p_track->fmt.video.i_bits_per_pixel =
1931 p_sample->data.p_sample_vide->i_depth;
1933 /* fall on display size */
1934 if( p_track->fmt.video.i_width <= 0 )
1935 p_track->fmt.video.i_width = p_track->i_width;
1936 if( p_track->fmt.video.i_height <= 0 )
1937 p_track->fmt.video.i_height = p_track->i_height;
1939 /* Find out apect ratio from display size */
1940 if( p_track->i_width > 0 && p_track->i_height > 0 &&
1941 /* Work-around buggy muxed files */
1942 p_sample->data.p_sample_vide->i_width != p_track->i_width )
1944 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
1945 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1947 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1948 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1950 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1951 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1954 /* Support for cropping (eg. in H263 files) */
1955 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1956 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1959 TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1960 &p_track->fmt.video.i_frame_rate_base,
1961 p_track, i_sample_description_index, i_chunk );
1962 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1963 (float)p_track->fmt.video.i_frame_rate_base;
1966 switch( (int)p_track->f_rotation ) {
1968 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1971 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1974 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1981 p_track->fmt.audio.i_channels =
1982 p_sample->data.p_sample_soun->i_channelcount;
1983 p_track->fmt.audio.i_rate =
1984 p_sample->data.p_sample_soun->i_sampleratehi;
1985 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1986 p_sample->data.p_sample_soun->i_sampleratehi *
1987 p_sample->data.p_sample_soun->i_samplesize;
1988 p_track->fmt.audio.i_bitspersample =
1989 p_sample->data.p_sample_soun->i_samplesize;
1991 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1993 MP4_Box_data_sample_soun_t *p_soun;
1994 p_soun = p_sample->data.p_sample_soun;
1996 if( p_soun->i_qt_version == 0 )
1998 switch( p_sample->i_type )
2000 case VLC_CODEC_ADPCM_IMA_QT:
2001 p_soun->i_qt_version = 1;
2002 p_soun->i_sample_per_packet = 64;
2003 p_soun->i_bytes_per_packet = 34;
2004 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
2005 p_soun->i_bytes_per_sample = 2;
2007 case VLC_CODEC_MACE3:
2008 p_soun->i_qt_version = 1;
2009 p_soun->i_sample_per_packet = 6;
2010 p_soun->i_bytes_per_packet = 2;
2011 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2012 p_soun->i_bytes_per_sample = 2;
2014 case VLC_CODEC_MACE6:
2015 p_soun->i_qt_version = 1;
2016 p_soun->i_sample_per_packet = 12;
2017 p_soun->i_bytes_per_packet = 2;
2018 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2019 p_soun->i_bytes_per_sample = 2;
2021 case VLC_CODEC_ALAW:
2022 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
2023 p_soun->i_samplesize = 8;
2024 p_track->i_sample_size = p_soun->i_channelcount;
2026 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
2027 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
2028 case VLC_FOURCC( 't', 'w', 'o', 's' ):
2029 case VLC_FOURCC( 's', 'o', 'w', 't' ):
2030 /* What would be the fun if you could trust the .mov */
2031 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
2038 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
2040 p_soun->i_qt_version = 0;
2043 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
2045 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2047 switch( p_sample->i_type )
2049 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2050 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2052 if( p_track->i_sample_size > 1 )
2053 p_soun->i_qt_version = 0;
2056 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2057 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2058 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2059 p_soun->i_qt_version = 0;
2066 if( p_track->i_sample_size != 0 &&
2067 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2068 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2070 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2071 p_sample->data.p_sample_soun->i_qt_version = 0;
2080 /* It's a little ugly but .. there are special cases */
2081 switch( p_sample->i_type )
2083 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2084 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2086 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2089 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2091 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2093 p_track->fmt.i_codec = VLC_CODEC_A52;
2096 static const int pi_bitrate[] = {
2103 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2104 p_track->fmt.audio.i_channels = 0;
2105 p_track->fmt.i_bitrate = 0;
2106 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2107 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2108 p_track->fmt.audio.i_bitspersample = 0;
2112 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2114 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2118 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2119 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2121 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2123 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2124 p_track->fmt.i_codec = VLC_CODEC_U8;
2126 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2128 /* Buggy files workaround */
2129 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2130 p_sample->data.p_sample_soun->i_sampleratehi) )
2132 MP4_Box_data_sample_soun_t *p_soun =
2133 p_sample->data.p_sample_soun;
2135 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2136 "(%u), making both equal (report any problem).",
2137 p_track->i_timescale, p_soun->i_sampleratehi );
2139 if( p_soun->i_sampleratehi != 0 )
2140 p_track->i_timescale = p_soun->i_sampleratehi;
2142 p_soun->i_sampleratehi = p_track->i_timescale;
2147 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2148 p_track->fmt.i_codec = VLC_CODEC_H263;
2151 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2152 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2154 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2155 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2158 text_style_t *p_style = text_style_New();
2161 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2162 p_style->i_font_size = p_text->i_font_size;
2163 if ( p_text->i_font_color )
2165 p_style->i_font_color = p_text->i_font_color >> 8;
2166 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2168 if ( p_text->i_background_color[3] >> 8 )
2170 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2171 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2172 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2173 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2176 p_track->fmt.subs.p_style = p_style;
2178 /* FIXME UTF-8 doesn't work here ? */
2179 if( p_track->b_mac_encoding )
2180 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2182 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2185 case VLC_FOURCC('y','v','1','2'):
2186 p_track->fmt.i_codec = VLC_CODEC_YV12;
2188 case VLC_FOURCC('y','u','v','2'):
2189 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2192 case VLC_FOURCC('i','n','2','4'):
2193 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2194 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2196 case VLC_FOURCC('i','n','3','2'):
2197 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2198 VLC_CODEC_S32L : VLC_CODEC_S32B;
2200 case VLC_FOURCC('f','l','3','2'):
2201 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2202 VLC_CODEC_F32L : VLC_CODEC_F32B;
2204 case VLC_FOURCC('f','l','6','4'):
2205 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2206 VLC_CODEC_F64L : VLC_CODEC_F64B;
2208 case VLC_CODEC_DVD_LPCM:
2210 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2211 if( p_soun->i_qt_version == 2 &&
2212 p_soun->i_qt_description > 20 + 28 )
2219 static const struct {
2223 vlc_fourcc_t i_codec;
2225 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2226 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2227 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2228 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2230 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2231 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2233 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2234 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2235 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2236 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2238 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2239 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2240 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2241 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2243 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2244 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2245 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2246 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2250 uint32_t i_bits = GetDWBE(&p_soun->p_qt_description[20 + 20]);
2251 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
2253 for( int i = 0; p_formats[i].i_codec; i++ )
2255 if( p_formats[i].i_bits == i_bits &&
2256 (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
2258 p_track->fmt.i_codec = p_formats[i].i_codec;
2259 p_track->fmt.audio.i_bitspersample = i_bits;
2260 p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
2261 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2263 p_soun->i_qt_version = 0;
2271 p_track->fmt.i_codec = p_sample->i_type;
2275 /* now see if esds is present and if so create a data packet
2276 with decoder_specific_info */
2277 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2278 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2279 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2280 ( p_esds->data.p_esds )&&
2283 /* First update information based on i_objectTypeIndication */
2284 switch( p_decconfig->i_objectTypeIndication )
2286 case( 0x20 ): /* MPEG4 VIDEO */
2287 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2289 case( 0x21 ): /* H.264 */
2290 p_track->fmt.i_codec = VLC_CODEC_H264;
2293 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2294 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2295 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2296 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2298 p_track->fmt.i_codec = VLC_CODEC_ALS;
2306 case( 0x65): /* MPEG2 video */
2307 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2309 /* Theses are MPEG2-AAC */
2310 case( 0x66): /* main profile */
2311 case( 0x67): /* Low complexity profile */
2312 case( 0x68): /* Scaleable Sampling rate profile */
2313 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2315 /* True MPEG 2 audio */
2317 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2319 case( 0x6a): /* MPEG1 video */
2320 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2322 case( 0x6b): /* MPEG1 audio */
2323 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2325 case( 0x6c ): /* jpeg */
2326 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2328 case( 0x6d ): /* png */
2329 p_track->fmt.i_codec = VLC_CODEC_PNG;
2331 case( 0x6e ): /* jpeg2000 */
2332 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2334 case( 0xa3 ): /* vc1 */
2335 p_track->fmt.i_codec = VLC_CODEC_VC1;
2338 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2341 p_track->fmt.i_codec = VLC_CODEC_A52;
2344 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2346 case( 0xa9 ): /* dts */
2347 case( 0xaa ): /* DTS-HD HRA */
2348 case( 0xab ): /* DTS-HD Master Audio */
2349 p_track->fmt.i_codec = VLC_CODEC_DTS;
2352 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2356 case( 0xe0 ): /* NeroDigital: dvd subs */
2357 if( p_track->fmt.i_cat == SPU_ES )
2359 p_track->fmt.i_codec = VLC_CODEC_SPU;
2360 if( p_track->i_width > 0 )
2361 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2362 if( p_track->i_height > 0 )
2363 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2366 case( 0xe1 ): /* QCelp for 3gp */
2367 if( p_track->fmt.i_cat == AUDIO_ES )
2369 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2375 /* Unknown entry, but don't touch i_fourcc */
2377 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2378 p_decconfig->i_objectTypeIndication,
2379 p_track->i_track_ID );
2382 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2383 if( p_track->fmt.i_extra > 0 )
2385 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2386 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2387 p_track->fmt.i_extra );
2389 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2390 p_track->fmt.i_extra >= 16 * 4 )
2392 for( int i = 0; i < 16; i++ )
2394 p_track->fmt.subs.spu.palette[1 + i] =
2395 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2397 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2402 switch( p_sample->i_type )
2404 /* qt decoder, send the complete chunk */
2405 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2406 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2407 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2408 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2409 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2410 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2411 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2412 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2413 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2414 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2415 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2416 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2417 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2419 /* qt decoder, send the complete chunk */
2420 case VLC_CODEC_SVQ1:
2421 case VLC_CODEC_SVQ3:
2422 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2423 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2424 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2425 p_track->fmt.i_extra =
2426 p_sample->data.p_sample_vide->i_qt_image_description;
2427 if( p_track->fmt.i_extra > 0 )
2429 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2430 memcpy( p_track->fmt.p_extra,
2431 p_sample->data.p_sample_vide->p_qt_image_description,
2432 p_track->fmt.i_extra);
2436 case VLC_CODEC_AMR_NB:
2437 p_track->fmt.audio.i_rate = 8000;
2439 case VLC_CODEC_AMR_WB:
2440 p_track->fmt.audio.i_rate = 16000;
2442 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2443 case VLC_CODEC_QDM2:
2444 case VLC_CODEC_ALAC:
2445 p_track->fmt.i_extra =
2446 p_sample->data.p_sample_soun->i_qt_description;
2447 if( p_track->fmt.i_extra > 0 )
2449 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2450 memcpy( p_track->fmt.p_extra,
2451 p_sample->data.p_sample_soun->p_qt_description,
2452 p_track->fmt.i_extra);
2454 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2456 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2457 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2461 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2463 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2466 p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
2467 if( p_track->fmt.i_extra > 0 )
2469 p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
2470 memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
2471 p_track->fmt.i_extra );
2476 msg_Err( p_demux, "missing dvc1" );
2481 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2482 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2484 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2488 p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
2489 if( p_track->fmt.i_extra > 0 )
2491 p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
2492 memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
2493 p_track->fmt.i_extra );
2498 msg_Err( p_demux, "missing avcC" );
2502 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2503 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2505 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2509 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2510 if( p_track->fmt.i_extra > 0 )
2512 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2513 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2514 p_track->fmt.i_extra );
2516 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2520 msg_Err( p_demux, "missing hvcC" );
2526 case VLC_CODEC_ADPCM_MS:
2527 case VLC_CODEC_ADPCM_IMA_WAV:
2528 case VLC_CODEC_QCELP:
2529 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2533 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2541 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2546 /* given a time it return sample/chunk
2547 * it also update elst field of the track
2549 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2550 int64_t i_start, uint32_t *pi_chunk,
2551 uint32_t *pi_sample )
2553 demux_sys_t *p_sys = p_demux->p_sys;
2554 MP4_Box_t *p_box_stss;
2556 unsigned int i_sample;
2557 unsigned int i_chunk;
2560 /* FIXME see if it's needed to check p_track->i_chunk_count */
2561 if( p_track->i_chunk_count == 0 )
2562 return( VLC_EGENERIC );
2564 /* handle elst (find the correct one) */
2565 MP4_TrackSetELST( p_demux, p_track, i_start );
2566 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
2568 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
2569 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2571 /* now calculate i_start for this elst */
2573 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2581 /* to track time scale */
2582 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2583 /* add elst offset */
2584 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2585 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2586 elst->i_media_time[p_track->i_elst] > 0 )
2588 i_start += elst->i_media_time[p_track->i_elst];
2591 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2592 "ms (track)", p_track->i_elst,
2593 i_mvt * 1000 / p_sys->i_timescale,
2594 i_start * 1000 / p_track->i_timescale );
2598 /* convert absolute time to in timescale unit */
2599 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2602 /* we start from sample 0/chunk 0, hope it won't take too much time */
2603 /* *** find good chunk *** */
2604 for( i_chunk = 0; ; i_chunk++ )
2606 if( i_chunk + 1 >= p_track->i_chunk_count )
2608 /* at the end and can't check if i_start in this chunk,
2609 it will be check while searching i_sample */
2610 i_chunk = p_track->i_chunk_count - 1;
2614 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2615 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2621 /* *** find sample in the chunk *** */
2622 i_sample = p_track->chunk[i_chunk].i_sample_first;
2623 i_dts = p_track->chunk[i_chunk].i_first_dts;
2624 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2627 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2628 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2631 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2632 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2634 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2639 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2643 i_sample += ( i_start - i_dts ) /
2644 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2649 if( i_sample >= p_track->i_sample_count )
2651 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2652 "(seeking too far) chunk=%d sample=%d",
2653 p_track->i_track_ID, i_chunk, i_sample );
2654 return( VLC_EGENERIC );
2658 /* *** Try to find nearest sync points *** */
2659 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2661 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2662 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2663 p_track->i_track_ID );
2664 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2666 if( i_index >= p_stss->i_entry_count - 1 ||
2667 i_sample < p_stss->i_sample_number[i_index+1] )
2669 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2670 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
2671 i_sample, i_sync_sample );
2673 if( i_sync_sample <= i_sample )
2675 while( i_chunk > 0 &&
2676 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2681 while( i_chunk < p_track->i_chunk_count - 1 &&
2682 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2683 p_track->chunk[i_chunk].i_sample_count )
2686 i_sample = i_sync_sample;
2693 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2694 "Sample Box (stss)", p_track->i_track_ID );
2697 *pi_chunk = i_chunk;
2698 *pi_sample = i_sample;
2703 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2704 unsigned int i_chunk, unsigned int i_sample )
2706 bool b_reselect = false;
2708 /* now see if actual es is ok */
2709 if( p_track->i_chunk >= p_track->i_chunk_count ||
2710 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2711 p_track->chunk[i_chunk].i_sample_description_index )
2713 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2714 p_track->i_track_ID );
2716 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2717 p_track->p_es, &b_reselect );
2719 es_out_Del( p_demux->out, p_track->p_es );
2721 p_track->p_es = NULL;
2723 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2725 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2726 p_track->i_track_ID );
2728 p_track->b_ok = false;
2729 p_track->b_selected = false;
2730 return VLC_EGENERIC;
2734 /* select again the new decoder */
2737 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2740 p_track->i_chunk = i_chunk;
2741 p_track->i_sample = i_sample;
2743 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2746 /****************************************************************************
2748 ****************************************************************************
2749 * Parse track information and create all needed data to run a track
2750 * If it succeed b_ok is set to 1 else to 0
2751 ****************************************************************************/
2752 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2753 MP4_Box_t *p_box_trak,
2754 bool b_force_enable )
2756 demux_sys_t *p_sys = p_demux->p_sys;
2758 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2759 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2769 char language[4] = { '\0' };
2771 /* hint track unsupported */
2773 /* set default value (-> track unusable) */
2774 p_track->b_ok = false;
2775 p_track->b_enable = false;
2776 p_track->b_selected = false;
2777 p_track->b_chapter = false;
2778 p_track->b_mac_encoding = false;
2780 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2787 /* do we launch this track by default ? */
2789 ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
2790 if( !p_track->b_enable )
2791 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2793 p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
2795 p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
2796 p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
2797 p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
2801 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2804 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2805 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2807 if( ( !p_mdhd )||( !p_hdlr ) )
2812 p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
2813 if( p_track->i_timescale == 0 )
2816 if( BOXDATA(p_mdhd)->i_language_code < 0x400 )
2818 strcpy( language, MP4_ConvertMacCode( BOXDATA(p_mdhd)->i_language_code ) );
2819 p_track->b_mac_encoding = true;
2821 else if( BOXDATA(p_mdhd)->i_language_code == 0x7fff )
2822 p_track->b_mac_encoding = true;
2825 for( unsigned i = 0; i < 3; i++ )
2826 language[i] = BOXDATA(p_mdhd)->i_language[i];
2830 switch( p_hdlr->data.p_hdlr->i_handler_type )
2833 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2837 p_track->fmt.i_cat = AUDIO_ES;
2841 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2845 p_track->fmt.i_cat = VIDEO_ES;
2852 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2853 p_track->fmt.i_cat = SPU_ES;
2860 p_track->i_elst = 0;
2861 p_track->i_elst_time = 0;
2862 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2864 MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
2867 msg_Warn( p_demux, "elst box found" );
2868 for( i = 0; i < elst->i_entry_count; i++ )
2870 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2871 "ms) rate=%d.%d", i,
2872 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2873 elst->i_media_time[i] >= 0 ?
2874 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2876 elst->i_media_rate_integer[i],
2877 elst->i_media_rate_fraction[i] );
2884 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2886 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2887 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2893 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2895 p_track->fmt.psz_language = strdup( language );
2898 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2901 MP4_Box_t *p_box_iter;
2902 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2903 p_box_iter = p_box_iter->p_next )
2905 switch( p_box_iter->i_type )
2908 p_track->fmt.psz_description =
2909 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2912 p_track->fmt.psz_description =
2913 strdup( p_box_iter->data.p_name->psz_text );
2919 /* Create chunk index table and sample index table */
2920 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2921 TrackCreateSamplesIndex( p_demux, p_track ) )
2923 return; /* cannot create chunks index */
2926 p_track->i_chunk = 0;
2927 p_track->i_sample = 0;
2929 /* Mark chapter only track */
2930 if( p_sys->p_tref_chap )
2932 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2935 for( i = 0; i < p_chap->i_entry_count; i++ )
2937 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2938 p_track->fmt.i_cat == UNKNOWN_ES )
2940 p_track->b_chapter = true;
2941 p_track->b_enable = false;
2948 if( b_force_enable &&
2949 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2951 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2952 p_track->i_track_ID );
2953 p_track->b_enable = true;
2954 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2957 p_track->p_es = NULL;
2958 if( TrackCreateES( p_demux,
2959 p_track, p_track->i_chunk,
2960 p_track->b_chapter ? NULL : &p_track->p_es ) )
2962 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2963 p_track->i_track_ID );
2966 p_track->b_ok = true;
2970 for( i = 0; i < p_track->i_chunk_count; i++ )
2972 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2973 i, p_track->chunk[i].i_sample_count,
2974 p_track->chunk[i].i_first_dts );
2981 static void FreeAndResetChunk( mp4_chunk_t *ck )
2983 free( ck->p_sample_count_dts );
2984 free( ck->p_sample_delta_dts );
2985 free( ck->p_sample_count_pts );
2986 free( ck->p_sample_offset_pts );
2987 free( ck->p_sample_size );
2988 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2989 free( ck->p_sample_data[i] );
2990 free( ck->p_sample_data );
2991 memset( ck, 0, sizeof( mp4_chunk_t ) );
2994 /****************************************************************************
2996 ****************************************************************************
2997 * Destroy a track created by MP4_TrackCreate.
2998 ****************************************************************************/
2999 static void MP4_TrackDestroy( mp4_track_t *p_track )
3001 unsigned int i_chunk;
3003 p_track->b_ok = false;
3004 p_track->b_enable = false;
3005 p_track->b_selected = false;
3007 es_format_Clean( &p_track->fmt );
3009 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
3011 if( p_track->chunk )
3013 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
3014 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
3016 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
3017 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3020 FREENULL( p_track->chunk );
3021 if( p_track->cchunk ) {
3022 FreeAndResetChunk( p_track->cchunk );
3023 FREENULL( p_track->cchunk );
3026 if( !p_track->i_sample_size )
3028 FREENULL( p_track->p_sample_size );
3032 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3035 if( !p_track->b_ok || p_track->b_chapter )
3037 return VLC_EGENERIC;
3040 if( p_track->b_selected )
3042 msg_Warn( p_demux, "track[Id 0x%x] already selected",
3043 p_track->i_track_ID );
3047 return MP4_TrackSeek( p_demux, p_track, i_start );
3050 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3052 if( !p_track->b_ok || p_track->b_chapter )
3057 if( !p_track->b_selected )
3059 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3060 p_track->i_track_ID );
3065 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3066 p_track->p_es, false );
3069 p_track->b_selected = false;
3072 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3078 if( !p_track->b_ok || p_track->b_chapter )
3079 return VLC_EGENERIC;
3081 p_track->b_selected = false;
3083 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3084 &i_chunk, &i_sample ) )
3086 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3087 p_track->i_track_ID );
3088 return VLC_EGENERIC;
3091 p_track->b_selected = true;
3093 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3094 p_track->b_selected = true;
3096 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3101 * 3 types: for audio
3104 #define QT_V0_MAX_SAMPLES 1024
3105 static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3108 MP4_Box_data_sample_soun_t *p_soun;
3110 if( p_track->i_sample_size == 0 )
3112 /* most simple case */
3113 return p_track->p_sample_size[p_track->i_sample];
3115 if( p_track->fmt.i_cat != AUDIO_ES )
3117 return p_track->i_sample_size;
3120 p_soun = p_track->p_sample->data.p_sample_soun;
3122 if( p_soun->i_qt_version == 1 )
3124 uint32_t i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
3125 if( p_track->fmt.audio.i_blockalign > 1 )
3126 i_samples = p_soun->i_sample_per_packet;
3127 i_size = i_samples / p_soun->i_sample_per_packet;
3128 if ( UINT32_MAX / i_size >= p_soun->i_bytes_per_frame )
3129 i_size *= p_soun->i_bytes_per_frame;
3131 i_size = UINT32_MAX;
3133 else if( p_track->i_sample_size > 256 )
3135 /* We do that so we don't read too much data
3136 * (in this case we are likely dealing with compressed data) */
3137 i_size = p_track->i_sample_size;
3141 mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3142 int64_t i_length = CLOCK_FREQ / 10;
3143 uint32_t i_samples = 0;
3144 uint32_t i_maxsamples = 0;
3145 for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
3147 i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
3148 if ( i_length < 0 ) break;
3152 i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
3153 i_samples = __MIN( i_maxsamples, i_samples );
3154 if ( i_samples == 0 ) i_samples = 1;
3155 i_size = i_samples * p_track->i_sample_size;
3156 *pi_nb_samples = i_samples;
3159 //fprintf( stderr, "size=%d\n", i_size );
3163 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3165 unsigned int i_sample;
3168 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3170 if( p_track->i_sample_size )
3172 MP4_Box_data_sample_soun_t *p_soun =
3173 p_track->p_sample->data.p_sample_soun;
3175 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3177 i_pos += ( p_track->i_sample -
3178 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3179 p_track->i_sample_size;
3183 /* we read chunk by chunk unless a blockalign is requested */
3184 if( p_track->fmt.audio.i_blockalign > 1 )
3185 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3186 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3191 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3192 i_sample < p_track->i_sample; i_sample++ )
3194 i_pos += p_track->p_sample_size[i_sample];
3201 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3203 if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
3205 MP4_Box_data_sample_soun_t *p_soun;
3207 p_soun = p_track->p_sample->data.p_sample_soun;
3209 if( p_soun->i_qt_version == 1 )
3211 /* we read chunk by chunk unless a blockalign is requested */
3212 if( p_track->fmt.audio.i_blockalign > 1 )
3213 p_track->i_sample += p_soun->i_sample_per_packet;
3215 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
3217 else if( p_track->i_sample_size > 256 )
3219 /* We do that so we don't read too much data
3220 * (in this case we are likely dealing with compressed data) */
3221 p_track->i_sample += 1;
3226 p_track->i_sample += i_samples;
3227 if( p_track->i_sample >
3228 p_track->chunk[p_track->i_chunk].i_sample_first +
3229 p_track->chunk[p_track->i_chunk].i_sample_count )
3232 p_track->chunk[p_track->i_chunk].i_sample_first +
3233 p_track->chunk[p_track->i_chunk].i_sample_count;
3239 p_track->i_sample++;
3242 if( p_track->i_sample >= p_track->i_sample_count )
3243 return VLC_EGENERIC;
3245 /* Have we changed chunk ? */
3246 if( p_track->i_sample >=
3247 p_track->chunk[p_track->i_chunk].i_sample_first +
3248 p_track->chunk[p_track->i_chunk].i_sample_count )
3250 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3251 p_track->i_sample ) )
3253 msg_Warn( p_demux, "track[0x%x] will be disabled "
3254 "(cannot restart decoder)", p_track->i_track_ID );
3255 MP4_TrackUnselect( p_demux, p_track );
3256 return VLC_EGENERIC;
3260 /* Have we changed elst */
3261 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3263 demux_sys_t *p_sys = p_demux->p_sys;
3264 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3265 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3266 p_sys->i_timescale / CLOCK_FREQ;
3268 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3269 i_mvt >= p_track->i_elst_time +
3270 elst->i_segment_duration[p_track->i_elst] )
3272 MP4_TrackSetELST( p_demux, p_track,
3273 MP4_TrackGetDTS( p_demux, p_track ) );
3280 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3283 demux_sys_t *p_sys = p_demux->p_sys;
3284 int i_elst_last = tk->i_elst;
3286 /* handle elst (find the correct one) */
3288 tk->i_elst_time = 0;
3289 if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3291 MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3292 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3294 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3296 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3298 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3302 tk->i_elst_time += i_dur;
3305 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3307 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3308 tk->i_elst = elst->i_entry_count - 1;
3309 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3312 if( elst->i_media_time[tk->i_elst] < 0 )
3315 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3318 if( i_elst_last != tk->i_elst )
3320 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3325 static const char *MP4_ConvertMacCode( uint16_t i_code )
3327 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3328 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3329 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3330 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3331 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3332 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3333 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3334 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3335 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3336 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3337 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3338 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3339 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3340 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3341 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3342 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3343 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3344 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3345 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3346 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3348 { "cy", 128 }, { "eu", 129 },
3349 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3350 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3351 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3352 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3357 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3359 if( p_cvt[i].i_code == i_code )
3360 return p_cvt[i].psz_iso639_1;
3365 /******************************************************************************
3366 * Here are the functions used for fragmented MP4
3367 *****************************************************************************/
3370 * It computes the sample rate for a video track using current video chunk
3372 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3373 const mp4_track_t *p_track )
3375 if( p_track->cchunk->i_last_dts == 0 )
3382 const mp4_chunk_t *p_chunk = p_track->cchunk;
3384 uint32_t i_sample = p_chunk->i_sample_count;
3385 uint64_t i_first_dts = p_chunk->i_first_dts;
3386 uint64_t i_last_dts = p_chunk->i_last_dts;
3388 if( i_sample > 1 && i_first_dts < i_last_dts )
3389 vlc_ureduce( pi_num, pi_den,
3390 ( i_sample - 1) * p_track->i_timescale,
3391 i_last_dts - i_first_dts,
3396 * Build raw avcC box (without the 8 bytes header)
3397 * \return The size of the box.
3399 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3400 const unsigned cpd_len )
3403 unsigned sps_len = 0, pps_len = 0;
3404 const uint32_t mark = 0x00000001;
3406 assert( CodecPrivateData[0] == 0 );
3407 assert( CodecPrivateData[1] == 0 );
3408 assert( CodecPrivateData[2] == 0 );
3409 assert( CodecPrivateData[3] == 1 );
3411 uint32_t length = cpd_len + 3;
3412 avcC = calloc( length, 1 );
3413 if( unlikely( avcC == NULL ) )
3416 uint8_t *sps = avcC + 8;
3418 uint32_t candidate = ~mark;
3419 CodecPrivateData += 4;
3420 for( unsigned i = 0; i < cpd_len - 4; i++ )
3422 sps[i] = CodecPrivateData[i];
3423 candidate = (candidate << 8) | CodecPrivateData[i];
3424 if( candidate == mark )
3435 uint8_t *pps = sps + sps_len + 3;
3436 pps_len = cpd_len - sps_len - 4 * 2;
3437 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3440 uint8_t AVCProfileIndication = 0x64;
3441 uint8_t profile_compatibility = 0x40;
3442 uint8_t AVCLevelIndication = 0x1f;
3443 uint8_t lengthSizeMinusOne = 0x03;
3446 avcC[1] = AVCProfileIndication;
3447 avcC[2] = profile_compatibility;
3448 avcC[3] = AVCLevelIndication;
3449 avcC[4] = 0xfc + lengthSizeMinusOne;
3451 avcC[6] = (sps_len & 0xff00)>>8;
3452 avcC[7] = sps_len & 0xff;
3454 avcC[8+sps_len] = 1;
3455 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3456 avcC[10+sps_len] = pps_len & 0xff;
3463 * Build a mp4_track_t from a StraBox
3466 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3468 fmt->i_extra = p_data->cpd_len;
3469 fmt->p_extra = malloc( p_data->cpd_len );
3470 if( unlikely( !fmt->p_extra ) )
3472 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3476 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3478 demux_sys_t *p_sys = p_demux->p_sys;
3480 MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3482 return VLC_EGENERIC;
3484 p_track->b_ok = true;
3485 p_track->b_selected = false;
3486 p_track->i_sample_count = UINT32_MAX;
3488 p_track->i_timescale = p_sys->i_timescale;
3489 p_track->i_width = p_data->MaxWidth;
3490 p_track->i_height = p_data->MaxHeight;
3491 p_track->i_track_ID = p_data->i_track_ID;
3493 es_format_t *fmt = &p_track->fmt;
3495 return VLC_EGENERIC;
3497 es_format_Init( fmt, p_data->i_es_cat, 0 );
3499 /* Set language FIXME */
3500 fmt->psz_language = strdup( "en" );
3502 fmt->i_original_fourcc = p_data->FourCC;
3503 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3505 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3506 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3507 * for MS weird use of FourCC*/
3508 switch( fmt->i_cat )
3511 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3512 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3513 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3515 fmt->i_extra = build_raw_avcC( p_extra,
3516 p_data->CodecPrivateData, p_data->cpd_len );
3520 ret = MP4_SetCodecExtraData( fmt, p_data );
3521 if( ret != VLC_SUCCESS )
3525 fmt->video.i_width = p_data->MaxWidth;
3526 fmt->video.i_height = p_data->MaxHeight;
3527 fmt->video.i_bits_per_pixel = 0x18;
3528 fmt->video.i_visible_width = p_data->MaxWidth;
3529 fmt->video.i_visible_height = p_data->MaxHeight;
3532 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3533 &fmt->video.i_frame_rate_base, p_track );
3535 if( fmt->video.i_frame_rate_base != 0 )
3537 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3538 (float)fmt->video.i_frame_rate_base;
3541 p_demux->p_sys->f_fps = 24;
3546 fmt->audio.i_channels = p_data->Channels;
3547 fmt->audio.i_rate = p_data->SamplingRate;
3548 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3549 fmt->audio.i_blockalign = p_data->nBlockAlign;
3551 fmt->i_bitrate = p_data->Bitrate;
3553 ret = MP4_SetCodecExtraData( fmt, p_data );
3554 if( ret != VLC_SUCCESS )
3567 * Return the track identified by tid
3569 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3571 demux_sys_t *p_sys = p_demux->p_sys;
3573 mp4_track_t *ret = NULL;
3574 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3576 ret = &p_sys->track[i];
3577 if( ret->i_track_ID == tid )
3580 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3584 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3586 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3587 mp4_chunk_t *ck = tk->cchunk;
3588 while( ck->i_sample < ck->i_sample_count )
3593 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3596 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3597 assert( sample_size > 0 );
3598 p_block = block_Alloc( sample_size );
3599 if( unlikely( !p_block ) )
3602 uint8_t *src = ck->p_sample_data[ck->i_sample];
3603 memcpy( p_block->p_buffer, src, sample_size );
3607 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3609 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3611 p_block->i_pts = p_block->i_dts + i_delta;
3612 else if( tk->fmt.i_cat != VIDEO_ES )
3613 p_block->i_pts = p_block->i_dts;
3615 p_block->i_pts = VLC_TS_INVALID;
3617 es_out_Send( p_demux->out, tk->p_es, p_block );
3625 * \Note If we call that function too soon,
3626 * before the track has been selected by MP4_TrackSelect
3627 * (during the first execution of Demux), then the track gets disabled
3629 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3631 demux_sys_t *p_sys = p_demux->p_sys;
3633 uint32_t i_sample = 0;
3634 bool b_smooth = false;
3635 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3637 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3642 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3643 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3644 return VLC_EGENERIC;
3648 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3650 return VLC_EGENERIC;
3653 i_sample = p_track->i_sample;
3654 es_out_Del( p_demux->out, p_track->p_es );
3655 es_format_Clean( &p_track->fmt );
3658 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3660 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3662 p_track->i_sample = i_sample;
3664 /* Temporary hack until we support track selection */
3665 p_track->b_selected = true;
3666 p_track->b_ok = true;
3667 p_track->b_enable = true;
3669 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3670 p_track->b_codec_need_restart = false;
3676 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3677 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3678 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3679 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3681 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3683 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3684 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3687 msg_Warn( p_demux, "no moof box found!" );
3688 return VLC_EGENERIC;
3691 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3694 msg_Warn( p_demux, "no traf box found!" );
3695 return VLC_EGENERIC;
3698 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3701 msg_Warn( p_demux, "no tfhd box found!" );
3702 return VLC_EGENERIC;
3705 uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
3706 *i_tk_id = i_track_ID;
3707 assert( i_track_ID > 0 );
3708 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3710 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
3712 return VLC_EGENERIC;
3714 mp4_chunk_t *ret = p_track->cchunk;
3716 if( BOXDATA(p_tfhd)->b_empty )
3717 msg_Warn( p_demux, "No samples in this chunk!" );
3719 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3720 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3721 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3722 * and so on. Finally, suppose that we get the chunks the other way around,
3723 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3724 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3725 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3726 * flush it, i.e. send to the decoder the samples not yet sent.
3727 * Note that all the samples to be flushed should worth less than 100 ms,
3728 * (though I did not do the formal proof) and thus this flushing mechanism
3729 * should not cause A/V sync issues, or delays or whatever.
3731 if( ret->i_sample < ret->i_sample_count )
3732 FlushChunk( p_demux, p_track );
3734 if( ret->i_sample_count )
3735 FreeAndResetChunk( ret );
3737 uint32_t default_duration = 0;
3738 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3739 default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
3741 uint32_t default_size = 0;
3742 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3743 default_size = BOXDATA(p_tfhd)->i_default_sample_size;
3745 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3748 msg_Warn( p_demux, "no trun box found!" );
3749 return VLC_EGENERIC;
3751 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3753 ret->i_sample_count = p_trun_data->i_sample_count;
3754 assert( ret->i_sample_count > 0 );
3755 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3756 ret->i_sample_first = p_track->i_sample_first;
3757 p_track->i_sample_first += ret->i_sample_count;
3759 ret->i_first_dts = p_track->i_first_dts;
3761 /* XXX I already saw DASH content with no default_duration and no
3762 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3763 * This chunk of code might be buggy with segments having
3764 * more than one subsegment. */
3765 if( !default_duration )
3767 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
3769 default_duration = BOXDATA(p_trex)->i_default_sample_duration;
3772 MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
3773 assert( p_sidx_data->i_reference_count == 1 );
3775 if( p_sidx_data->i_timescale == 0 )
3776 return VLC_EGENERIC;
3778 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3779 p_sidx_data->i_timescale;
3780 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3785 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3787 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3788 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3790 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3793 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3794 if( !ret->p_sample_count_pts )
3797 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3799 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3800 if( !ret->p_sample_offset_pts )
3804 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3805 if( !ret->p_sample_size )
3808 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3809 if( !ret->p_sample_data )
3812 uint32_t dur = 0, i_mdatlen = 0, len;
3813 uint32_t chunk_duration = 0, chunk_size = 0;
3815 /* Skip header of mdat */
3817 int i_read = stream_Read( p_demux->s, &mdat, 8 );
3818 i_mdatlen = GetDWBE( mdat );
3819 if ( i_read < 8 || i_mdatlen < 8 ||
3820 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
3821 return VLC_EGENERIC;
3823 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3825 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3826 dur = p_trun_data->p_samples[i].i_duration;
3828 dur = default_duration;
3829 ret->p_sample_delta_dts[i] = dur;
3830 chunk_duration += dur;
3832 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3834 if( ret->p_sample_offset_pts )
3836 ret->p_sample_offset_pts[i] =
3837 p_trun_data->p_samples[i].i_composition_time_offset;
3840 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3841 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3843 len = ret->p_sample_size[i] = default_size;
3845 if ( chunk_size + len > ( i_mdatlen - 8 ) )
3846 return VLC_EGENERIC;
3848 ret->p_sample_data[i] = malloc( len );
3849 if( ret->p_sample_data[i] == NULL )
3851 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
3853 return VLC_EGENERIC;
3856 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3857 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3859 if( p_track->b_codec_need_restart &&
3860 p_track->fmt.i_cat == VIDEO_ES )
3861 ReInitDecoder( p_demux, p_track );
3863 /* Skip if we didn't reach the end of mdat box */
3864 if ( chunk_size < (i_mdatlen - 8) )
3865 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
3867 p_track->b_has_non_empty_cchunk = true;
3872 * Get the next chunk of the track identified by i_tk_id.
3873 * \Note We don't want to seek all the time, so if the first chunk given by the
3874 * input method doesn't belong to the right track, we don't throw it away,
3875 * and so, in general, this function fetch more than one chunk.
3876 * Not to mention that a new init segment might be put everywhere
3877 * between two chunks by the input method.
3879 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3881 demux_sys_t *p_sys = p_demux->p_sys;
3882 mp4_track_t *p_track;
3884 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3886 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3888 return VLC_EGENERIC;
3890 if( !p_chunk->p_first )
3891 goto MP4_frg_GetChunks_Error;
3892 uint32_t i_type = p_chunk->p_first->i_type;
3894 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3896 MP4_BoxFree( p_demux->s, p_sys->p_root );
3897 p_sys->p_root = p_chunk;
3899 if( i_type == ATOM_ftyp ) /* DASH */
3901 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3904 msg_Warn( p_demux, "No tkhd found!" );
3905 goto MP4_frg_GetChunks_Error;
3907 tid = BOXDATA(p_tkhd)->i_track_ID;
3909 else /* Smooth Streaming */
3911 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3912 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3913 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3915 msg_Warn( p_demux, "No StraBox found!" );
3916 goto MP4_frg_GetChunks_Error;
3918 tid = BOXDATA(p_stra)->i_track_ID;
3921 p_track = MP4_frg_GetTrackByID( p_demux, tid );
3923 goto MP4_frg_GetChunks_Error;
3924 p_track->b_codec_need_restart = true;
3926 return MP4_frg_GetChunks( p_demux, i_tk_id );
3929 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3930 goto MP4_frg_GetChunks_Error;
3932 MP4_BoxFree( p_demux->s, p_chunk );
3934 if( tid == i_tk_id )
3939 MP4_frg_GetChunks_Error:
3940 MP4_BoxFree( p_demux->s, p_chunk );
3941 return VLC_EGENERIC;
3947 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3949 if( !p_track->b_ok || p_track->b_chapter )
3951 return VLC_EGENERIC;
3954 if( p_track->b_selected )
3956 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3960 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3961 p_track->b_selected = true;
3966 * DemuxFrg: read packet and send them to decoders
3967 * \return 1 on success, 0 on error.
3968 * TODO check for newly selected track
3970 int DemuxFrg( demux_t *p_demux )
3972 demux_sys_t *p_sys = p_demux->p_sys;
3974 unsigned i_track_selected;
3976 /* check for newly selected/unselected track */
3977 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3979 mp4_track_t *tk = &p_sys->track[i_track];
3982 if( !tk->b_ok || tk->b_chapter )
3985 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3986 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3988 if( tk->b_selected && !b )
3990 MP4_TrackUnselect( p_demux, tk );
3992 else if( !tk->b_selected && b)
3994 MP4_frg_TrackSelect( p_demux, tk );
3997 if( tk->b_selected )
4001 if( i_track_selected <= 0 )
4003 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
4004 if( p_sys->i_timescale > 0 )
4006 int64_t i_length = CLOCK_FREQ *
4007 (mtime_t)p_sys->i_duration /
4008 (mtime_t)p_sys->i_timescale;
4009 if( MP4_GetMoviePTS( p_sys ) >= i_length )
4014 msg_Warn( p_demux, "no track selected, exiting..." );
4018 /* first wait for the good time to read a packet */
4019 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4021 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4023 /* we will read 100ms for each stream so ...*/
4024 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4026 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4028 mp4_track_t *tk = &p_sys->track[i_track];
4030 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4032 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4036 if( !tk->b_has_non_empty_cchunk )
4038 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4040 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4045 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4050 mp4_chunk_t *ck = tk->cchunk;
4051 if( ck->i_sample >= ck->i_sample_count )
4053 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4054 ck->i_sample, ck->i_sample_count );
4058 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4059 p_block = block_Alloc( sample_size );
4060 uint8_t *src = ck->p_sample_data[ck->i_sample];
4061 memcpy( p_block->p_buffer, src, sample_size );
4064 if( ck->i_sample == ck->i_sample_count )
4065 tk->b_has_non_empty_cchunk = false;
4068 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4070 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4072 p_block->i_pts = p_block->i_dts + i_delta;
4073 else if( tk->fmt.i_cat != VIDEO_ES )
4074 p_block->i_pts = p_block->i_dts;
4076 p_block->i_pts = VLC_TS_INVALID;
4078 es_out_Send( p_demux->out, tk->p_es, p_block );
4082 if( !tk->b_has_non_empty_cchunk )