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 */
86 MP4_Box_t *p_tref_chap;
89 input_title_t *p_title;
92 /*****************************************************************************
93 * Declaration of local function
94 *****************************************************************************/
95 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
96 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
97 static void MP4_TrackDestroy( mp4_track_t * );
99 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
100 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
102 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
104 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
105 static uint32_t MP4_TrackSampleSize( mp4_track_t *, uint32_t * );
106 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
107 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
109 static void MP4_UpdateSeekpoint( demux_t * );
110 static const char *MP4_ConvertMacCode( uint16_t );
112 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
114 uint32_t i_return = 0;
115 if ( i_toread > INT32_MAX )
117 i_return = stream_Read( s, p_read, INT32_MAX );
118 if ( i_return < INT32_MAX )
121 i_toread -= INT32_MAX;
123 i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
127 /* Return time in microsecond of a track */
128 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
130 demux_sys_t *p_sys = p_demux->p_sys;
132 if( p_sys->b_fragmented )
133 chunk = *p_track->cchunk;
135 chunk = p_track->chunk[p_track->i_chunk];
137 unsigned int i_index = 0;
138 unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
139 int64_t i_dts = chunk.i_first_dts;
141 while( i_sample > 0 )
143 if( i_sample > chunk.p_sample_count_dts[i_index] )
145 i_dts += chunk.p_sample_count_dts[i_index] *
146 chunk.p_sample_delta_dts[i_index];
147 i_sample -= chunk.p_sample_count_dts[i_index];
152 i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
157 /* now handle elst */
158 if( p_track->p_elst )
160 demux_sys_t *p_sys = p_demux->p_sys;
161 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
163 /* convert to offset */
164 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
165 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
166 elst->i_media_time[p_track->i_elst] > 0 )
168 i_dts -= elst->i_media_time[p_track->i_elst];
171 /* add i_elst_time */
172 i_dts += p_track->i_elst_time * p_track->i_timescale /
175 if( i_dts < 0 ) i_dts = 0;
178 return CLOCK_FREQ * i_dts / p_track->i_timescale;
181 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
183 demux_sys_t *p_sys = p_demux->p_sys;
185 if( p_sys->b_fragmented )
186 ck = p_track->cchunk;
188 ck = &p_track->chunk[p_track->i_chunk];
190 unsigned int i_index = 0;
191 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
193 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
196 for( i_index = 0;; i_index++ )
198 if( i_sample < ck->p_sample_count_pts[i_index] )
199 return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
200 (int64_t)p_track->i_timescale;
202 i_sample -= ck->p_sample_count_pts[i_index];
206 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
208 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
211 static void LoadChapter( demux_t *p_demux );
213 static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
215 demux_sys_t *p_sys = p_demux->p_sys;
217 if( b_smooth ) /* Smooth Streaming */
219 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
221 goto LoadInitFragError;
225 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
226 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
227 goto LoadInitFragError;
228 /* Get number of tracks */
230 for( int i = 0; i < 3; i++ )
232 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
233 if( p_stra && p_stra->data.p_stra->i_track_ID )
235 /* Get timescale and duration of the video track; */
236 if( p_sys->i_timescale == 0 )
238 p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
239 p_sys->i_duration = p_stra->data.p_stra->i_duration;
240 if( p_sys->i_timescale == 0 )
242 msg_Err( p_demux, "bad timescale" );
243 goto LoadInitFragError;
251 /* Load all boxes ( except raw data ) */
252 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
254 goto LoadInitFragError;
260 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
264 /* Does lookup for remaining boxes */
265 static int ProbeFragments( demux_t *p_demux )
267 demux_sys_t *p_sys = p_demux->p_sys;
269 msg_Dbg( p_demux, "probing fragments from %"PRId64, stream_Tell( p_demux->s ) );
271 MP4_ReadBoxContainerRaw( p_demux->s, p_sys->p_root );
276 static int InitTracks( demux_t *p_demux )
278 demux_sys_t *p_sys = p_demux->p_sys;
280 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
281 if( p_sys->track == NULL )
284 if( p_sys->b_fragmented )
286 mp4_track_t *p_track;
287 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
289 p_track = &p_sys->track[i];
290 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
291 if( unlikely( !p_track->cchunk ) )
293 free( p_sys->track );
301 static void CreateTracksFromSmooBox( demux_t *p_demux )
303 demux_sys_t *p_sys = p_demux->p_sys;
305 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
306 mp4_track_t *p_track;
308 for( int i = 0; i < 3; i++ )
310 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
311 if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
315 p_track = &p_sys->track[j]; j++;
316 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
317 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
322 /*****************************************************************************
323 * Open: check file and initializes MP4 structures
324 *****************************************************************************/
325 static int Open( vlc_object_t * p_this )
327 demux_t *p_demux = (demux_t *)p_this;
330 const uint8_t *p_peek;
340 /* A little test to see if it could be a mp4 */
341 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
343 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
354 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
357 /* We don't yet support f4v, but avformat does. */
358 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
365 /* create our structure that will contains all data */
366 p_sys = calloc( 1, sizeof( demux_sys_t ) );
371 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
372 if( !p_sys->b_seekable )
374 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
378 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
380 /*Set exported functions */
381 p_demux->pf_demux = Demux;
382 p_demux->pf_control = Control;
384 p_demux->p_sys = p_sys;
386 /* Is it Smooth Streaming? */
387 bool b_smooth = false;
388 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
389 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
392 p_sys->b_fragmented = true;
395 if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
398 /* LoadInitFrag early failed */
399 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
401 if ( p_sys->b_seekable )
403 /* Probe remaining to check if there's really fragments
404 or if that file is just ready to append fragments */
405 ProbeFragments( p_demux );
406 p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
409 p_sys->b_fragmented = true;
412 if( p_sys->b_fragmented )
414 p_demux->pf_demux = DemuxFrg;
419 if( InitTracks( p_demux ) != VLC_SUCCESS )
421 CreateTracksFromSmooBox( p_demux );
424 else if( p_sys->b_fragmented )
426 /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
427 * a file, and we let avformat do the job. */
428 msg_Warn( p_demux, "MP4 plugin discarded "\
429 "(fragmented, let avformat demux it)" );
430 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
433 else if( !p_sys->b_fastseekable )
435 msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
436 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
440 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
442 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
444 switch( p_ftyp->data.p_ftyp->i_major_brand )
448 "ISO Media file (isom) version %d.",
449 p_ftyp->data.p_ftyp->i_minor_version );
452 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
453 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
454 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
455 msg_Dbg( p_demux, "3GPP Media file Release: %c",
456 #ifdef WORDS_BIGENDIAN
457 p_ftyp->data.p_ftyp->i_major_brand
459 p_ftyp->data.p_ftyp->i_major_brand >> 24
463 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
464 msg_Dbg( p_demux, "Apple QuickTime file" );
466 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
467 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
471 "unrecognized major file specification (%4.4s).",
472 (char*)&p_ftyp->data.p_ftyp->i_major_brand );
478 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
481 /* the file need to have one moov box */
482 if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
484 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
488 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
491 /* we have a free box as a moov, rename it */
492 p_foov->i_type = ATOM_moov;
495 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
497 int i_count = MP4_BoxCount( p_rmra, "rmda" );
500 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
502 input_thread_t *p_input = demux_GetParentInput( p_demux );
503 input_item_t *p_current = input_GetItem( p_input );
505 input_item_node_t *p_subitems = input_item_node_Create( p_current );
507 for( i = 0; i < i_count; i++ )
509 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
513 if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
517 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
519 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
520 psz_ref, (char*)&i_ref_type );
522 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
524 if( strstr( psz_ref, "qt5gateQT" ) )
526 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
529 if( !strncmp( psz_ref, "http://", 7 ) ||
530 !strncmp( psz_ref, "rtsp://", 7 ) )
537 char *psz_path = strdup( p_demux->psz_location );
538 char *end = strrchr( psz_path, '/' );
539 if( end ) end[1] = '\0';
540 else *psz_path = '\0';
542 if( asprintf( &psz_absolute, "%s://%s%s",
543 p_demux->psz_access, psz_path, psz_ref ) < 0 )
547 input_item_node_Delete( p_subitems );
548 vlc_object_release( p_input) ;
553 psz_ref = psz_absolute;
556 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
557 input_item_t *p_item = input_item_New( psz_ref, NULL );
558 input_item_CopyOptions( p_current, p_item );
559 input_item_node_AppendItem( p_subitems, p_item );
560 vlc_gc_decref( p_item );
564 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
565 (char*)&p_rdrf->data.p_rdrf->i_ref_type );
569 input_item_node_PostAndDelete( p_subitems );
570 vlc_object_release( p_input );
573 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
577 msg_Err( p_demux, "cannot find /moov/mvhd" );
582 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
583 p_demux->pf_demux = DemuxRef;
589 p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
590 if( p_sys->i_timescale == 0 )
592 msg_Err( p_this, "bad timescale" );
595 p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
598 /* Try in mehd if fragmented */
599 if ( p_sys->i_duration == 0 )
601 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
603 p_sys->i_duration = p_mehd->data.p_mehd->i_fragment_duration;
606 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
608 msg_Err( p_demux, "cannot find any /moov/trak" );
611 msg_Dbg( p_demux, "found %d track%c",
613 p_sys->i_tracks ? 's':' ' );
615 if( InitTracks( p_demux ) != VLC_SUCCESS )
618 /* Search the first chap reference (like quicktime) and
619 * check that at least 1 stream is enabled */
620 p_sys->p_tref_chap = NULL;
621 b_enabled_es = false;
622 for( i = 0; i < p_sys->i_tracks; i++ )
624 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
627 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
628 if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
631 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
632 if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
633 p_sys->p_tref_chap = p_chap;
636 /* now process each track and extract all useful information */
637 for( i = 0; i < p_sys->i_tracks; i++ )
639 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
640 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
642 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
645 switch( p_sys->track[i].fmt.i_cat )
654 psz_cat = "subtitle";
662 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
663 p_sys->track[i].i_track_ID, psz_cat,
664 p_sys->track[i].b_enable ? "enable":"disable",
665 p_sys->track[i].fmt.psz_language ?
666 p_sys->track[i].fmt.psz_language : "undef" );
668 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
670 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
671 p_sys->track[i].i_track_ID,
672 p_sys->track[i].fmt.psz_language ?
673 p_sys->track[i].fmt.psz_language : "undef" );
677 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
678 p_sys->track[i].i_track_ID );
683 LoadChapter( p_demux );
690 MP4_BoxFree( p_demux->s, p_sys->p_root );
696 /*****************************************************************************
697 * Demux: read packet and send them to decoders
698 *****************************************************************************
699 * TODO check for newly selected track (ie audio upt to now )
700 *****************************************************************************/
701 static int Demux( demux_t *p_demux )
703 demux_sys_t *p_sys = p_demux->p_sys;
704 unsigned int i_track;
707 unsigned int i_track_selected;
709 /* check for newly selected/unselected track */
710 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
713 mp4_track_t *tk = &p_sys->track[i_track];
716 if( !tk->b_ok || tk->b_chapter ||
717 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
722 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
724 if( tk->b_selected && !b )
726 MP4_TrackUnselect( p_demux, tk );
728 else if( !tk->b_selected && b)
730 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
739 if( i_track_selected <= 0 )
741 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
742 if( p_sys->i_timescale > 0 )
744 int64_t i_length = CLOCK_FREQ *
745 (mtime_t)p_sys->i_duration /
746 (mtime_t)p_sys->i_timescale;
747 if( MP4_GetMoviePTS( p_sys ) >= i_length )
752 msg_Warn( p_demux, "no track selected, exiting..." );
757 MP4_UpdateSeekpoint( p_demux );
759 /* first wait for the good time to read a packet */
760 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
762 /* we will read 100ms for each stream so ...*/
763 mtime_t i_targettime = p_sys->i_pcr + CLOCK_FREQ/10;
764 bool b_data_sent = false;
766 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
768 mp4_track_t *tk = &p_sys->track[i_track];
770 if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
773 while( MP4_TrackGetDTS( p_demux, tk ) < i_targettime
774 || ( p_sys->i_pcr == VLC_TS_INVALID && !b_data_sent ) )
777 msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
778 MP4_TrackGetDTS( p_demux, tk ),
779 MP4_GetMoviePTS( p_sys ) );
781 uint32_t i_nb_samples = 0;
782 uint32_t i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
783 if( i_samplessize > 0 )
786 int64_t i_delta, i_newpos;
789 i_newpos = MP4_TrackGetPos( tk );
790 if( stream_Tell( p_demux->s ) != i_newpos )
792 if( stream_Seek( p_demux->s, i_newpos ) )
794 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
796 MP4_TrackUnselect( p_demux, tk );
802 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
804 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
806 MP4_TrackUnselect( p_demux, tk );
809 else if( tk->fmt.i_cat == SPU_ES )
811 if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
812 tk->fmt.i_codec != VLC_CODEC_SPU )
813 p_block->i_buffer = 0;
817 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
819 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
821 p_block->i_pts = p_block->i_dts + i_delta;
822 else if( tk->fmt.i_cat != VIDEO_ES )
823 p_block->i_pts = p_block->i_dts;
825 p_block->i_pts = VLC_TS_INVALID;
829 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
832 es_out_Send( p_demux->out, tk->p_es, p_block );
836 if( MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
843 p_sys->i_pcr = INT64_MAX;
844 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
846 mp4_track_t *tk = &p_sys->track[i_track];
847 if ( !tk->b_ok || !tk->b_selected ) continue;
848 p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
849 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
856 static void MP4_UpdateSeekpoint( demux_t *p_demux )
858 demux_sys_t *p_sys = p_demux->p_sys;
861 if( !p_sys->p_title )
863 i_time = MP4_GetMoviePTS( p_sys );
864 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
866 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
871 if( i != p_demux->info.i_seekpoint && i >= 0 )
873 p_demux->info.i_seekpoint = i;
874 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
877 /*****************************************************************************
879 ******************************************************************************/
880 static int Seek( demux_t *p_demux, mtime_t i_date )
882 demux_sys_t *p_sys = p_demux->p_sys;
883 unsigned int i_track;
885 /* First update global time */
886 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
887 p_sys->i_pcr = VLC_TS_INVALID;
889 /* Now for each stream try to go to this time */
890 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
892 mp4_track_t *tk = &p_sys->track[i_track];
893 MP4_TrackSeek( p_demux, tk, i_date );
895 MP4_UpdateSeekpoint( p_demux );
897 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
902 static int MP4_frg_Seek( demux_t *p_demux, double f )
904 demux_sys_t *p_sys = p_demux->p_sys;
906 int64_t i64 = stream_Size( p_demux->s );
907 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
913 /* update global time */
914 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
915 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
917 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
919 mp4_track_t *tk = &p_sys->track[i_track];
921 /* We don't want the current chunk to be flushed */
922 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
924 /* reset/update some values */
925 tk->i_sample = tk->i_sample_first = 0;
926 tk->i_first_dts = p_sys->i_time;
928 /* We want to discard the current chunk and get the next one at once */
929 tk->b_has_non_empty_cchunk = false;
931 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
936 /*****************************************************************************
938 *****************************************************************************/
939 static int Control( demux_t *p_demux, int i_query, va_list args )
941 demux_sys_t *p_sys = p_demux->p_sys;
948 case DEMUX_GET_POSITION:
949 pf = (double*)va_arg( args, double * );
950 if( p_sys->i_duration > 0 )
952 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
960 case DEMUX_SET_POSITION:
961 f = (double)va_arg( args, double );
962 if( p_sys->b_fragmented )
964 return MP4_frg_Seek( p_demux, f );
966 else if( p_sys->i_timescale > 0 )
968 i64 = (int64_t)( f * CLOCK_FREQ *
969 (double)p_sys->i_duration /
970 (double)p_sys->i_timescale );
971 return Seek( p_demux, i64 );
973 else return VLC_SUCCESS;
976 pi64 = (int64_t*)va_arg( args, int64_t * );
977 if( p_sys->i_timescale > 0 )
980 (mtime_t)p_sys->i_time /
981 (mtime_t)p_sys->i_timescale;
987 i64 = (int64_t)va_arg( args, int64_t );
988 return Seek( p_demux, i64 );
990 case DEMUX_GET_LENGTH:
991 pi64 = (int64_t*)va_arg( args, int64_t * );
992 if( p_sys->i_timescale > 0 )
995 (mtime_t)p_sys->i_duration /
996 (mtime_t)p_sys->i_timescale;
1002 pf = (double*)va_arg( args, double* );
1006 case DEMUX_GET_ATTACHMENTS:
1008 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1009 int *pi_int = va_arg( args, int * );
1011 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
1012 if ( !p_covr ) return VLC_EGENERIC;
1016 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1018 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
1023 return VLC_EGENERIC;
1025 *ppp_attach = (input_attachment_t**)
1026 malloc( sizeof(input_attachment_t*) * i_count );
1027 if( !(*ppp_attach) ) return VLC_ENOMEM;
1031 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1033 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1036 if ( !memcmp( p_box->data.p_data->p_blob,
1037 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1039 psz_mime = strdup( "image/png" );
1041 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1043 psz_mime = strdup( "image/jpeg" );
1050 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1052 (*ppp_attach)[i_count++] =
1053 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1054 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1055 free( psz_filename );
1063 free( *ppp_attach );
1064 return VLC_EGENERIC;
1072 case DEMUX_GET_META:
1074 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1075 MP4_Box_t *p_0xa9xxx;
1077 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1079 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1081 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1082 if( p_udta == NULL )
1084 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1085 if( p_udta == NULL && p_covr == NULL )
1086 return VLC_EGENERIC;
1091 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1092 p_0xa9xxx = p_0xa9xxx->p_next )
1095 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
1098 /* FIXME FIXME: should convert from whatever the character
1099 * encoding of MP4 meta data is to UTF-8. */
1100 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
1101 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1102 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1104 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1105 switch( p_0xa9xxx->i_type )
1107 case ATOM_0xa9nam: /* Full name */
1108 SET( vlc_meta_SetTitle );
1111 SET( vlc_meta_SetArtist );
1114 SET( vlc_meta_SetArtist );
1117 SET( vlc_meta_SetCopyright );
1119 case ATOM_0xa9day: /* Creation Date */
1120 SET( vlc_meta_SetDate );
1122 case ATOM_0xa9des: /* Description */
1123 SET( vlc_meta_SetDescription );
1125 case ATOM_0xa9gen: /* Genre */
1126 SET( vlc_meta_SetGenre );
1130 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1131 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1134 case ATOM_0xa9alb: /* Album */
1135 SET( vlc_meta_SetAlbum );
1138 case ATOM_0xa9trk: /* Track */
1139 SET( vlc_meta_SetTrackNum );
1144 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1145 p_0xa9xxx->data.p_trkn->i_track_number );
1146 vlc_meta_SetTrackNum( p_meta, psz_trck );
1147 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1149 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1150 p_0xa9xxx->data.p_trkn->i_track_total );
1151 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1155 case ATOM_0xa9cmt: /* Commment */
1156 SET( vlc_meta_SetDescription );
1159 case ATOM_0xa9url: /* URL */
1160 SET( vlc_meta_SetURL );
1163 case ATOM_0xa9too: /* Encoder Tool */
1164 case ATOM_0xa9enc: /* Encoded By */
1165 SET( vlc_meta_SetEncodedBy );
1169 SET( vlc_meta_SetPublisher );
1173 SET( vlc_meta_SetDirector );
1180 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1182 { ATOM_0xa9wrt, N_("Writer") },
1183 { ATOM_0xa9com, N_("Composer") },
1184 { ATOM_0xa9prd, N_("Producer") },
1185 { ATOM_0xa9inf, N_("Information") },
1186 { ATOM_0xa9dis, N_("Disclaimer") },
1187 { ATOM_0xa9req, N_("Requirements") },
1188 { ATOM_0xa9fmt, N_("Original Format") },
1189 { ATOM_0xa9dsa, N_("Display Source As") },
1190 { ATOM_0xa9hst, N_("Host Computer") },
1191 { ATOM_0xa9prf, N_("Performers") },
1192 { ATOM_0xa9ope, N_("Original Performer") },
1193 { ATOM_0xa9src, N_("Providers Source Content") },
1194 { ATOM_0xa9wrn, N_("Warning") },
1195 { ATOM_0xa9swr, N_("Software") },
1196 { ATOM_0xa9lyr, N_("Lyrics") },
1197 { ATOM_0xa9mak, N_("Record Company") },
1198 { ATOM_0xa9mod, N_("Model") },
1199 { ATOM_0xa9PRD, N_("Product") },
1200 { ATOM_0xa9grp, N_("Grouping") },
1201 { ATOM_0xa9gen, N_("Genre") },
1202 { ATOM_0xa9st3, N_("Sub-Title") },
1203 { ATOM_0xa9arg, N_("Arranger") },
1204 { ATOM_0xa9ard, N_("Art Director") },
1205 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1206 { ATOM_0xa9con, N_("Conductor") },
1207 { ATOM_0xa9des, N_("Song Description") },
1208 { ATOM_0xa9lnt, N_("Liner Notes") },
1209 { ATOM_0xa9phg, N_("Phonogram Rights") },
1210 { ATOM_0xa9pub, N_("Publisher") },
1211 { ATOM_0xa9sne, N_("Sound Engineer") },
1212 { ATOM_0xa9sol, N_("Soloist") },
1213 { ATOM_0xa9thx, N_("Thanks") },
1214 { ATOM_0xa9xpd, N_("Executive Producer") },
1217 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1219 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1221 char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1224 EnsureUTF8( psz_utf );
1225 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1235 case DEMUX_GET_TITLE_INFO:
1237 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1238 int *pi_int = (int*)va_arg( args, int* );
1239 int *pi_title_offset = (int*)va_arg( args, int* );
1240 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1242 if( !p_sys->p_title )
1243 return VLC_EGENERIC;
1246 *ppp_title = malloc( sizeof( input_title_t*) );
1247 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1248 *pi_title_offset = 0;
1249 *pi_seekpoint_offset = 0;
1252 case DEMUX_SET_TITLE:
1254 const int i_title = (int)va_arg( args, int );
1255 if( !p_sys->p_title || i_title != 0 )
1256 return VLC_EGENERIC;
1259 case DEMUX_SET_SEEKPOINT:
1261 const int i_seekpoint = (int)va_arg( args, int );
1262 if( !p_sys->p_title )
1263 return VLC_EGENERIC;
1264 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1267 case DEMUX_SET_NEXT_DEMUX_TIME:
1268 case DEMUX_SET_GROUP:
1269 case DEMUX_HAS_UNSUPPORTED_META:
1270 case DEMUX_GET_PTS_DELAY:
1271 case DEMUX_CAN_RECORD:
1272 return VLC_EGENERIC;
1275 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1276 return VLC_EGENERIC;
1280 /*****************************************************************************
1281 * Close: frees unused data
1282 *****************************************************************************/
1283 static void Close ( vlc_object_t * p_this )
1285 demux_t * p_demux = (demux_t *)p_this;
1286 demux_sys_t *p_sys = p_demux->p_sys;
1287 unsigned int i_track;
1289 msg_Dbg( p_demux, "freeing all memory" );
1291 MP4_BoxFree( p_demux->s, p_sys->p_root );
1292 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1294 MP4_TrackDestroy( &p_sys->track[i_track] );
1296 FREENULL( p_sys->track );
1298 if( p_sys->p_title )
1299 vlc_input_title_Delete( p_sys->p_title );
1306 /****************************************************************************
1307 * Local functions, specific to vlc
1308 ****************************************************************************/
1310 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1312 demux_sys_t *p_sys = p_demux->p_sys;
1315 p_sys->p_title = vlc_input_title_New();
1316 for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1318 seekpoint_t *s = vlc_seekpoint_New();
1320 s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1321 EnsureUTF8( s->psz_name );
1322 s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1323 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1326 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1328 demux_sys_t *p_sys = p_demux->p_sys;
1330 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1332 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1333 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1334 uint32_t i_nb_samples = 0;
1335 const uint32_t i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
1337 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1340 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1341 __MIN( sizeof(p_buffer), i_size ) );
1342 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1346 seekpoint_t *s = vlc_seekpoint_New();
1348 s->psz_name = strndup( &p_buffer[2], i_len );
1349 EnsureUTF8( s->psz_name );
1351 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1353 if( !p_sys->p_title )
1354 p_sys->p_title = vlc_input_title_New();
1355 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1358 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1359 tk->chunk[tk->i_chunk].i_sample_count )
1363 static void LoadChapter( demux_t *p_demux )
1365 demux_sys_t *p_sys = p_demux->p_sys;
1368 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1370 LoadChapterGpac( p_demux, p_chpl );
1372 else if( p_sys->p_tref_chap )
1374 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1377 /* Load the first subtitle track like quicktime */
1378 for( i = 0; i < p_chap->i_entry_count; i++ )
1380 for( j = 0; j < p_sys->i_tracks; j++ )
1382 mp4_track_t *tk = &p_sys->track[j];
1383 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1384 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1387 if( j < p_sys->i_tracks )
1389 LoadChapterApple( p_demux, &p_sys->track[j] );
1395 /* Add duration if titles are enabled */
1396 if( p_sys->p_title )
1398 p_sys->p_title->i_length = CLOCK_FREQ *
1399 (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1403 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1404 static int TrackCreateChunksIndex( demux_t *p_demux,
1405 mp4_track_t *p_demux_track )
1407 demux_sys_t *p_sys = p_demux->p_sys;
1408 if( p_sys->b_fragmented )
1411 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1414 unsigned int i_chunk;
1415 unsigned int i_index, i_last;
1417 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1418 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1419 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1421 return( VLC_EGENERIC );
1424 p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1425 if( !p_demux_track->i_chunk_count )
1427 msg_Warn( p_demux, "no chunk defined" );
1428 return( VLC_EGENERIC );
1430 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1431 sizeof( mp4_chunk_t ) );
1432 if( p_demux_track->chunk == NULL )
1437 /* first we read chunk offset */
1438 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1440 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1442 ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1444 ck->i_first_dts = 0;
1445 ck->p_sample_count_dts = NULL;
1446 ck->p_sample_delta_dts = NULL;
1447 ck->p_sample_count_pts = NULL;
1448 ck->p_sample_offset_pts = NULL;
1451 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1452 to be used for the sample XXX begin to 1
1453 We construct it begining at the end */
1454 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1455 i_index = p_stsc->data.p_stsc->i_entry_count;
1458 msg_Warn( p_demux, "cannot read chunk table or table empty" );
1459 return( VLC_EGENERIC );
1464 for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1465 i_chunk < i_last; i_chunk++ )
1467 if( i_chunk >= p_demux_track->i_chunk_count )
1469 msg_Warn( p_demux, "corrupted chunk table" );
1470 return VLC_EGENERIC;
1473 p_demux_track->chunk[i_chunk].i_sample_description_index =
1474 p_stsc->data.p_stsc->i_sample_description_index[i_index];
1475 p_demux_track->chunk[i_chunk].i_sample_count =
1476 p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1478 i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1481 p_demux_track->chunk[0].i_sample_first = 0;
1482 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1484 p_demux_track->chunk[i_chunk].i_sample_first =
1485 p_demux_track->chunk[i_chunk-1].i_sample_first +
1486 p_demux_track->chunk[i_chunk-1].i_sample_count;
1489 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1490 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1495 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1496 const uint32_t i_index,
1497 uint32_t i_index_samples_left,
1498 uint32_t i_sample_count,
1499 const uint32_t *pi_index_sample_count,
1500 const uint32_t i_table_count )
1502 uint32_t i_array_offset;
1503 while( i_sample_count > 0 )
1505 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1506 i_array_offset = i_index + *pi_entry;
1508 return VLC_EGENERIC;
1510 if ( i_array_offset >= i_table_count )
1512 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1513 return VLC_EGENERIC;
1516 if ( i_index_samples_left )
1518 if ( i_index_samples_left > i_sample_count )
1520 i_index_samples_left -= i_sample_count;
1522 *pi_entry +=1; /* No samples left, go copy */
1527 i_sample_count -= i_index_samples_left;
1528 i_index_samples_left = 0;
1535 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1543 static int TrackCreateSamplesIndex( demux_t *p_demux,
1544 mp4_track_t *p_demux_track )
1546 demux_sys_t *p_sys = p_demux->p_sys;
1547 if( p_sys->b_fragmented )
1551 MP4_Box_data_stsz_t *stsz;
1552 /* TODO use also stss and stsh table for seeking */
1553 /* FIXME use edit table */
1556 * Gives the sample size for each samples. There is also a stz2 table
1557 * (compressed form) that we need to implement TODO */
1558 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1561 /* FIXME and stz2 */
1562 msg_Warn( p_demux, "cannot find STSZ box" );
1563 return VLC_EGENERIC;
1565 stsz = p_box->data.p_stsz;
1567 /* Use stsz table to create a sample number -> sample size table */
1568 p_demux_track->i_sample_count = stsz->i_sample_count;
1569 if( stsz->i_sample_size )
1571 /* 1: all sample have the same size, so no need to construct a table */
1572 p_demux_track->i_sample_size = stsz->i_sample_size;
1573 p_demux_track->p_sample_size = NULL;
1577 /* 2: each sample can have a different size */
1578 p_demux_track->i_sample_size = 0;
1579 p_demux_track->p_sample_size =
1580 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1581 if( p_demux_track->p_sample_size == NULL )
1584 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1586 p_demux_track->p_sample_size[i_sample] =
1587 stsz->i_entry_size[i_sample];
1591 /* Use stts table to create a sample number -> dts table.
1592 * XXX: if we don't want to waste too much memory, we can't expand
1593 * the box! so each chunk will contain an "extract" of this table
1594 * for fast research (problem with raw stream where a sample is sometime
1595 * just channels*bits_per_sample/8 */
1597 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1598 * differing in 2/2 fields and 1 signedness */
1600 mtime_t i_next_dts = 0;
1602 * Gives mapping between sample and decoding time
1604 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1607 msg_Warn( p_demux, "cannot find STTS box" );
1608 return VLC_EGENERIC;
1612 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
1614 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
1616 /* Create sample -> dts table per chunk */
1617 uint32_t i_index = 0;
1618 uint32_t i_current_index_samples_left = 0;
1620 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1622 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1623 uint32_t i_entry, i_sample_count;
1625 /* save first dts */
1626 ck->i_first_dts = i_next_dts;
1627 ck->i_last_dts = i_next_dts;
1629 /* count how many entries are needed for this chunk
1630 * for p_sample_delta_dts and p_sample_count_dts */
1633 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1634 i_current_index_samples_left,
1636 stts->pi_sample_count,
1637 stts->i_entry_count );
1638 if ( i_ret != VLC_SUCCESS )
1642 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1643 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1644 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1646 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1651 i_sample_count = ck->i_sample_count;
1653 for( uint32_t i = 0; i < i_entry; i++ )
1655 if ( i_current_index_samples_left )
1657 if ( i_current_index_samples_left > i_sample_count )
1659 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1660 ck->p_sample_count_dts[i] = i_sample_count;
1661 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1662 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1663 i_current_index_samples_left -= i_sample_count;
1665 assert( i == i_entry - 1 );
1670 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
1671 ck->p_sample_count_dts[i] = i_current_index_samples_left;
1672 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1673 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1674 i_sample_count -= i_current_index_samples_left;
1675 i_current_index_samples_left = 0;
1681 if ( stts->pi_sample_count[i_index] > i_sample_count )
1683 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1684 ck->p_sample_count_dts[i] = i_sample_count;
1685 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1686 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1687 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
1689 assert( i == i_entry - 1 );
1690 // keep building from same index
1694 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
1695 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
1696 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1697 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1698 i_sample_count -= stts->pi_sample_count[i_index];
1709 * Gives the delta between decoding time (dts) and composition table (pts)
1711 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1714 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1716 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
1718 /* Create pts-dts table per chunk */
1719 uint32_t i_index = 0;
1720 uint32_t i_current_index_samples_left = 0;
1722 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1724 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1725 uint32_t i_entry, i_sample_count;
1727 /* count how many entries are needed for this chunk
1728 * for p_sample_offset_pts and p_sample_count_pts */
1730 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1731 i_current_index_samples_left,
1733 ctts->pi_sample_count,
1734 ctts->i_entry_count );
1735 if ( i_ret != VLC_SUCCESS )
1739 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1740 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1741 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1743 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1748 i_sample_count = ck->i_sample_count;
1750 for( uint32_t i = 0; i < i_entry; i++ )
1752 if ( i_current_index_samples_left )
1754 if ( i_current_index_samples_left > i_sample_count )
1756 ck->p_sample_count_pts[i] = i_sample_count;
1757 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1758 i_current_index_samples_left -= i_sample_count;
1760 assert( i == i_entry - 1 );
1765 ck->p_sample_count_pts[i] = i_current_index_samples_left;
1766 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1767 i_sample_count -= i_current_index_samples_left;
1768 i_current_index_samples_left = 0;
1774 if ( ctts->pi_sample_count[i_index] > i_sample_count )
1776 ck->p_sample_count_pts[i] = i_sample_count;
1777 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1778 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
1780 assert( i == i_entry - 1 );
1781 // keep building from same index
1785 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
1786 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1787 i_sample_count -= ctts->pi_sample_count[i_index];
1797 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
1798 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1799 i_next_dts / p_demux_track->i_timescale );
1806 * It computes the sample rate for a video track using the given sample
1809 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1810 const mp4_track_t *p_track,
1811 unsigned i_sd_index,
1817 if( p_track->i_chunk_count <= 0 )
1821 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1822 while( p_chunk > &p_track->chunk[0] &&
1823 p_chunk[-1].i_sample_description_index == i_sd_index )
1828 uint64_t i_sample = 0;
1829 uint64_t i_first_dts = p_chunk->i_first_dts;
1830 uint64_t i_last_dts;
1833 i_sample += p_chunk->i_sample_count;
1834 i_last_dts = p_chunk->i_last_dts;
1837 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1838 p_chunk->i_sample_description_index == i_sd_index );
1840 if( i_sample > 1 && i_first_dts < i_last_dts )
1841 vlc_ureduce( pi_num, pi_den,
1842 ( i_sample - 1) * p_track->i_timescale,
1843 i_last_dts - i_first_dts,
1849 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1851 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1852 unsigned int i_chunk, es_out_id_t **pp_es )
1854 demux_sys_t *p_sys = p_demux->p_sys;
1855 unsigned int i_sample_description_index;
1857 if( p_sys->b_fragmented )
1858 i_sample_description_index = 1; /* XXX */
1860 i_sample_description_index =
1861 p_track->chunk[i_chunk].i_sample_description_index;
1863 MP4_Box_t *p_sample;
1872 if( !i_sample_description_index )
1874 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1875 p_track->i_track_ID );
1876 return VLC_EGENERIC;
1879 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
1880 i_sample_description_index - 1 );
1883 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
1885 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1886 p_track->i_track_ID );
1887 return VLC_EGENERIC;
1890 p_track->p_sample = p_sample;
1892 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1894 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1896 p_sample->i_type = p_frma->data.p_frma->i_type;
1899 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1901 p_enda = MP4_BoxGet( p_sample, "enda" );
1903 p_pasp = MP4_BoxGet( p_sample, "pasp" );
1906 switch( p_track->fmt.i_cat )
1909 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1910 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1911 p_track->fmt.video.i_bits_per_pixel =
1912 p_sample->data.p_sample_vide->i_depth;
1914 /* fall on display size */
1915 if( p_track->fmt.video.i_width <= 0 )
1916 p_track->fmt.video.i_width = p_track->i_width;
1917 if( p_track->fmt.video.i_height <= 0 )
1918 p_track->fmt.video.i_height = p_track->i_height;
1920 /* Find out apect ratio from display size */
1921 if( p_track->i_width > 0 && p_track->i_height > 0 &&
1922 /* Work-around buggy muxed files */
1923 p_sample->data.p_sample_vide->i_width != p_track->i_width )
1925 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
1926 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1928 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1929 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1931 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1932 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1935 /* Support for cropping (eg. in H263 files) */
1936 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1937 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1940 TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1941 &p_track->fmt.video.i_frame_rate_base,
1942 p_track, i_sample_description_index, i_chunk );
1943 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1944 (float)p_track->fmt.video.i_frame_rate_base;
1947 switch( (int)p_track->f_rotation ) {
1949 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1952 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1955 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1962 p_track->fmt.audio.i_channels =
1963 p_sample->data.p_sample_soun->i_channelcount;
1964 p_track->fmt.audio.i_rate =
1965 p_sample->data.p_sample_soun->i_sampleratehi;
1966 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1967 p_sample->data.p_sample_soun->i_sampleratehi *
1968 p_sample->data.p_sample_soun->i_samplesize;
1969 p_track->fmt.audio.i_bitspersample =
1970 p_sample->data.p_sample_soun->i_samplesize;
1972 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1974 MP4_Box_data_sample_soun_t *p_soun;
1975 p_soun = p_sample->data.p_sample_soun;
1977 if( p_soun->i_qt_version == 0 )
1979 switch( p_sample->i_type )
1981 case VLC_CODEC_ADPCM_IMA_QT:
1982 p_soun->i_qt_version = 1;
1983 p_soun->i_sample_per_packet = 64;
1984 p_soun->i_bytes_per_packet = 34;
1985 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
1986 p_soun->i_bytes_per_sample = 2;
1988 case VLC_CODEC_MACE3:
1989 p_soun->i_qt_version = 1;
1990 p_soun->i_sample_per_packet = 6;
1991 p_soun->i_bytes_per_packet = 2;
1992 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1993 p_soun->i_bytes_per_sample = 2;
1995 case VLC_CODEC_MACE6:
1996 p_soun->i_qt_version = 1;
1997 p_soun->i_sample_per_packet = 12;
1998 p_soun->i_bytes_per_packet = 2;
1999 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2000 p_soun->i_bytes_per_sample = 2;
2002 case VLC_CODEC_ALAW:
2003 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
2004 p_soun->i_samplesize = 8;
2005 p_track->i_sample_size = p_soun->i_channelcount;
2007 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
2008 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
2009 case VLC_FOURCC( 't', 'w', 'o', 's' ):
2010 case VLC_FOURCC( 's', 'o', 'w', 't' ):
2011 /* What would be the fun if you could trust the .mov */
2012 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
2019 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
2021 p_soun->i_qt_version = 0;
2024 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
2026 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2028 switch( p_sample->i_type )
2030 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2031 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2033 if( p_track->i_sample_size > 1 )
2034 p_soun->i_qt_version = 0;
2037 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2038 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2039 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2040 p_soun->i_qt_version = 0;
2047 if( p_track->i_sample_size != 0 &&
2048 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2049 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2051 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2052 p_sample->data.p_sample_soun->i_qt_version = 0;
2061 /* It's a little ugly but .. there are special cases */
2062 switch( p_sample->i_type )
2064 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2065 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2067 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2070 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2072 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2074 p_track->fmt.i_codec = VLC_CODEC_A52;
2077 static const int pi_bitrate[] = {
2084 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2085 p_track->fmt.audio.i_channels = 0;
2086 p_track->fmt.i_bitrate = 0;
2087 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2088 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2089 p_track->fmt.audio.i_bitspersample = 0;
2093 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2095 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2099 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2100 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2102 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2104 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2105 p_track->fmt.i_codec = VLC_CODEC_U8;
2107 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2109 /* Buggy files workaround */
2110 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2111 p_sample->data.p_sample_soun->i_sampleratehi) )
2113 MP4_Box_data_sample_soun_t *p_soun =
2114 p_sample->data.p_sample_soun;
2116 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2117 "(%u), making both equal (report any problem).",
2118 p_track->i_timescale, p_soun->i_sampleratehi );
2120 if( p_soun->i_sampleratehi != 0 )
2121 p_track->i_timescale = p_soun->i_sampleratehi;
2123 p_soun->i_sampleratehi = p_track->i_timescale;
2128 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2129 p_track->fmt.i_codec = VLC_CODEC_H263;
2132 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2133 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2135 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2136 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2139 text_style_t *p_style = text_style_New();
2142 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2143 p_style->i_font_size = p_text->i_font_size;
2144 if ( p_text->i_font_color )
2146 p_style->i_font_color = p_text->i_font_color >> 8;
2147 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2149 if ( p_text->i_background_color[3] >> 8 )
2151 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2152 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2153 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2154 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2157 p_track->fmt.subs.p_style = p_style;
2159 /* FIXME UTF-8 doesn't work here ? */
2160 if( p_track->b_mac_encoding )
2161 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2163 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2166 case VLC_FOURCC('y','v','1','2'):
2167 p_track->fmt.i_codec = VLC_CODEC_YV12;
2169 case VLC_FOURCC('y','u','v','2'):
2170 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2173 case VLC_FOURCC('i','n','2','4'):
2174 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2175 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2177 case VLC_FOURCC('i','n','3','2'):
2178 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2179 VLC_CODEC_S32L : VLC_CODEC_S32B;
2181 case VLC_FOURCC('f','l','3','2'):
2182 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2183 VLC_CODEC_F32L : VLC_CODEC_F32B;
2185 case VLC_FOURCC('f','l','6','4'):
2186 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2187 VLC_CODEC_F64L : VLC_CODEC_F64B;
2189 case VLC_CODEC_DVD_LPCM:
2191 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2192 if( p_soun->i_qt_version == 2 &&
2193 p_soun->i_qt_description > 20 + 28 )
2200 static const struct {
2204 vlc_fourcc_t i_codec;
2206 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2207 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2208 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2209 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2211 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2212 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2214 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2215 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2216 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2217 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2219 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2220 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2221 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2222 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2224 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2225 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2226 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2227 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2231 uint32_t i_bits = GetDWBE(&p_soun->p_qt_description[20 + 20]);
2232 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
2234 for( int i = 0; p_formats[i].i_codec; i++ )
2236 if( p_formats[i].i_bits == i_bits &&
2237 (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
2239 p_track->fmt.i_codec = p_formats[i].i_codec;
2240 p_track->fmt.audio.i_bitspersample = i_bits;
2241 p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
2242 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2244 p_soun->i_qt_version = 0;
2252 p_track->fmt.i_codec = p_sample->i_type;
2256 /* now see if esds is present and if so create a data packet
2257 with decoder_specific_info */
2258 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2259 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2260 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2261 ( p_esds->data.p_esds )&&
2264 /* First update information based on i_objectTypeIndication */
2265 switch( p_decconfig->i_objectTypeIndication )
2267 case( 0x20 ): /* MPEG4 VIDEO */
2268 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2270 case( 0x21 ): /* H.264 */
2271 p_track->fmt.i_codec = VLC_CODEC_H264;
2274 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2275 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2276 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2277 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2279 p_track->fmt.i_codec = VLC_CODEC_ALS;
2287 case( 0x65): /* MPEG2 video */
2288 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2290 /* Theses are MPEG2-AAC */
2291 case( 0x66): /* main profile */
2292 case( 0x67): /* Low complexity profile */
2293 case( 0x68): /* Scaleable Sampling rate profile */
2294 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2296 /* True MPEG 2 audio */
2298 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2300 case( 0x6a): /* MPEG1 video */
2301 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2303 case( 0x6b): /* MPEG1 audio */
2304 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2306 case( 0x6c ): /* jpeg */
2307 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2309 case( 0x6d ): /* png */
2310 p_track->fmt.i_codec = VLC_CODEC_PNG;
2312 case( 0x6e ): /* jpeg2000 */
2313 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2315 case( 0xa3 ): /* vc1 */
2316 p_track->fmt.i_codec = VLC_CODEC_VC1;
2319 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2322 p_track->fmt.i_codec = VLC_CODEC_A52;
2325 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2327 case( 0xa9 ): /* dts */
2328 case( 0xaa ): /* DTS-HD HRA */
2329 case( 0xab ): /* DTS-HD Master Audio */
2330 p_track->fmt.i_codec = VLC_CODEC_DTS;
2333 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2337 case( 0xe0 ): /* NeroDigital: dvd subs */
2338 if( p_track->fmt.i_cat == SPU_ES )
2340 p_track->fmt.i_codec = VLC_CODEC_SPU;
2341 if( p_track->i_width > 0 )
2342 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2343 if( p_track->i_height > 0 )
2344 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2347 case( 0xe1 ): /* QCelp for 3gp */
2348 if( p_track->fmt.i_cat == AUDIO_ES )
2350 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2356 /* Unknown entry, but don't touch i_fourcc */
2358 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2359 p_decconfig->i_objectTypeIndication,
2360 p_track->i_track_ID );
2363 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2364 if( p_track->fmt.i_extra > 0 )
2366 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2367 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2368 p_track->fmt.i_extra );
2370 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2371 p_track->fmt.i_extra >= 16 * 4 )
2373 for( int i = 0; i < 16; i++ )
2375 p_track->fmt.subs.spu.palette[1 + i] =
2376 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2378 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2383 switch( p_sample->i_type )
2385 /* qt decoder, send the complete chunk */
2386 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2387 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2388 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2389 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2390 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2391 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2392 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2393 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2394 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2395 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2396 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2397 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2398 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2400 /* qt decoder, send the complete chunk */
2401 case VLC_CODEC_SVQ1:
2402 case VLC_CODEC_SVQ3:
2403 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2404 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2405 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2406 p_track->fmt.i_extra =
2407 p_sample->data.p_sample_vide->i_qt_image_description;
2408 if( p_track->fmt.i_extra > 0 )
2410 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2411 memcpy( p_track->fmt.p_extra,
2412 p_sample->data.p_sample_vide->p_qt_image_description,
2413 p_track->fmt.i_extra);
2417 case VLC_CODEC_AMR_NB:
2418 p_track->fmt.audio.i_rate = 8000;
2420 case VLC_CODEC_AMR_WB:
2421 p_track->fmt.audio.i_rate = 16000;
2423 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2424 case VLC_CODEC_QDM2:
2425 case VLC_CODEC_ALAC:
2426 p_track->fmt.i_extra =
2427 p_sample->data.p_sample_soun->i_qt_description;
2428 if( p_track->fmt.i_extra > 0 )
2430 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2431 memcpy( p_track->fmt.p_extra,
2432 p_sample->data.p_sample_soun->p_qt_description,
2433 p_track->fmt.i_extra);
2435 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2437 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2438 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2442 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2444 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2447 p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2448 if( p_track->fmt.i_extra > 0 )
2450 p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2451 memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2452 p_track->fmt.i_extra );
2457 msg_Err( p_demux, "missing dvc1" );
2462 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2463 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2465 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2469 p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2470 if( p_track->fmt.i_extra > 0 )
2472 p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2473 memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2474 p_track->fmt.i_extra );
2479 msg_Err( p_demux, "missing avcC" );
2483 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2484 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2486 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2490 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2491 if( p_track->fmt.i_extra > 0 )
2493 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2494 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2495 p_track->fmt.i_extra );
2497 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2501 msg_Err( p_demux, "missing hvcC" );
2507 case VLC_CODEC_ADPCM_MS:
2508 case VLC_CODEC_ADPCM_IMA_WAV:
2509 case VLC_CODEC_QCELP:
2510 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2514 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2522 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2527 /* given a time it return sample/chunk
2528 * it also update elst field of the track
2530 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2531 int64_t i_start, uint32_t *pi_chunk,
2532 uint32_t *pi_sample )
2534 demux_sys_t *p_sys = p_demux->p_sys;
2535 MP4_Box_t *p_box_stss;
2537 unsigned int i_sample;
2538 unsigned int i_chunk;
2541 /* FIXME see if it's needed to check p_track->i_chunk_count */
2542 if( p_track->i_chunk_count == 0 )
2543 return( VLC_EGENERIC );
2545 /* handle elst (find the correct one) */
2546 MP4_TrackSetELST( p_demux, p_track, i_start );
2547 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2549 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2550 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2552 /* now calculate i_start for this elst */
2554 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2562 /* to track time scale */
2563 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2564 /* add elst offset */
2565 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2566 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2567 elst->i_media_time[p_track->i_elst] > 0 )
2569 i_start += elst->i_media_time[p_track->i_elst];
2572 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2573 "ms (track)", p_track->i_elst,
2574 i_mvt * 1000 / p_sys->i_timescale,
2575 i_start * 1000 / p_track->i_timescale );
2579 /* convert absolute time to in timescale unit */
2580 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2583 /* we start from sample 0/chunk 0, hope it won't take too much time */
2584 /* *** find good chunk *** */
2585 for( i_chunk = 0; ; i_chunk++ )
2587 if( i_chunk + 1 >= p_track->i_chunk_count )
2589 /* at the end and can't check if i_start in this chunk,
2590 it will be check while searching i_sample */
2591 i_chunk = p_track->i_chunk_count - 1;
2595 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2596 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2602 /* *** find sample in the chunk *** */
2603 i_sample = p_track->chunk[i_chunk].i_sample_first;
2604 i_dts = p_track->chunk[i_chunk].i_first_dts;
2605 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2608 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2609 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2612 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2613 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2615 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2620 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2624 i_sample += ( i_start - i_dts ) /
2625 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2630 if( i_sample >= p_track->i_sample_count )
2632 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2633 "(seeking too far) chunk=%d sample=%d",
2634 p_track->i_track_ID, i_chunk, i_sample );
2635 return( VLC_EGENERIC );
2639 /* *** Try to find nearest sync points *** */
2640 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2642 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2643 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2644 p_track->i_track_ID );
2645 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2647 if( i_index >= p_stss->i_entry_count - 1 ||
2648 i_sample < p_stss->i_sample_number[i_index+1] )
2650 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2651 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
2652 i_sample, i_sync_sample );
2654 if( i_sync_sample <= i_sample )
2656 while( i_chunk > 0 &&
2657 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2662 while( i_chunk < p_track->i_chunk_count - 1 &&
2663 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2664 p_track->chunk[i_chunk].i_sample_count )
2667 i_sample = i_sync_sample;
2674 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2675 "Sample Box (stss)", p_track->i_track_ID );
2678 *pi_chunk = i_chunk;
2679 *pi_sample = i_sample;
2684 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2685 unsigned int i_chunk, unsigned int i_sample )
2687 bool b_reselect = false;
2689 /* now see if actual es is ok */
2690 if( p_track->i_chunk >= p_track->i_chunk_count ||
2691 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2692 p_track->chunk[i_chunk].i_sample_description_index )
2694 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2695 p_track->i_track_ID );
2697 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2698 p_track->p_es, &b_reselect );
2700 es_out_Del( p_demux->out, p_track->p_es );
2702 p_track->p_es = NULL;
2704 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2706 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2707 p_track->i_track_ID );
2709 p_track->b_ok = false;
2710 p_track->b_selected = false;
2711 return VLC_EGENERIC;
2715 /* select again the new decoder */
2718 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2721 p_track->i_chunk = i_chunk;
2722 p_track->i_sample = i_sample;
2724 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2727 /****************************************************************************
2729 ****************************************************************************
2730 * Parse track information and create all needed data to run a track
2731 * If it succeed b_ok is set to 1 else to 0
2732 ****************************************************************************/
2733 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2734 MP4_Box_t *p_box_trak,
2735 bool b_force_enable )
2737 demux_sys_t *p_sys = p_demux->p_sys;
2739 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2740 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2750 char language[4] = { '\0' };
2752 /* hint track unsupported */
2754 /* set default value (-> track unusable) */
2755 p_track->b_ok = false;
2756 p_track->b_enable = false;
2757 p_track->b_selected = false;
2758 p_track->b_chapter = false;
2759 p_track->b_mac_encoding = false;
2761 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2768 /* do we launch this track by default ? */
2770 ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2771 if( !p_track->b_enable )
2772 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2774 p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2776 p_track->i_width = p_tkhd->data.p_tkhd->i_width / BLOCK16x16;
2777 p_track->i_height = p_tkhd->data.p_tkhd->i_height / BLOCK16x16;
2778 p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2782 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2785 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2786 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2788 if( ( !p_mdhd )||( !p_hdlr ) )
2793 p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2794 if( p_track->i_timescale == 0 )
2797 if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2799 strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2800 p_track->b_mac_encoding = true;
2802 else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2803 p_track->b_mac_encoding = true;
2806 for( unsigned i = 0; i < 3; i++ )
2807 language[i] = p_mdhd->data.p_mdhd->i_language[i];
2811 switch( p_hdlr->data.p_hdlr->i_handler_type )
2814 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2818 p_track->fmt.i_cat = AUDIO_ES;
2822 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2826 p_track->fmt.i_cat = VIDEO_ES;
2833 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2834 p_track->fmt.i_cat = SPU_ES;
2841 p_track->i_elst = 0;
2842 p_track->i_elst_time = 0;
2843 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2845 MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2848 msg_Warn( p_demux, "elst box found" );
2849 for( i = 0; i < elst->i_entry_count; i++ )
2851 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2852 "ms) rate=%d.%d", i,
2853 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2854 elst->i_media_time[i] >= 0 ?
2855 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2857 elst->i_media_rate_integer[i],
2858 elst->i_media_rate_fraction[i] );
2865 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2867 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2868 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2874 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2876 p_track->fmt.psz_language = strdup( language );
2879 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2882 MP4_Box_t *p_box_iter;
2883 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2884 p_box_iter = p_box_iter->p_next )
2886 switch( p_box_iter->i_type )
2889 p_track->fmt.psz_description =
2890 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2893 p_track->fmt.psz_description =
2894 strdup( p_box_iter->data.p_name->psz_text );
2900 /* Create chunk index table and sample index table */
2901 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2902 TrackCreateSamplesIndex( p_demux, p_track ) )
2904 return; /* cannot create chunks index */
2907 p_track->i_chunk = 0;
2908 p_track->i_sample = 0;
2910 /* Mark chapter only track */
2911 if( p_sys->p_tref_chap )
2913 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2916 for( i = 0; i < p_chap->i_entry_count; i++ )
2918 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2919 p_track->fmt.i_cat == UNKNOWN_ES )
2921 p_track->b_chapter = true;
2922 p_track->b_enable = false;
2929 if( b_force_enable &&
2930 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2932 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2933 p_track->i_track_ID );
2934 p_track->b_enable = true;
2935 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2938 p_track->p_es = NULL;
2939 if( TrackCreateES( p_demux,
2940 p_track, p_track->i_chunk,
2941 p_track->b_chapter ? NULL : &p_track->p_es ) )
2943 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2944 p_track->i_track_ID );
2947 p_track->b_ok = true;
2951 for( i = 0; i < p_track->i_chunk_count; i++ )
2953 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2954 i, p_track->chunk[i].i_sample_count,
2955 p_track->chunk[i].i_first_dts );
2962 static void FreeAndResetChunk( mp4_chunk_t *ck )
2964 free( ck->p_sample_count_dts );
2965 free( ck->p_sample_delta_dts );
2966 free( ck->p_sample_count_pts );
2967 free( ck->p_sample_offset_pts );
2968 free( ck->p_sample_size );
2969 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2970 free( ck->p_sample_data[i] );
2971 free( ck->p_sample_data );
2972 memset( ck, 0, sizeof( mp4_chunk_t ) );
2975 /****************************************************************************
2977 ****************************************************************************
2978 * Destroy a track created by MP4_TrackCreate.
2979 ****************************************************************************/
2980 static void MP4_TrackDestroy( mp4_track_t *p_track )
2982 unsigned int i_chunk;
2984 p_track->b_ok = false;
2985 p_track->b_enable = false;
2986 p_track->b_selected = false;
2988 es_format_Clean( &p_track->fmt );
2990 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2992 if( p_track->chunk )
2994 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2995 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2997 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2998 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3001 FREENULL( p_track->chunk );
3002 if( p_track->cchunk ) {
3003 FreeAndResetChunk( p_track->cchunk );
3004 FREENULL( p_track->cchunk );
3007 if( !p_track->i_sample_size )
3009 FREENULL( p_track->p_sample_size );
3013 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3016 if( !p_track->b_ok || p_track->b_chapter )
3018 return VLC_EGENERIC;
3021 if( p_track->b_selected )
3023 msg_Warn( p_demux, "track[Id 0x%x] already selected",
3024 p_track->i_track_ID );
3028 return MP4_TrackSeek( p_demux, p_track, i_start );
3031 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3033 if( !p_track->b_ok || p_track->b_chapter )
3038 if( !p_track->b_selected )
3040 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3041 p_track->i_track_ID );
3046 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3047 p_track->p_es, false );
3050 p_track->b_selected = false;
3053 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3059 if( !p_track->b_ok || p_track->b_chapter )
3060 return VLC_EGENERIC;
3062 p_track->b_selected = false;
3064 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3065 &i_chunk, &i_sample ) )
3067 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3068 p_track->i_track_ID );
3069 return VLC_EGENERIC;
3072 p_track->b_selected = true;
3074 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3075 p_track->b_selected = true;
3077 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3082 * 3 types: for audio
3085 #define QT_V0_MAX_SAMPLES 1024
3086 static uint32_t MP4_TrackSampleSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3089 MP4_Box_data_sample_soun_t *p_soun;
3091 if( p_track->i_sample_size == 0 )
3093 /* most simple case */
3094 return p_track->p_sample_size[p_track->i_sample];
3096 if( p_track->fmt.i_cat != AUDIO_ES )
3098 return p_track->i_sample_size;
3101 p_soun = p_track->p_sample->data.p_sample_soun;
3103 if( p_soun->i_qt_version == 1 )
3105 uint32_t i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
3106 if( p_track->fmt.audio.i_blockalign > 1 )
3107 i_samples = p_soun->i_sample_per_packet;
3108 i_size = i_samples / p_soun->i_sample_per_packet;
3109 if ( UINT32_MAX / i_size >= p_soun->i_bytes_per_frame )
3110 i_size *= p_soun->i_bytes_per_frame;
3112 i_size = UINT32_MAX;
3114 else if( p_track->i_sample_size > 256 )
3116 /* We do that so we don't read too much data
3117 * (in this case we are likely dealing with compressed data) */
3118 i_size = p_track->i_sample_size;
3122 mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3123 int64_t i_length = CLOCK_FREQ / 10;
3124 uint32_t i_samples = 0;
3125 uint32_t i_maxsamples = 0;
3126 for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
3128 i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
3129 if ( i_length < 0 ) break;
3133 i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
3134 i_samples = __MIN( i_maxsamples, i_samples );
3135 if ( i_samples == 0 ) i_samples = 1;
3136 i_size = i_samples * p_track->i_sample_size;
3137 *pi_nb_samples = i_samples;
3140 //fprintf( stderr, "size=%d\n", i_size );
3144 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3146 unsigned int i_sample;
3149 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3151 if( p_track->i_sample_size )
3153 MP4_Box_data_sample_soun_t *p_soun =
3154 p_track->p_sample->data.p_sample_soun;
3156 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3158 i_pos += ( p_track->i_sample -
3159 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3160 p_track->i_sample_size;
3164 /* we read chunk by chunk unless a blockalign is requested */
3165 if( p_track->fmt.audio.i_blockalign > 1 )
3166 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3167 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3172 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3173 i_sample < p_track->i_sample; i_sample++ )
3175 i_pos += p_track->p_sample_size[i_sample];
3182 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3184 if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
3186 MP4_Box_data_sample_soun_t *p_soun;
3188 p_soun = p_track->p_sample->data.p_sample_soun;
3190 if( p_soun->i_qt_version == 1 )
3192 /* we read chunk by chunk unless a blockalign is requested */
3193 if( p_track->fmt.audio.i_blockalign > 1 )
3194 p_track->i_sample += p_soun->i_sample_per_packet;
3196 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
3198 else if( p_track->i_sample_size > 256 )
3200 /* We do that so we don't read too much data
3201 * (in this case we are likely dealing with compressed data) */
3202 p_track->i_sample += 1;
3207 p_track->i_sample += i_samples;
3208 if( p_track->i_sample >
3209 p_track->chunk[p_track->i_chunk].i_sample_first +
3210 p_track->chunk[p_track->i_chunk].i_sample_count )
3213 p_track->chunk[p_track->i_chunk].i_sample_first +
3214 p_track->chunk[p_track->i_chunk].i_sample_count;
3220 p_track->i_sample++;
3223 if( p_track->i_sample >= p_track->i_sample_count )
3224 return VLC_EGENERIC;
3226 /* Have we changed chunk ? */
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 )
3231 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3232 p_track->i_sample ) )
3234 msg_Warn( p_demux, "track[0x%x] will be disabled "
3235 "(cannot restart decoder)", p_track->i_track_ID );
3236 MP4_TrackUnselect( p_demux, p_track );
3237 return VLC_EGENERIC;
3241 /* Have we changed elst */
3242 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
3244 demux_sys_t *p_sys = p_demux->p_sys;
3245 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
3246 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3247 p_sys->i_timescale / CLOCK_FREQ;
3249 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3250 i_mvt >= p_track->i_elst_time +
3251 elst->i_segment_duration[p_track->i_elst] )
3253 MP4_TrackSetELST( p_demux, p_track,
3254 MP4_TrackGetDTS( p_demux, p_track ) );
3261 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3264 demux_sys_t *p_sys = p_demux->p_sys;
3265 int i_elst_last = tk->i_elst;
3267 /* handle elst (find the correct one) */
3269 tk->i_elst_time = 0;
3270 if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
3272 MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
3273 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3275 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3277 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3279 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3283 tk->i_elst_time += i_dur;
3286 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3288 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3289 tk->i_elst = elst->i_entry_count - 1;
3290 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3293 if( elst->i_media_time[tk->i_elst] < 0 )
3296 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3299 if( i_elst_last != tk->i_elst )
3301 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3306 static const char *MP4_ConvertMacCode( uint16_t i_code )
3308 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3309 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3310 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3311 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3312 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3313 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3314 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3315 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3316 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3317 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3318 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3319 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3320 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3321 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3322 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3323 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3324 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3325 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3326 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3327 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3329 { "cy", 128 }, { "eu", 129 },
3330 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3331 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3332 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3333 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3338 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3340 if( p_cvt[i].i_code == i_code )
3341 return p_cvt[i].psz_iso639_1;
3346 /******************************************************************************
3347 * Here are the functions used for fragmented MP4
3348 *****************************************************************************/
3351 * It computes the sample rate for a video track using current video chunk
3353 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3354 const mp4_track_t *p_track )
3356 if( p_track->cchunk->i_last_dts == 0 )
3363 const mp4_chunk_t *p_chunk = p_track->cchunk;
3365 uint32_t i_sample = p_chunk->i_sample_count;
3366 uint64_t i_first_dts = p_chunk->i_first_dts;
3367 uint64_t i_last_dts = p_chunk->i_last_dts;
3369 if( i_sample > 1 && i_first_dts < i_last_dts )
3370 vlc_ureduce( pi_num, pi_den,
3371 ( i_sample - 1) * p_track->i_timescale,
3372 i_last_dts - i_first_dts,
3377 * Build raw avcC box (without the 8 bytes header)
3378 * \return The size of the box.
3380 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3381 const unsigned cpd_len )
3384 unsigned sps_len = 0, pps_len = 0;
3385 const uint32_t mark = 0x00000001;
3387 assert( CodecPrivateData[0] == 0 );
3388 assert( CodecPrivateData[1] == 0 );
3389 assert( CodecPrivateData[2] == 0 );
3390 assert( CodecPrivateData[3] == 1 );
3392 uint32_t length = cpd_len + 3;
3393 avcC = calloc( length, 1 );
3394 if( unlikely( avcC == NULL ) )
3397 uint8_t *sps = avcC + 8;
3399 uint32_t candidate = ~mark;
3400 CodecPrivateData += 4;
3401 for( unsigned i = 0; i < cpd_len - 4; i++ )
3403 sps[i] = CodecPrivateData[i];
3404 candidate = (candidate << 8) | CodecPrivateData[i];
3405 if( candidate == mark )
3416 uint8_t *pps = sps + sps_len + 3;
3417 pps_len = cpd_len - sps_len - 4 * 2;
3418 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3421 uint8_t AVCProfileIndication = 0x64;
3422 uint8_t profile_compatibility = 0x40;
3423 uint8_t AVCLevelIndication = 0x1f;
3424 uint8_t lengthSizeMinusOne = 0x03;
3427 avcC[1] = AVCProfileIndication;
3428 avcC[2] = profile_compatibility;
3429 avcC[3] = AVCLevelIndication;
3430 avcC[4] = 0xfc + lengthSizeMinusOne;
3432 avcC[6] = (sps_len & 0xff00)>>8;
3433 avcC[7] = sps_len & 0xff;
3435 avcC[8+sps_len] = 1;
3436 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3437 avcC[10+sps_len] = pps_len & 0xff;
3444 * Build a mp4_track_t from a StraBox
3447 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3449 fmt->i_extra = p_data->cpd_len;
3450 fmt->p_extra = malloc( p_data->cpd_len );
3451 if( unlikely( !fmt->p_extra ) )
3453 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3457 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3459 demux_sys_t *p_sys = p_demux->p_sys;
3461 MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3463 return VLC_EGENERIC;
3465 p_track->b_ok = true;
3466 p_track->b_selected = false;
3467 p_track->i_sample_count = UINT32_MAX;
3469 p_track->i_timescale = p_sys->i_timescale;
3470 p_track->i_width = p_data->MaxWidth;
3471 p_track->i_height = p_data->MaxHeight;
3472 p_track->i_track_ID = p_data->i_track_ID;
3474 es_format_t *fmt = &p_track->fmt;
3476 return VLC_EGENERIC;
3478 es_format_Init( fmt, p_data->i_es_cat, 0 );
3480 /* Set language FIXME */
3481 fmt->psz_language = strdup( "en" );
3483 fmt->i_original_fourcc = p_data->FourCC;
3484 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3486 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3487 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3488 * for MS weird use of FourCC*/
3489 switch( fmt->i_cat )
3492 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3493 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3494 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3496 fmt->i_extra = build_raw_avcC( p_extra,
3497 p_data->CodecPrivateData, p_data->cpd_len );
3501 ret = MP4_SetCodecExtraData( fmt, p_data );
3502 if( ret != VLC_SUCCESS )
3506 fmt->video.i_width = p_data->MaxWidth;
3507 fmt->video.i_height = p_data->MaxHeight;
3508 fmt->video.i_bits_per_pixel = 0x18;
3509 fmt->video.i_visible_width = p_data->MaxWidth;
3510 fmt->video.i_visible_height = p_data->MaxHeight;
3513 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3514 &fmt->video.i_frame_rate_base, p_track );
3516 if( fmt->video.i_frame_rate_base != 0 )
3518 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3519 (float)fmt->video.i_frame_rate_base;
3522 p_demux->p_sys->f_fps = 24;
3527 fmt->audio.i_channels = p_data->Channels;
3528 fmt->audio.i_rate = p_data->SamplingRate;
3529 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3530 fmt->audio.i_blockalign = p_data->nBlockAlign;
3532 fmt->i_bitrate = p_data->Bitrate;
3534 ret = MP4_SetCodecExtraData( fmt, p_data );
3535 if( ret != VLC_SUCCESS )
3548 * Return the track identified by tid
3550 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3552 demux_sys_t *p_sys = p_demux->p_sys;
3554 mp4_track_t *ret = NULL;
3555 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3557 ret = &p_sys->track[i];
3558 if( ret->i_track_ID == tid )
3561 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3565 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3567 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3568 mp4_chunk_t *ck = tk->cchunk;
3569 while( ck->i_sample < ck->i_sample_count )
3574 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3577 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3578 assert( sample_size > 0 );
3579 p_block = block_Alloc( sample_size );
3580 if( unlikely( !p_block ) )
3583 uint8_t *src = ck->p_sample_data[ck->i_sample];
3584 memcpy( p_block->p_buffer, src, sample_size );
3588 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3590 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3592 p_block->i_pts = p_block->i_dts + i_delta;
3593 else if( tk->fmt.i_cat != VIDEO_ES )
3594 p_block->i_pts = p_block->i_dts;
3596 p_block->i_pts = VLC_TS_INVALID;
3598 es_out_Send( p_demux->out, tk->p_es, p_block );
3606 * \Note If we call that function too soon,
3607 * before the track has been selected by MP4_TrackSelect
3608 * (during the first execution of Demux), then the track gets disabled
3610 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3612 demux_sys_t *p_sys = p_demux->p_sys;
3614 uint32_t i_sample = 0;
3615 bool b_smooth = false;
3616 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3618 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3623 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3624 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3625 return VLC_EGENERIC;
3629 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3631 return VLC_EGENERIC;
3634 i_sample = p_track->i_sample;
3635 es_out_Del( p_demux->out, p_track->p_es );
3636 es_format_Clean( &p_track->fmt );
3639 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3641 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3643 p_track->i_sample = i_sample;
3645 /* Temporary hack until we support track selection */
3646 p_track->b_selected = true;
3647 p_track->b_ok = true;
3648 p_track->b_enable = true;
3650 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3651 p_track->b_codec_need_restart = false;
3657 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3658 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3659 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3660 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3662 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3664 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3665 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3668 msg_Warn( p_demux, "no moof box found!" );
3669 return VLC_EGENERIC;
3672 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3675 msg_Warn( p_demux, "no traf box found!" );
3676 return VLC_EGENERIC;
3679 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3682 msg_Warn( p_demux, "no tfhd box found!" );
3683 return VLC_EGENERIC;
3686 uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3687 *i_tk_id = i_track_ID;
3688 assert( i_track_ID > 0 );
3689 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3691 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
3693 return VLC_EGENERIC;
3695 mp4_chunk_t *ret = p_track->cchunk;
3697 if( p_tfhd->data.p_tfhd->b_empty )
3698 msg_Warn( p_demux, "No samples in this chunk!" );
3700 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3701 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3702 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3703 * and so on. Finally, suppose that we get the chunks the other way around,
3704 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3705 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3706 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3707 * flush it, i.e. send to the decoder the samples not yet sent.
3708 * Note that all the samples to be flushed should worth less than 100 ms,
3709 * (though I did not do the formal proof) and thus this flushing mechanism
3710 * should not cause A/V sync issues, or delays or whatever.
3712 if( ret->i_sample < ret->i_sample_count )
3713 FlushChunk( p_demux, p_track );
3715 if( ret->i_sample_count )
3716 FreeAndResetChunk( ret );
3718 uint32_t default_duration = 0;
3719 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3720 default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3722 uint32_t default_size = 0;
3723 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3724 default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3726 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3729 msg_Warn( p_demux, "no trun box found!" );
3730 return VLC_EGENERIC;
3732 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3734 ret->i_sample_count = p_trun_data->i_sample_count;
3735 assert( ret->i_sample_count > 0 );
3736 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3737 ret->i_sample_first = p_track->i_sample_first;
3738 p_track->i_sample_first += ret->i_sample_count;
3740 ret->i_first_dts = p_track->i_first_dts;
3742 /* XXX I already saw DASH content with no default_duration and no
3743 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3744 * This chunk of code might be buggy with segments having
3745 * more than one subsegment. */
3746 if( !default_duration )
3748 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
3751 while( p_trex && p_trex->data.p_trex->i_track_ID != i_track_ID )
3752 p_trex = p_trex->p_next;
3754 default_duration = p_trex->data.p_trex->i_default_sample_duration;
3758 MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3759 assert( p_sidx_data->i_reference_count == 1 );
3761 if( p_sidx_data->i_timescale == 0 )
3762 return VLC_EGENERIC;
3764 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3765 p_sidx_data->i_timescale;
3766 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3771 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3773 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3774 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3776 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3779 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3780 if( !ret->p_sample_count_pts )
3783 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3785 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3786 if( !ret->p_sample_offset_pts )
3790 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3791 if( !ret->p_sample_size )
3794 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3795 if( !ret->p_sample_data )
3798 uint32_t dur = 0, i_mdatlen = 0, len;
3799 uint32_t chunk_duration = 0, chunk_size = 0;
3801 /* Skip header of mdat */
3803 int i_read = stream_Read( p_demux->s, &mdat, 8 );
3804 i_mdatlen = GetDWBE( mdat );
3805 if ( i_read < 8 || i_mdatlen < 8 ||
3806 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
3807 return VLC_EGENERIC;
3809 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3811 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3812 dur = p_trun_data->p_samples[i].i_duration;
3814 dur = default_duration;
3815 ret->p_sample_delta_dts[i] = dur;
3816 chunk_duration += dur;
3818 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3820 if( ret->p_sample_offset_pts )
3822 ret->p_sample_offset_pts[i] =
3823 p_trun_data->p_samples[i].i_composition_time_offset;
3826 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3827 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3829 len = ret->p_sample_size[i] = default_size;
3831 if ( chunk_size + len > ( i_mdatlen - 8 ) )
3832 return VLC_EGENERIC;
3834 ret->p_sample_data[i] = malloc( len );
3835 if( ret->p_sample_data[i] == NULL )
3837 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
3839 return VLC_EGENERIC;
3842 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3843 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3845 if( p_track->b_codec_need_restart &&
3846 p_track->fmt.i_cat == VIDEO_ES )
3847 ReInitDecoder( p_demux, p_track );
3849 /* Skip if we didn't reach the end of mdat box */
3850 if ( chunk_size < (i_mdatlen - 8) )
3851 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
3853 p_track->b_has_non_empty_cchunk = true;
3858 * Get the next chunk of the track identified by i_tk_id.
3859 * \Note We don't want to seek all the time, so if the first chunk given by the
3860 * input method doesn't belong to the right track, we don't throw it away,
3861 * and so, in general, this function fetch more than one chunk.
3862 * Not to mention that a new init segment might be put everywhere
3863 * between two chunks by the input method.
3865 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3867 demux_sys_t *p_sys = p_demux->p_sys;
3868 mp4_track_t *p_track;
3870 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3872 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3874 return VLC_EGENERIC;
3876 if( !p_chunk->p_first )
3877 goto MP4_frg_GetChunks_Error;
3878 uint32_t i_type = p_chunk->p_first->i_type;
3880 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3882 MP4_BoxFree( p_demux->s, p_sys->p_root );
3883 p_sys->p_root = p_chunk;
3885 if( i_type == ATOM_ftyp ) /* DASH */
3887 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3890 msg_Warn( p_demux, "No tkhd found!" );
3891 goto MP4_frg_GetChunks_Error;
3893 tid = p_tkhd->data.p_tkhd->i_track_ID;
3895 else /* Smooth Streaming */
3897 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3898 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3899 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3901 msg_Warn( p_demux, "No StraBox found!" );
3902 goto MP4_frg_GetChunks_Error;
3904 tid = p_stra->data.p_stra->i_track_ID;
3907 p_track = MP4_frg_GetTrackByID( p_demux, tid );
3909 goto MP4_frg_GetChunks_Error;
3910 p_track->b_codec_need_restart = true;
3912 return MP4_frg_GetChunks( p_demux, i_tk_id );
3915 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3916 goto MP4_frg_GetChunks_Error;
3918 MP4_BoxFree( p_demux->s, p_chunk );
3920 if( tid == i_tk_id )
3925 MP4_frg_GetChunks_Error:
3926 MP4_BoxFree( p_demux->s, p_chunk );
3927 return VLC_EGENERIC;
3933 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3935 if( !p_track->b_ok || p_track->b_chapter )
3937 return VLC_EGENERIC;
3940 if( p_track->b_selected )
3942 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3946 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3947 p_track->b_selected = true;
3952 * DemuxFrg: read packet and send them to decoders
3953 * \return 1 on success, 0 on error.
3954 * TODO check for newly selected track
3956 int DemuxFrg( demux_t *p_demux )
3958 demux_sys_t *p_sys = p_demux->p_sys;
3960 unsigned i_track_selected;
3962 /* check for newly selected/unselected track */
3963 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3965 mp4_track_t *tk = &p_sys->track[i_track];
3968 if( !tk->b_ok || tk->b_chapter )
3971 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3972 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3974 if( tk->b_selected && !b )
3976 MP4_TrackUnselect( p_demux, tk );
3978 else if( !tk->b_selected && b)
3980 MP4_frg_TrackSelect( p_demux, tk );
3983 if( tk->b_selected )
3987 if( i_track_selected <= 0 )
3989 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3990 if( p_sys->i_timescale > 0 )
3992 int64_t i_length = CLOCK_FREQ *
3993 (mtime_t)p_sys->i_duration /
3994 (mtime_t)p_sys->i_timescale;
3995 if( MP4_GetMoviePTS( p_sys ) >= i_length )
4000 msg_Warn( p_demux, "no track selected, exiting..." );
4004 /* first wait for the good time to read a packet */
4005 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4007 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4009 /* we will read 100ms for each stream so ...*/
4010 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4012 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4014 mp4_track_t *tk = &p_sys->track[i_track];
4016 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4018 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4022 if( !tk->b_has_non_empty_cchunk )
4024 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4026 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4031 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4036 mp4_chunk_t *ck = tk->cchunk;
4037 if( ck->i_sample >= ck->i_sample_count )
4039 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4040 ck->i_sample, ck->i_sample_count );
4044 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4045 p_block = block_Alloc( sample_size );
4046 uint8_t *src = ck->p_sample_data[ck->i_sample];
4047 memcpy( p_block->p_buffer, src, sample_size );
4050 if( ck->i_sample == ck->i_sample_count )
4051 tk->b_has_non_empty_cchunk = false;
4054 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4056 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4058 p_block->i_pts = p_block->i_dts + i_delta;
4059 else if( tk->fmt.i_cat != VIDEO_ES )
4060 p_block->i_pts = p_block->i_dts;
4062 p_block->i_pts = VLC_TS_INVALID;
4064 es_out_Send( p_demux->out, tk->p_es, p_block );
4068 if( !tk->b_has_non_empty_cchunk )