1 /*****************************************************************************
2 * mp4.c : MP4 file input module for vlc
3 *****************************************************************************
4 * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN
6 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation; either version 2.1 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21 *****************************************************************************/
23 /*****************************************************************************
25 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35 #include <vlc_charset.h> /* EnsureUTF8 */
36 #include <vlc_meta.h> /* vlc_meta_t, vlc_meta_ */
37 #include <vlc_input.h>
41 #include "id3genres.h" /* for ATOM_gnre */
43 /*****************************************************************************
45 *****************************************************************************/
46 static int Open ( vlc_object_t * );
47 static void Close( vlc_object_t * );
50 set_category( CAT_INPUT )
51 set_subcategory( SUBCAT_INPUT_DEMUX )
52 set_description( N_("MP4 stream demuxer") )
53 set_shortname( N_("MP4") )
54 set_capability( "demux", 240 )
55 set_callbacks( Open, Close )
58 /*****************************************************************************
60 *****************************************************************************/
61 static int Demux ( demux_t * );
62 static int DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
63 static int DemuxFrg( demux_t * );
64 static int Seek ( demux_t *, mtime_t );
65 static int Control ( demux_t *, int, va_list );
69 MP4_Box_t *p_root; /* container for the whole file */
73 uint64_t i_time; /* time position of the presentation
74 * in movie timescale */
75 uint64_t i_timescale; /* movie time scale */
76 uint64_t i_duration; /* movie duration */
77 unsigned int i_tracks; /* number of tracks */
78 mp4_track_t *track; /* array of track */
79 float f_fps; /* number of frame per seconds */
81 bool b_fragmented; /* fMP4 */
84 MP4_Box_t *p_tref_chap;
87 input_title_t *p_title;
90 /*****************************************************************************
91 * Declaration of local function
92 *****************************************************************************/
93 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
94 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
95 static void MP4_TrackDestroy( mp4_track_t * );
97 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
98 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
100 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
102 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
103 static int MP4_TrackSampleSize( mp4_track_t *, int * );
104 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, int );
105 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
107 static void MP4_UpdateSeekpoint( demux_t * );
108 static const char *MP4_ConvertMacCode( uint16_t );
110 /* Return time in microsecond of a track */
111 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
113 demux_sys_t *p_sys = p_demux->p_sys;
115 if( p_sys->b_fragmented )
116 chunk = *p_track->cchunk;
118 chunk = p_track->chunk[p_track->i_chunk];
120 unsigned int i_index = 0;
121 unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
122 int64_t i_dts = chunk.i_first_dts;
124 while( i_sample > 0 )
126 if( i_sample > chunk.p_sample_count_dts[i_index] )
128 i_dts += chunk.p_sample_count_dts[i_index] *
129 chunk.p_sample_delta_dts[i_index];
130 i_sample -= chunk.p_sample_count_dts[i_index];
135 i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
140 /* now handle elst */
141 if( p_track->p_elst )
143 demux_sys_t *p_sys = p_demux->p_sys;
144 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
146 /* convert to offset */
147 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
148 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
149 elst->i_media_time[p_track->i_elst] > 0 )
151 i_dts -= elst->i_media_time[p_track->i_elst];
154 /* add i_elst_time */
155 i_dts += p_track->i_elst_time * p_track->i_timescale /
158 if( i_dts < 0 ) i_dts = 0;
161 return CLOCK_FREQ * i_dts / p_track->i_timescale;
164 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
166 demux_sys_t *p_sys = p_demux->p_sys;
168 if( p_sys->b_fragmented )
169 ck = p_track->cchunk;
171 ck = &p_track->chunk[p_track->i_chunk];
173 unsigned int i_index = 0;
174 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
176 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
179 for( i_index = 0;; i_index++ )
181 if( i_sample < ck->p_sample_count_pts[i_index] )
182 return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
183 (int64_t)p_track->i_timescale;
185 i_sample -= ck->p_sample_count_pts[i_index];
189 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
191 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
194 static void LoadChapter( demux_t *p_demux );
196 static int LoadInitFrag( demux_t *p_demux, const bool b_smooth )
198 demux_sys_t *p_sys = p_demux->p_sys;
200 if( b_smooth ) /* Smooth Streaming */
202 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
204 goto LoadInitFragError;
208 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
209 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
210 goto LoadInitFragError;
211 /* Get number of tracks */
213 for( int i = 0; i < 3; i++ )
215 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
216 if( p_stra && p_stra->data.p_stra->i_track_ID )
218 /* Get timescale and duration of the video track; */
219 if( p_sys->i_timescale == 0 )
221 p_sys->i_timescale = p_stra->data.p_stra->i_timescale;
222 p_sys->i_duration = p_stra->data.p_stra->i_duration;
223 if( p_sys->i_timescale == 0 )
225 msg_Err( p_demux, "bad timescale" );
226 goto LoadInitFragError;
234 /* Load all boxes ( except raw data ) */
235 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
237 goto LoadInitFragError;
243 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
247 static int InitTracks( demux_t *p_demux )
249 demux_sys_t *p_sys = p_demux->p_sys;
251 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
252 if( p_sys->track == NULL )
255 if( p_sys->b_fragmented )
257 mp4_track_t *p_track;
258 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
260 p_track = &p_sys->track[i];
261 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
262 if( unlikely( !p_track->cchunk ) )
264 free( p_sys->track );
272 static void CreateTracksFromSmooBox( demux_t *p_demux )
274 demux_sys_t *p_sys = p_demux->p_sys;
276 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
277 mp4_track_t *p_track;
279 for( int i = 0; i < 3; i++ )
281 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
282 if( !p_stra || p_stra->data.p_stra->i_track_ID == 0 )
286 p_track = &p_sys->track[j]; j++;
287 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
288 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
293 /*****************************************************************************
294 * Open: check file and initializes MP4 structures
295 *****************************************************************************/
296 static int Open( vlc_object_t * p_this )
298 demux_t *p_demux = (demux_t *)p_this;
301 const uint8_t *p_peek;
312 /* A little test to see if it could be a mp4 */
313 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
315 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
326 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
329 /* We don't yet support f4v, but avformat does. */
330 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
338 stream_Control( p_demux->s, STREAM_CAN_SEEK, &b_seekable );
341 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
345 /*Set exported functions */
346 p_demux->pf_demux = Demux;
347 p_demux->pf_control = Control;
349 /* create our structure that will contains all data */
350 p_demux->p_sys = p_sys = calloc( 1, sizeof( demux_sys_t ) );
352 /* Is it Smooth Streaming? */
353 bool b_smooth = false;
354 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
355 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
358 p_sys->b_fragmented = true;
361 if( LoadInitFrag( p_demux, b_smooth ) != VLC_SUCCESS )
364 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
366 p_sys->b_fragmented = true;
368 if( p_sys->b_fragmented )
370 p_demux->pf_demux = DemuxFrg;
373 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
376 if( InitTracks( p_demux ) != VLC_SUCCESS )
378 CreateTracksFromSmooBox( p_demux );
381 else if( p_sys->b_fragmented && b_seekable )
383 /* We are not yet able to demux a fragmented MP4 file, using the 'mfra'
384 * box. So if STREAM_CAN_FASTSEEK is true, we're assuming we've got such
385 * a file, and we let avformat do the job. */
386 msg_Warn( p_demux, "MP4 plugin discarded "\
387 "(fast-seekable and fragmented, let avformat demux it)" );
388 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
391 else if( !p_sys->b_fragmented && !b_seekable )
393 msg_Warn( p_demux, "MP4 plugin discarded (not fast-seekable)" );
394 stream_Seek( p_demux->s, 0 ); /* rewind, for other demux */
398 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
400 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
402 switch( p_ftyp->data.p_ftyp->i_major_brand )
406 "ISO Media file (isom) version %d.",
407 p_ftyp->data.p_ftyp->i_minor_version );
410 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
411 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
412 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
413 msg_Dbg( p_demux, "3GPP Media file Release: %c",
414 #ifdef WORDS_BIGENDIAN
415 p_ftyp->data.p_ftyp->i_major_brand
417 p_ftyp->data.p_ftyp->i_major_brand >> 24
421 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
422 msg_Dbg( p_demux, "Apple QuickTime file" );
424 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
425 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
429 "unrecognized major file specification (%4.4s).",
430 (char*)&p_ftyp->data.p_ftyp->i_major_brand );
436 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
439 /* the file need to have one moov box */
440 if( MP4_BoxCount( p_sys->p_root, "/moov" ) <= 0 )
442 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
446 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
449 /* we have a free box as a moov, rename it */
450 p_foov->i_type = ATOM_moov;
453 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
455 int i_count = MP4_BoxCount( p_rmra, "rmda" );
458 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
460 input_thread_t *p_input = demux_GetParentInput( p_demux );
461 input_item_t *p_current = input_GetItem( p_input );
463 input_item_node_t *p_subitems = input_item_node_Create( p_current );
465 for( i = 0; i < i_count; i++ )
467 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
471 if( !p_rdrf || !( psz_ref = strdup( p_rdrf->data.p_rdrf->psz_ref ) ) )
475 i_ref_type = p_rdrf->data.p_rdrf->i_ref_type;
477 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
478 psz_ref, (char*)&i_ref_type );
480 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
482 if( strstr( psz_ref, "qt5gateQT" ) )
484 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
487 if( !strncmp( psz_ref, "http://", 7 ) ||
488 !strncmp( psz_ref, "rtsp://", 7 ) )
495 char *psz_path = strdup( p_demux->psz_location );
496 char *end = strrchr( psz_path, '/' );
497 if( end ) end[1] = '\0';
498 else *psz_path = '\0';
500 if( asprintf( &psz_absolute, "%s://%s%s",
501 p_demux->psz_access, psz_path, psz_ref ) < 0 )
505 input_item_node_Delete( p_subitems );
506 vlc_object_release( p_input) ;
511 psz_ref = psz_absolute;
514 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
515 input_item_t *p_item = input_item_New( psz_ref, NULL );
516 input_item_CopyOptions( p_current, p_item );
517 input_item_node_AppendItem( p_subitems, p_item );
518 vlc_gc_decref( p_item );
522 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
523 (char*)&p_rdrf->data.p_rdrf->i_ref_type );
527 input_item_node_PostAndDelete( p_subitems );
528 vlc_object_release( p_input );
531 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
535 msg_Err( p_demux, "cannot find /moov/mvhd" );
540 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
541 p_demux->pf_demux = DemuxRef;
547 p_sys->i_timescale = p_mvhd->data.p_mvhd->i_timescale;
548 if( p_sys->i_timescale == 0 )
550 msg_Err( p_this, "bad timescale" );
553 p_sys->i_duration = p_mvhd->data.p_mvhd->i_duration;
556 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
558 msg_Err( p_demux, "cannot find any /moov/trak" );
561 msg_Dbg( p_demux, "found %d track%c",
563 p_sys->i_tracks ? 's':' ' );
565 if( InitTracks( p_demux ) != VLC_SUCCESS )
568 /* Search the first chap reference (like quicktime) and
569 * check that at least 1 stream is enabled */
570 p_sys->p_tref_chap = NULL;
571 b_enabled_es = false;
572 for( i = 0; i < p_sys->i_tracks; i++ )
574 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
577 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
578 if( p_tkhd && (p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED) )
581 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
582 if( p_chap && p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
583 p_sys->p_tref_chap = p_chap;
586 /* now process each track and extract all useful information */
587 for( i = 0; i < p_sys->i_tracks; i++ )
589 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
590 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
592 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
595 switch( p_sys->track[i].fmt.i_cat )
604 psz_cat = "subtitle";
612 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
613 p_sys->track[i].i_track_ID, psz_cat,
614 p_sys->track[i].b_enable ? "enable":"disable",
615 p_sys->track[i].fmt.psz_language ?
616 p_sys->track[i].fmt.psz_language : "undef" );
618 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
620 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
621 p_sys->track[i].i_track_ID,
622 p_sys->track[i].fmt.psz_language ?
623 p_sys->track[i].fmt.psz_language : "undef" );
627 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
628 p_sys->track[i].i_track_ID );
633 LoadChapter( p_demux );
640 MP4_BoxFree( p_demux->s, p_sys->p_root );
646 /*****************************************************************************
647 * Demux: read packet and send them to decoders
648 *****************************************************************************
649 * TODO check for newly selected track (ie audio upt to now )
650 *****************************************************************************/
651 static int Demux( demux_t *p_demux )
653 demux_sys_t *p_sys = p_demux->p_sys;
654 unsigned int i_track;
657 unsigned int i_track_selected;
659 /* check for newly selected/unselected track */
660 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
663 mp4_track_t *tk = &p_sys->track[i_track];
666 if( !tk->b_ok || tk->b_chapter ||
667 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
672 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
674 if( tk->b_selected && !b )
676 MP4_TrackUnselect( p_demux, tk );
678 else if( !tk->b_selected && b)
680 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
689 if( i_track_selected <= 0 )
691 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
692 if( p_sys->i_timescale > 0 )
694 int64_t i_length = CLOCK_FREQ *
695 (mtime_t)p_sys->i_duration /
696 (mtime_t)p_sys->i_timescale;
697 if( MP4_GetMoviePTS( p_sys ) >= i_length )
702 msg_Warn( p_demux, "no track selected, exiting..." );
707 MP4_UpdateSeekpoint( p_demux );
709 /* first wait for the good time to read a packet */
710 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
712 /* we will read 100ms for each stream so ...*/
713 mtime_t i_targettime = p_sys->i_pcr + CLOCK_FREQ/10;
714 bool b_data_sent = false;
716 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
718 mp4_track_t *tk = &p_sys->track[i_track];
720 if( !tk->b_ok || tk->b_chapter || !tk->b_selected || tk->i_sample >= tk->i_sample_count )
723 while( MP4_TrackGetDTS( p_demux, tk ) < i_targettime )
726 msg_Dbg( p_demux, "tk(%i)=%lld mv=%lld", i_track,
727 MP4_TrackGetDTS( p_demux, tk ),
728 MP4_GetMoviePTS( p_sys ) );
730 int i_nb_samples = 0;
731 int i_samplessize = MP4_TrackSampleSize( tk, &i_nb_samples );
732 if( i_samplessize > 0 )
735 int64_t i_delta, i_newpos;
738 i_newpos = MP4_TrackGetPos( tk );
739 if( stream_Tell( p_demux->s ) != i_newpos )
741 if( stream_Seek( p_demux->s, i_newpos ) )
743 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
745 MP4_TrackUnselect( p_demux, tk );
751 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
753 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
755 MP4_TrackUnselect( p_demux, tk );
758 else if( tk->fmt.i_cat == SPU_ES )
760 if ( tk->fmt.i_codec != VLC_CODEC_TX3G )
761 p_block->i_buffer = 0;
765 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
767 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
769 p_block->i_pts = p_block->i_dts + i_delta;
770 else if( tk->fmt.i_cat != VIDEO_ES )
771 p_block->i_pts = p_block->i_dts;
773 p_block->i_pts = VLC_TS_INVALID;
777 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
780 es_out_Send( p_demux->out, tk->p_es, p_block );
784 if( MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
791 p_sys->i_pcr = INT64_MAX;
792 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
794 mp4_track_t *tk = &p_sys->track[i_track];
795 if ( !tk->b_ok || !tk->b_selected ) continue;
796 p_sys->i_pcr = __MIN( MP4_TrackGetDTS( p_demux, tk ), p_sys->i_pcr );
797 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
804 static void MP4_UpdateSeekpoint( demux_t *p_demux )
806 demux_sys_t *p_sys = p_demux->p_sys;
809 if( !p_sys->p_title )
811 i_time = MP4_GetMoviePTS( p_sys );
812 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
814 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
819 if( i != p_demux->info.i_seekpoint && i >= 0 )
821 p_demux->info.i_seekpoint = i;
822 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
825 /*****************************************************************************
827 ******************************************************************************/
828 static int Seek( demux_t *p_demux, mtime_t i_date )
830 demux_sys_t *p_sys = p_demux->p_sys;
831 unsigned int i_track;
833 /* First update global time */
834 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
835 p_sys->i_pcr = VLC_TS_INVALID;
837 /* Now for each stream try to go to this time */
838 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
840 mp4_track_t *tk = &p_sys->track[i_track];
841 MP4_TrackSeek( p_demux, tk, i_date );
843 MP4_UpdateSeekpoint( p_demux );
845 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
850 static int MP4_frg_Seek( demux_t *p_demux, double f )
852 demux_sys_t *p_sys = p_demux->p_sys;
854 int64_t i64 = stream_Size( p_demux->s );
855 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
861 /* update global time */
862 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_duration);
863 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
865 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
867 mp4_track_t *tk = &p_sys->track[i_track];
869 /* We don't want the current chunk to be flushed */
870 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
872 /* reset/update some values */
873 tk->i_sample = tk->i_sample_first = 0;
874 tk->i_first_dts = p_sys->i_time;
876 /* We want to discard the current chunk and get the next one at once */
877 tk->b_has_non_empty_cchunk = false;
879 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
884 /*****************************************************************************
886 *****************************************************************************/
887 static int Control( demux_t *p_demux, int i_query, va_list args )
889 demux_sys_t *p_sys = p_demux->p_sys;
896 case DEMUX_GET_POSITION:
897 pf = (double*)va_arg( args, double * );
898 if( p_sys->i_duration > 0 )
900 *pf = (double)p_sys->i_time / (double)p_sys->i_duration;
908 case DEMUX_SET_POSITION:
909 f = (double)va_arg( args, double );
910 if( p_sys->b_fragmented )
912 return MP4_frg_Seek( p_demux, f );
914 else if( p_sys->i_timescale > 0 )
916 i64 = (int64_t)( f * CLOCK_FREQ *
917 (double)p_sys->i_duration /
918 (double)p_sys->i_timescale );
919 return Seek( p_demux, i64 );
921 else return VLC_SUCCESS;
924 pi64 = (int64_t*)va_arg( args, int64_t * );
925 if( p_sys->i_timescale > 0 )
928 (mtime_t)p_sys->i_time /
929 (mtime_t)p_sys->i_timescale;
935 i64 = (int64_t)va_arg( args, int64_t );
936 return Seek( p_demux, i64 );
938 case DEMUX_GET_LENGTH:
939 pi64 = (int64_t*)va_arg( args, int64_t * );
940 if( p_sys->i_timescale > 0 )
943 (mtime_t)p_sys->i_duration /
944 (mtime_t)p_sys->i_timescale;
950 pf = (double*)va_arg( args, double* );
954 case DEMUX_GET_ATTACHMENTS:
956 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
957 int *pi_int = va_arg( args, int * );
959 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
960 if ( !p_covr ) return VLC_EGENERIC;
964 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
966 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
973 *ppp_attach = (input_attachment_t**)
974 malloc( sizeof(input_attachment_t*) * i_count );
975 if( !(*ppp_attach) ) return VLC_ENOMEM;
979 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
981 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
984 if ( !memcmp( p_box->data.p_data->p_blob,
985 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
987 psz_mime = strdup( "image/png" );
989 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
991 psz_mime = strdup( "image/jpeg" );
998 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1000 (*ppp_attach)[i_count++] =
1001 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1002 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1003 free( psz_filename );
1011 free( *ppp_attach );
1012 return VLC_EGENERIC;
1020 case DEMUX_GET_META:
1022 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1023 MP4_Box_t *p_0xa9xxx;
1025 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1027 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1029 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1030 if( p_udta == NULL )
1032 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1033 if( p_udta == NULL && p_covr == NULL )
1034 return VLC_EGENERIC;
1039 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1040 p_0xa9xxx = p_0xa9xxx->p_next )
1043 if( !p_0xa9xxx || !p_0xa9xxx->data.p_0xa9xxx )
1046 /* FIXME FIXME: should convert from whatever the character
1047 * encoding of MP4 meta data is to UTF-8. */
1048 #define SET(fct) do { char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" ); \
1049 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1050 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1052 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1053 switch( p_0xa9xxx->i_type )
1055 case ATOM_0xa9nam: /* Full name */
1056 SET( vlc_meta_SetTitle );
1059 SET( vlc_meta_SetArtist );
1062 SET( vlc_meta_SetArtist );
1065 SET( vlc_meta_SetCopyright );
1067 case ATOM_0xa9day: /* Creation Date */
1068 SET( vlc_meta_SetDate );
1070 case ATOM_0xa9des: /* Description */
1071 SET( vlc_meta_SetDescription );
1073 case ATOM_0xa9gen: /* Genre */
1074 SET( vlc_meta_SetGenre );
1078 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1079 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1082 case ATOM_0xa9alb: /* Album */
1083 SET( vlc_meta_SetAlbum );
1086 case ATOM_0xa9trk: /* Track */
1087 SET( vlc_meta_SetTrackNum );
1092 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1093 p_0xa9xxx->data.p_trkn->i_track_number );
1094 vlc_meta_SetTrackNum( p_meta, psz_trck );
1095 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1097 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1098 p_0xa9xxx->data.p_trkn->i_track_total );
1099 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1103 case ATOM_0xa9cmt: /* Commment */
1104 SET( vlc_meta_SetDescription );
1107 case ATOM_0xa9url: /* URL */
1108 SET( vlc_meta_SetURL );
1111 case ATOM_0xa9too: /* Encoder Tool */
1112 case ATOM_0xa9enc: /* Encoded By */
1113 SET( vlc_meta_SetEncodedBy );
1117 SET( vlc_meta_SetPublisher );
1121 SET( vlc_meta_SetDirector );
1128 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1130 { ATOM_0xa9wrt, N_("Writer") },
1131 { ATOM_0xa9com, N_("Composer") },
1132 { ATOM_0xa9prd, N_("Producer") },
1133 { ATOM_0xa9inf, N_("Information") },
1134 { ATOM_0xa9dis, N_("Disclaimer") },
1135 { ATOM_0xa9req, N_("Requirements") },
1136 { ATOM_0xa9fmt, N_("Original Format") },
1137 { ATOM_0xa9dsa, N_("Display Source As") },
1138 { ATOM_0xa9hst, N_("Host Computer") },
1139 { ATOM_0xa9prf, N_("Performers") },
1140 { ATOM_0xa9ope, N_("Original Performer") },
1141 { ATOM_0xa9src, N_("Providers Source Content") },
1142 { ATOM_0xa9wrn, N_("Warning") },
1143 { ATOM_0xa9swr, N_("Software") },
1144 { ATOM_0xa9lyr, N_("Lyrics") },
1145 { ATOM_0xa9mak, N_("Record Company") },
1146 { ATOM_0xa9mod, N_("Model") },
1147 { ATOM_0xa9PRD, N_("Product") },
1148 { ATOM_0xa9grp, N_("Grouping") },
1149 { ATOM_0xa9gen, N_("Genre") },
1150 { ATOM_0xa9st3, N_("Sub-Title") },
1151 { ATOM_0xa9arg, N_("Arranger") },
1152 { ATOM_0xa9ard, N_("Art Director") },
1153 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1154 { ATOM_0xa9con, N_("Conductor") },
1155 { ATOM_0xa9des, N_("Song Description") },
1156 { ATOM_0xa9lnt, N_("Liner Notes") },
1157 { ATOM_0xa9phg, N_("Phonogram Rights") },
1158 { ATOM_0xa9pub, N_("Publisher") },
1159 { ATOM_0xa9sne, N_("Sound Engineer") },
1160 { ATOM_0xa9sol, N_("Soloist") },
1161 { ATOM_0xa9thx, N_("Thanks") },
1162 { ATOM_0xa9xpd, N_("Executive Producer") },
1165 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1167 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1169 char *psz_utf = strdup( p_0xa9xxx->data.p_0xa9xxx->psz_text ? p_0xa9xxx->data.p_0xa9xxx->psz_text : "" );
1172 EnsureUTF8( psz_utf );
1173 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1183 case DEMUX_GET_TITLE_INFO:
1185 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1186 int *pi_int = (int*)va_arg( args, int* );
1187 int *pi_title_offset = (int*)va_arg( args, int* );
1188 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1190 if( !p_sys->p_title )
1191 return VLC_EGENERIC;
1194 *ppp_title = malloc( sizeof( input_title_t*) );
1195 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1196 *pi_title_offset = 0;
1197 *pi_seekpoint_offset = 0;
1200 case DEMUX_SET_TITLE:
1202 const int i_title = (int)va_arg( args, int );
1203 if( !p_sys->p_title || i_title != 0 )
1204 return VLC_EGENERIC;
1207 case DEMUX_SET_SEEKPOINT:
1209 const int i_seekpoint = (int)va_arg( args, int );
1210 if( !p_sys->p_title )
1211 return VLC_EGENERIC;
1212 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1215 case DEMUX_SET_NEXT_DEMUX_TIME:
1216 case DEMUX_SET_GROUP:
1217 case DEMUX_HAS_UNSUPPORTED_META:
1218 case DEMUX_GET_PTS_DELAY:
1219 case DEMUX_CAN_RECORD:
1220 return VLC_EGENERIC;
1223 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1224 return VLC_EGENERIC;
1228 /*****************************************************************************
1229 * Close: frees unused data
1230 *****************************************************************************/
1231 static void Close ( vlc_object_t * p_this )
1233 demux_t * p_demux = (demux_t *)p_this;
1234 demux_sys_t *p_sys = p_demux->p_sys;
1235 unsigned int i_track;
1237 msg_Dbg( p_demux, "freeing all memory" );
1239 MP4_BoxFree( p_demux->s, p_sys->p_root );
1240 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1242 MP4_TrackDestroy( &p_sys->track[i_track] );
1244 FREENULL( p_sys->track );
1246 if( p_sys->p_title )
1247 vlc_input_title_Delete( p_sys->p_title );
1254 /****************************************************************************
1255 * Local functions, specific to vlc
1256 ****************************************************************************/
1258 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1260 demux_sys_t *p_sys = p_demux->p_sys;
1263 p_sys->p_title = vlc_input_title_New();
1264 for( i = 0; i < p_chpl->data.p_chpl->i_chapter; i++ )
1266 seekpoint_t *s = vlc_seekpoint_New();
1268 s->psz_name = strdup( p_chpl->data.p_chpl->chapter[i].psz_name );
1269 EnsureUTF8( s->psz_name );
1270 s->i_time_offset = p_chpl->data.p_chpl->chapter[i].i_start / 10;
1271 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1274 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1276 demux_sys_t *p_sys = p_demux->p_sys;
1278 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1280 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1281 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1282 int i_nb_samples = 0;
1283 const unsigned int i_size = MP4_TrackSampleSize( tk, &i_nb_samples );
1285 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1288 const int i_read = stream_Read( p_demux->s, p_buffer, __MIN( sizeof(p_buffer), i_size ) );
1289 const int i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1293 seekpoint_t *s = vlc_seekpoint_New();
1295 s->psz_name = strndup( &p_buffer[2], i_len );
1296 EnsureUTF8( s->psz_name );
1298 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1300 if( !p_sys->p_title )
1301 p_sys->p_title = vlc_input_title_New();
1302 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1305 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1306 tk->chunk[tk->i_chunk].i_sample_count )
1310 static void LoadChapter( demux_t *p_demux )
1312 demux_sys_t *p_sys = p_demux->p_sys;
1315 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) && p_chpl->data.p_chpl->i_chapter > 0 )
1317 LoadChapterGpac( p_demux, p_chpl );
1319 else if( p_sys->p_tref_chap )
1321 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1324 /* Load the first subtitle track like quicktime */
1325 for( i = 0; i < p_chap->i_entry_count; i++ )
1327 for( j = 0; j < p_sys->i_tracks; j++ )
1329 mp4_track_t *tk = &p_sys->track[j];
1330 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1331 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1334 if( j < p_sys->i_tracks )
1336 LoadChapterApple( p_demux, &p_sys->track[j] );
1342 /* Add duration if titles are enabled */
1343 if( p_sys->p_title )
1345 p_sys->p_title->i_length = CLOCK_FREQ *
1346 (uint64_t)p_sys->i_duration / (uint64_t)p_sys->i_timescale;
1350 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1351 static int TrackCreateChunksIndex( demux_t *p_demux,
1352 mp4_track_t *p_demux_track )
1354 demux_sys_t *p_sys = p_demux->p_sys;
1355 if( p_sys->b_fragmented )
1358 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1361 unsigned int i_chunk;
1362 unsigned int i_index, i_last;
1364 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1365 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1366 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1368 return( VLC_EGENERIC );
1371 p_demux_track->i_chunk_count = p_co64->data.p_co64->i_entry_count;
1372 if( !p_demux_track->i_chunk_count )
1374 msg_Warn( p_demux, "no chunk defined" );
1375 return( VLC_EGENERIC );
1377 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1378 sizeof( mp4_chunk_t ) );
1379 if( p_demux_track->chunk == NULL )
1384 /* first we read chunk offset */
1385 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1387 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1389 ck->i_offset = p_co64->data.p_co64->i_chunk_offset[i_chunk];
1391 ck->i_first_dts = 0;
1392 ck->p_sample_count_dts = NULL;
1393 ck->p_sample_delta_dts = NULL;
1394 ck->p_sample_count_pts = NULL;
1395 ck->p_sample_offset_pts = NULL;
1398 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1399 to be used for the sample XXX begin to 1
1400 We construct it begining at the end */
1401 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1402 i_index = p_stsc->data.p_stsc->i_entry_count;
1405 msg_Warn( p_demux, "cannot read chunk table or table empty" );
1406 return( VLC_EGENERIC );
1411 for( i_chunk = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1412 i_chunk < i_last; i_chunk++ )
1414 if( i_chunk >= p_demux_track->i_chunk_count )
1416 msg_Warn( p_demux, "corrupted chunk table" );
1417 return VLC_EGENERIC;
1420 p_demux_track->chunk[i_chunk].i_sample_description_index =
1421 p_stsc->data.p_stsc->i_sample_description_index[i_index];
1422 p_demux_track->chunk[i_chunk].i_sample_count =
1423 p_stsc->data.p_stsc->i_samples_per_chunk[i_index];
1425 i_last = p_stsc->data.p_stsc->i_first_chunk[i_index] - 1;
1428 p_demux_track->chunk[0].i_sample_first = 0;
1429 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1431 p_demux_track->chunk[i_chunk].i_sample_first =
1432 p_demux_track->chunk[i_chunk-1].i_sample_first +
1433 p_demux_track->chunk[i_chunk-1].i_sample_count;
1436 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1437 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1442 static int TrackCreateSamplesIndex( demux_t *p_demux,
1443 mp4_track_t *p_demux_track )
1445 demux_sys_t *p_sys = p_demux->p_sys;
1446 if( p_sys->b_fragmented )
1450 MP4_Box_data_stsz_t *stsz;
1451 MP4_Box_data_stts_t *stts;
1452 /* TODO use also stss and stsh table for seeking */
1453 /* FIXME use edit table */
1458 uint32_t i_index_sample_used;
1463 * Gives the sample size for each samples. There is also a stz2 table
1464 * (compressed form) that we need to implement TODO */
1465 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1468 /* FIXME and stz2 */
1469 msg_Warn( p_demux, "cannot find STSZ box" );
1470 return VLC_EGENERIC;
1472 stsz = p_box->data.p_stsz;
1475 * Gives mapping between sample and decoding time
1477 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1480 msg_Warn( p_demux, "cannot find STTS box" );
1481 return VLC_EGENERIC;
1483 stts = p_box->data.p_stts;
1485 /* Use stsz table to create a sample number -> sample size table */
1486 p_demux_track->i_sample_count = stsz->i_sample_count;
1487 if( stsz->i_sample_size )
1489 /* 1: all sample have the same size, so no need to construct a table */
1490 p_demux_track->i_sample_size = stsz->i_sample_size;
1491 p_demux_track->p_sample_size = NULL;
1495 /* 2: each sample can have a different size */
1496 p_demux_track->i_sample_size = 0;
1497 p_demux_track->p_sample_size =
1498 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1499 if( p_demux_track->p_sample_size == NULL )
1502 for( i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1504 p_demux_track->p_sample_size[i_sample] =
1505 stsz->i_entry_size[i_sample];
1509 /* Use stts table to create a sample number -> dts table.
1510 * XXX: if we don't want to waste too much memory, we can't expand
1511 * the box! so each chunk will contain an "extract" of this table
1512 * for fast research (problem with raw stream where a sample is sometime
1513 * just channels*bits_per_sample/8 */
1516 i_index = 0; i_index_sample_used = 0;
1517 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1519 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1520 uint32_t i_entry, i_sample_count, i;
1522 /* save first dts */
1523 ck->i_first_dts = i_next_dts;
1524 ck->i_last_dts = i_next_dts;
1526 /* count how many entries are needed for this chunk
1527 * for p_sample_delta_dts and p_sample_count_dts */
1528 i_sample_count = ck->i_sample_count;
1531 uint32_t i_array_offset = i_index;
1532 while( i_sample_count > 0 )
1534 if (likely( (UINT32_MAX - i_index) >= i_entry ))
1535 i_array_offset = i_index + i_entry;
1537 return VLC_EGENERIC;
1539 if ( i_array_offset >= stts->i_entry_count )
1541 if ( likely( i_entry != UINT32_MAX ) )
1546 if ( i_sample_count > stts->pi_sample_count[i_array_offset] )
1547 i_sample_count -= stts->pi_sample_count[i_array_offset];
1551 /* don't count already used sample in this entry */
1554 if ( i_index_sample_used < ( UINT32_MAX - i_sample_count ) )
1555 i_sample_count += i_index_sample_used;
1558 if (likely( i_entry != UINT32_MAX ))
1562 msg_Err( p_demux, "suspiciously high number of i_entry" );
1563 break; /* likely will go ENOMEM now */
1568 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1569 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1571 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1573 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1578 i_sample_count = ck->i_sample_count;
1579 for( i = 0; i < i_entry; i++ )
1584 if ( i_index >= stts->i_entry_count )
1585 i_index = stts->i_entry_count;
1587 if ( i_index_sample_used < stts->pi_sample_count[i_index] )
1588 i_rest = stts->pi_sample_count[i_index] - i_index_sample_used;
1592 i_used = __MIN( i_rest, i_sample_count );
1594 if ( (UINT32_MAX - i_index_sample_used) >= i_used )
1595 i_index_sample_used += i_used;
1597 i_index_sample_used = UINT32_MAX;
1599 if ( i_used > i_sample_count )
1600 i_sample_count -= i_used;
1604 i_next_dts += i_used * stts->pi_sample_delta[i_index];
1606 ck->p_sample_count_dts[i] = i_used;
1607 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1609 ck->i_last_dts = i_next_dts - ck->p_sample_delta_dts[i];
1611 if( i_index_sample_used >= stts->pi_sample_count[i_index] )
1613 i_index_sample_used = 0;
1614 if (unlikely( i_index == UINT32_MAX ))
1623 * Gives the delta between decoding time (dts) and composition table (pts)
1625 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
1628 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
1630 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
1632 /* Create pts-dts table per chunk */
1633 i_index = 0; i_index_sample_used = 0;
1634 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1636 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1637 uint32_t i_entry, i_sample_count, i;
1639 /* count how many entries are needed for this chunk
1640 * for p_sample_delta_dts and p_sample_count_dts */
1641 i_sample_count = ck->i_sample_count;
1644 uint32_t i_array_offset = i_index;
1645 while( i_sample_count > 0 )
1647 if ( (UINT32_MAX - i_index) > i_entry )
1648 i_array_offset = i_index + i_entry;
1650 i_array_offset = UINT32_MAX;
1652 if ( i_array_offset >= ctts->i_entry_count )
1654 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, ctts->i_entry_count );
1655 return VLC_EGENERIC;
1658 if ( i_sample_count > ctts->pi_sample_count[i_array_offset] )
1659 i_sample_count -= ctts->pi_sample_count[i_array_offset];
1663 /* don't count already used sample in this entry */
1666 if ( i_index_sample_used < ( UINT32_MAX - i_sample_count ) )
1667 i_sample_count += i_index_sample_used;
1670 if (likely( i_entry != UINT32_MAX ))
1674 msg_Err( p_demux, "suspiciously high number of i_entry" );
1675 break; /* likely will go ENOMEM now */
1680 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
1681 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
1682 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
1684 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1689 i_sample_count = ck->i_sample_count;
1691 for( i = 0; i < i_entry; i++ )
1696 if ( i_index >= ctts->i_entry_count )
1698 msg_Err( p_demux, "invalid index total samples" );
1699 return VLC_EGENERIC;
1702 if ( i_index_sample_used < ctts->pi_sample_count[i_index] )
1703 i_rest = ctts->pi_sample_count[i_index] - i_index_sample_used;
1707 i_used = __MIN( i_rest, i_sample_count );
1709 if ( (UINT32_MAX - i_index_sample_used) > i_used )
1710 i_index_sample_used += i_used;
1712 i_index_sample_used = UINT32_MAX;
1714 if ( i_used > i_sample_count )
1715 i_sample_count -= i_used;
1719 ck->p_sample_count_pts[i] = i_used;
1720 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
1722 if( i_index_sample_used >= ctts->pi_sample_count[i_index] )
1724 i_index_sample_used = 0;
1725 if (unlikely( i_index == UINT32_MAX ))
1734 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
1735 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
1736 i_next_dts / p_demux_track->i_timescale );
1742 * It computes the sample rate for a video track using the given sample
1745 static void TrackGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
1746 const mp4_track_t *p_track,
1747 unsigned i_sd_index,
1753 if( p_track->i_chunk_count <= 0 )
1757 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
1758 while( p_chunk > &p_track->chunk[0] &&
1759 p_chunk[-1].i_sample_description_index == i_sd_index )
1764 uint64_t i_sample = 0;
1765 uint64_t i_first_dts = p_chunk->i_first_dts;
1766 uint64_t i_last_dts;
1769 i_sample += p_chunk->i_sample_count;
1770 i_last_dts = p_chunk->i_last_dts;
1773 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
1774 p_chunk->i_sample_description_index == i_sd_index );
1776 if( i_sample > 1 && i_first_dts < i_last_dts )
1777 vlc_ureduce( pi_num, pi_den,
1778 ( i_sample - 1) * p_track->i_timescale,
1779 i_last_dts - i_first_dts,
1785 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
1787 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
1788 unsigned int i_chunk, es_out_id_t **pp_es )
1790 demux_sys_t *p_sys = p_demux->p_sys;
1791 unsigned int i_sample_description_index;
1793 if( p_sys->b_fragmented )
1794 i_sample_description_index = 1; /* XXX */
1796 i_sample_description_index =
1797 p_track->chunk[i_chunk].i_sample_description_index;
1799 MP4_Box_t *p_sample;
1808 if( !i_sample_description_index )
1810 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
1811 p_track->i_track_ID );
1812 return VLC_EGENERIC;
1815 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
1816 i_sample_description_index - 1 );
1819 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
1821 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
1822 p_track->i_track_ID );
1823 return VLC_EGENERIC;
1826 p_track->p_sample = p_sample;
1828 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) )
1830 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
1832 p_sample->i_type = p_frma->data.p_frma->i_type;
1835 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
1837 p_enda = MP4_BoxGet( p_sample, "enda" );
1839 p_pasp = MP4_BoxGet( p_sample, "pasp" );
1842 switch( p_track->fmt.i_cat )
1845 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
1846 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
1847 p_track->fmt.video.i_bits_per_pixel =
1848 p_sample->data.p_sample_vide->i_depth;
1850 /* fall on display size */
1851 if( p_track->fmt.video.i_width <= 0 )
1852 p_track->fmt.video.i_width = p_track->i_width;
1853 if( p_track->fmt.video.i_height <= 0 )
1854 p_track->fmt.video.i_height = p_track->i_height;
1856 /* Find out apect ratio from display size */
1857 if( p_track->i_width > 0 && p_track->i_height > 0 &&
1858 /* Work-around buggy muxed files */
1859 p_sample->data.p_sample_vide->i_width != p_track->i_width )
1861 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
1862 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
1864 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
1865 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
1867 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
1868 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
1871 /* Support for cropping (eg. in H263 files) */
1872 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
1873 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
1876 TrackGetESSampleRate( &p_track->fmt.video.i_frame_rate,
1877 &p_track->fmt.video.i_frame_rate_base,
1878 p_track, i_sample_description_index, i_chunk );
1879 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
1880 (float)p_track->fmt.video.i_frame_rate_base;
1883 switch( (int)p_track->f_rotation ) {
1885 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
1888 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
1891 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
1898 p_track->fmt.audio.i_channels =
1899 p_sample->data.p_sample_soun->i_channelcount;
1900 p_track->fmt.audio.i_rate =
1901 p_sample->data.p_sample_soun->i_sampleratehi;
1902 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
1903 p_sample->data.p_sample_soun->i_sampleratehi *
1904 p_sample->data.p_sample_soun->i_samplesize;
1905 p_track->fmt.audio.i_bitspersample =
1906 p_sample->data.p_sample_soun->i_samplesize;
1908 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
1910 MP4_Box_data_sample_soun_t *p_soun;
1911 p_soun = p_sample->data.p_sample_soun;
1913 if( p_soun->i_qt_version == 0 )
1915 switch( p_sample->i_type )
1917 case VLC_CODEC_ADPCM_IMA_QT:
1918 p_soun->i_qt_version = 1;
1919 p_soun->i_sample_per_packet = 64;
1920 p_soun->i_bytes_per_packet = 34;
1921 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
1922 p_soun->i_bytes_per_sample = 2;
1924 case VLC_CODEC_MACE3:
1925 p_soun->i_qt_version = 1;
1926 p_soun->i_sample_per_packet = 6;
1927 p_soun->i_bytes_per_packet = 2;
1928 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1929 p_soun->i_bytes_per_sample = 2;
1931 case VLC_CODEC_MACE6:
1932 p_soun->i_qt_version = 1;
1933 p_soun->i_sample_per_packet = 12;
1934 p_soun->i_bytes_per_packet = 2;
1935 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
1936 p_soun->i_bytes_per_sample = 2;
1938 case VLC_CODEC_ALAW:
1939 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
1940 p_soun->i_samplesize = 8;
1941 p_track->i_sample_size = p_soun->i_channelcount;
1943 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
1944 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
1945 case VLC_FOURCC( 't', 'w', 'o', 's' ):
1946 case VLC_FOURCC( 's', 'o', 'w', 't' ):
1947 /* What would be the fun if you could trust the .mov */
1948 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
1955 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
1957 p_soun->i_qt_version = 0;
1960 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
1962 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
1964 switch( p_sample->i_type )
1966 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
1967 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
1969 if( p_track->i_sample_size > 1 )
1970 p_soun->i_qt_version = 0;
1973 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
1974 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
1975 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
1976 p_soun->i_qt_version = 0;
1983 if( p_track->i_sample_size != 0 &&
1984 p_sample->data.p_sample_soun->i_qt_version == 1 &&
1985 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
1987 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
1988 p_sample->data.p_sample_soun->i_qt_version = 0;
1997 /* It's a little ugly but .. there are special cases */
1998 switch( p_sample->i_type )
2000 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2001 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2003 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2006 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2008 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2010 p_track->fmt.i_codec = VLC_CODEC_A52;
2013 static const int pi_bitrate[] = {
2020 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2021 p_track->fmt.audio.i_channels = 0;
2022 p_track->fmt.i_bitrate = 0;
2023 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2024 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2025 p_track->fmt.audio.i_bitspersample = 0;
2029 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2031 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2035 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2036 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2038 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2040 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2041 p_track->fmt.i_codec = VLC_CODEC_U8;
2043 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2045 /* Buggy files workaround */
2046 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2047 p_sample->data.p_sample_soun->i_sampleratehi) )
2049 MP4_Box_data_sample_soun_t *p_soun =
2050 p_sample->data.p_sample_soun;
2052 msg_Warn( p_demux, "i_timescale (%"PRIu64") != i_sampleratehi "
2053 "(%u), making both equal (report any problem).",
2054 p_track->i_timescale, p_soun->i_sampleratehi );
2056 if( p_soun->i_sampleratehi != 0 )
2057 p_track->i_timescale = p_soun->i_sampleratehi;
2059 p_soun->i_sampleratehi = p_track->i_timescale;
2064 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2065 p_track->fmt.i_codec = VLC_CODEC_H263;
2068 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2069 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2071 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2072 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2075 text_style_t *p_style = text_style_New();
2078 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2079 p_style->i_font_size = p_text->i_font_size;
2080 if ( p_text->i_font_color )
2082 p_style->i_font_color = p_text->i_font_color >> 8;
2083 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2085 if ( p_text->i_background_color[3] >> 8 )
2087 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2088 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2089 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2090 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2093 p_track->fmt.subs.p_style = p_style;
2095 /* FIXME UTF-8 doesn't work here ? */
2096 if( p_track->b_mac_encoding )
2097 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2099 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2102 case VLC_FOURCC('y','v','1','2'):
2103 p_track->fmt.i_codec = VLC_CODEC_YV12;
2105 case VLC_FOURCC('y','u','v','2'):
2106 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2109 case VLC_FOURCC('i','n','2','4'):
2110 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2111 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2113 case VLC_FOURCC('i','n','3','2'):
2114 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2115 VLC_CODEC_S32L : VLC_CODEC_S32B;
2117 case VLC_FOURCC('f','l','3','2'):
2118 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2119 VLC_CODEC_F32L : VLC_CODEC_F32B;
2121 case VLC_FOURCC('f','l','6','4'):
2122 p_track->fmt.i_codec = p_enda && p_enda->data.p_enda->i_little_endian == 1 ?
2123 VLC_CODEC_F64L : VLC_CODEC_F64B;
2125 case VLC_CODEC_DVD_LPCM:
2127 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2128 if( p_soun->i_qt_version == 2 &&
2129 p_soun->i_qt_description > 20 + 28 )
2136 static const struct {
2140 vlc_fourcc_t i_codec;
2142 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2143 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2144 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2145 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2147 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2148 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2150 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2151 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2152 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2153 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2155 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2156 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2157 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2158 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2160 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2161 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2162 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2163 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2167 uint32_t i_bits = GetDWBE(&p_soun->p_qt_description[20 + 20]);
2168 uint32_t i_flags = GetDWBE(&p_soun->p_qt_description[20 + 24]);
2170 for( int i = 0; p_formats[i].i_codec; i++ )
2172 if( p_formats[i].i_bits == i_bits &&
2173 (i_flags & p_formats[i].i_mask) == p_formats[i].i_flags )
2175 p_track->fmt.i_codec = p_formats[i].i_codec;
2176 p_track->fmt.audio.i_bitspersample = i_bits;
2177 p_track->fmt.audio.i_blockalign = p_soun->i_channelcount * i_bits / 8;
2178 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2180 p_soun->i_qt_version = 0;
2188 p_track->fmt.i_codec = p_sample->i_type;
2192 /* now see if esds is present and if so create a data packet
2193 with decoder_specific_info */
2194 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2195 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2196 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2197 ( p_esds->data.p_esds )&&
2200 /* First update information based on i_objectTypeIndication */
2201 switch( p_decconfig->i_objectTypeIndication )
2203 case( 0x20 ): /* MPEG4 VIDEO */
2204 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2206 case( 0x21 ): /* H.264 */
2207 p_track->fmt.i_codec = VLC_CODEC_H264;
2210 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2211 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2212 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2213 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2215 p_track->fmt.i_codec = VLC_CODEC_ALS;
2223 case( 0x65): /* MPEG2 video */
2224 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2226 /* Theses are MPEG2-AAC */
2227 case( 0x66): /* main profile */
2228 case( 0x67): /* Low complexity profile */
2229 case( 0x68): /* Scaleable Sampling rate profile */
2230 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2232 /* True MPEG 2 audio */
2234 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2236 case( 0x6a): /* MPEG1 video */
2237 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2239 case( 0x6b): /* MPEG1 audio */
2240 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2242 case( 0x6c ): /* jpeg */
2243 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2245 case( 0x6d ): /* png */
2246 p_track->fmt.i_codec = VLC_CODEC_PNG;
2248 case( 0x6e ): /* jpeg2000 */
2249 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2251 case( 0xa3 ): /* vc1 */
2252 p_track->fmt.i_codec = VLC_CODEC_VC1;
2255 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2258 p_track->fmt.i_codec = VLC_CODEC_A52;
2261 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2263 case( 0xa9 ): /* dts */
2264 case( 0xaa ): /* DTS-HD HRA */
2265 case( 0xab ): /* DTS-HD Master Audio */
2266 p_track->fmt.i_codec = VLC_CODEC_DTS;
2269 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2273 case( 0xe0 ): /* NeroDigital: dvd subs */
2274 if( p_track->fmt.i_cat == SPU_ES )
2276 p_track->fmt.i_codec = VLC_CODEC_SPU;
2277 if( p_track->i_width > 0 )
2278 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2279 if( p_track->i_height > 0 )
2280 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2283 case( 0xe1 ): /* QCelp for 3gp */
2284 if( p_track->fmt.i_cat == AUDIO_ES )
2286 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2292 /* Unknown entry, but don't touch i_fourcc */
2294 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2295 p_decconfig->i_objectTypeIndication,
2296 p_track->i_track_ID );
2299 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2300 if( p_track->fmt.i_extra > 0 )
2302 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2303 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2304 p_track->fmt.i_extra );
2309 switch( p_sample->i_type )
2311 /* qt decoder, send the complete chunk */
2312 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2313 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2314 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2315 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2316 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2317 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2318 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2319 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2320 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2321 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2322 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2323 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2324 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2326 /* qt decoder, send the complete chunk */
2327 case VLC_CODEC_SVQ1:
2328 case VLC_CODEC_SVQ3:
2329 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2330 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2331 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2332 p_track->fmt.i_extra =
2333 p_sample->data.p_sample_vide->i_qt_image_description;
2334 if( p_track->fmt.i_extra > 0 )
2336 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2337 memcpy( p_track->fmt.p_extra,
2338 p_sample->data.p_sample_vide->p_qt_image_description,
2339 p_track->fmt.i_extra);
2343 case VLC_CODEC_AMR_NB:
2344 p_track->fmt.audio.i_rate = 8000;
2346 case VLC_CODEC_AMR_WB:
2347 p_track->fmt.audio.i_rate = 16000;
2349 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2350 case VLC_CODEC_QDM2:
2351 case VLC_CODEC_ALAC:
2352 p_track->fmt.i_extra =
2353 p_sample->data.p_sample_soun->i_qt_description;
2354 if( p_track->fmt.i_extra > 0 )
2356 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2357 memcpy( p_track->fmt.p_extra,
2358 p_sample->data.p_sample_soun->p_qt_description,
2359 p_track->fmt.i_extra);
2361 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2363 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2364 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2368 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2370 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2373 p_track->fmt.i_extra = p_dvc1->data.p_dvc1->i_vc1;
2374 if( p_track->fmt.i_extra > 0 )
2376 p_track->fmt.p_extra = malloc( p_dvc1->data.p_dvc1->i_vc1 );
2377 memcpy( p_track->fmt.p_extra, p_dvc1->data.p_dvc1->p_vc1,
2378 p_track->fmt.i_extra );
2383 msg_Err( p_demux, "missing dvc1" );
2388 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2389 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2391 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2395 p_track->fmt.i_extra = p_avcC->data.p_avcC->i_avcC;
2396 if( p_track->fmt.i_extra > 0 )
2398 p_track->fmt.p_extra = malloc( p_avcC->data.p_avcC->i_avcC );
2399 memcpy( p_track->fmt.p_extra, p_avcC->data.p_avcC->p_avcC,
2400 p_track->fmt.i_extra );
2405 msg_Err( p_demux, "missing avcC" );
2409 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2410 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2412 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2416 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2417 if( p_track->fmt.i_extra > 0 )
2419 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2420 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2421 p_track->fmt.i_extra );
2423 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2427 msg_Err( p_demux, "missing hvcC" );
2433 case VLC_CODEC_ADPCM_MS:
2434 case VLC_CODEC_ADPCM_IMA_WAV:
2435 case VLC_CODEC_QCELP:
2436 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2440 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2448 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2453 /* given a time it return sample/chunk
2454 * it also update elst field of the track
2456 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2457 int64_t i_start, uint32_t *pi_chunk,
2458 uint32_t *pi_sample )
2460 demux_sys_t *p_sys = p_demux->p_sys;
2461 MP4_Box_t *p_box_stss;
2463 unsigned int i_sample;
2464 unsigned int i_chunk;
2467 /* FIXME see if it's needed to check p_track->i_chunk_count */
2468 if( p_track->i_chunk_count == 0 )
2469 return( VLC_EGENERIC );
2471 /* handle elst (find the correct one) */
2472 MP4_TrackSetELST( p_demux, p_track, i_start );
2473 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
2475 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
2476 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2478 /* now calculate i_start for this elst */
2480 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2488 /* to track time scale */
2489 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2490 /* add elst offset */
2491 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2492 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2493 elst->i_media_time[p_track->i_elst] > 0 )
2495 i_start += elst->i_media_time[p_track->i_elst];
2498 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2499 "ms (track)", p_track->i_elst,
2500 i_mvt * 1000 / p_sys->i_timescale,
2501 i_start * 1000 / p_track->i_timescale );
2505 /* convert absolute time to in timescale unit */
2506 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2509 /* we start from sample 0/chunk 0, hope it won't take too much time */
2510 /* *** find good chunk *** */
2511 for( i_chunk = 0; ; i_chunk++ )
2513 if( i_chunk + 1 >= p_track->i_chunk_count )
2515 /* at the end and can't check if i_start in this chunk,
2516 it will be check while searching i_sample */
2517 i_chunk = p_track->i_chunk_count - 1;
2521 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2522 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2528 /* *** find sample in the chunk *** */
2529 i_sample = p_track->chunk[i_chunk].i_sample_first;
2530 i_dts = p_track->chunk[i_chunk].i_first_dts;
2531 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2534 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2535 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2538 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2539 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2541 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2546 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2550 i_sample += ( i_start - i_dts ) /
2551 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2556 if( i_sample >= p_track->i_sample_count )
2558 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2559 "(seeking too far) chunk=%d sample=%d",
2560 p_track->i_track_ID, i_chunk, i_sample );
2561 return( VLC_EGENERIC );
2565 /* *** Try to find nearest sync points *** */
2566 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2568 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2569 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2570 p_track->i_track_ID );
2571 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2573 if( i_index >= p_stss->i_entry_count - 1 ||
2574 i_sample < p_stss->i_sample_number[i_index+1] )
2576 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2577 msg_Dbg( p_demux, "stts gives %d --> %d (sample number)",
2578 i_sample, i_sync_sample );
2580 if( i_sync_sample <= i_sample )
2582 while( i_chunk > 0 &&
2583 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2588 while( i_chunk < p_track->i_chunk_count - 1 &&
2589 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2590 p_track->chunk[i_chunk].i_sample_count )
2593 i_sample = i_sync_sample;
2600 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2601 "Sample Box (stss)", p_track->i_track_ID );
2604 *pi_chunk = i_chunk;
2605 *pi_sample = i_sample;
2610 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2611 unsigned int i_chunk, unsigned int i_sample )
2613 bool b_reselect = false;
2615 /* now see if actual es is ok */
2616 if( p_track->i_chunk >= p_track->i_chunk_count ||
2617 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2618 p_track->chunk[i_chunk].i_sample_description_index )
2620 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2621 p_track->i_track_ID );
2623 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2624 p_track->p_es, &b_reselect );
2626 es_out_Del( p_demux->out, p_track->p_es );
2628 p_track->p_es = NULL;
2630 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2632 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2633 p_track->i_track_ID );
2635 p_track->b_ok = false;
2636 p_track->b_selected = false;
2637 return VLC_EGENERIC;
2641 /* select again the new decoder */
2644 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2647 p_track->i_chunk = i_chunk;
2648 p_track->i_sample = i_sample;
2650 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2653 /****************************************************************************
2655 ****************************************************************************
2656 * Parse track information and create all needed data to run a track
2657 * If it succeed b_ok is set to 1 else to 0
2658 ****************************************************************************/
2659 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2660 MP4_Box_t *p_box_trak,
2661 bool b_force_enable )
2663 demux_sys_t *p_sys = p_demux->p_sys;
2665 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2666 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2676 char language[4] = { '\0' };
2678 /* hint track unsupported */
2680 /* set default value (-> track unusable) */
2681 p_track->b_ok = false;
2682 p_track->b_enable = false;
2683 p_track->b_selected = false;
2684 p_track->b_chapter = false;
2685 p_track->b_mac_encoding = false;
2687 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2694 /* do we launch this track by default ? */
2696 ( ( p_tkhd->data.p_tkhd->i_flags&MP4_TRACK_ENABLED ) != 0 );
2697 if( !p_track->b_enable )
2698 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2700 p_track->i_track_ID = p_tkhd->data.p_tkhd->i_track_ID;
2702 p_track->i_width = p_tkhd->data.p_tkhd->i_width / BLOCK16x16;
2703 p_track->i_height = p_tkhd->data.p_tkhd->i_height / BLOCK16x16;
2704 p_track->f_rotation = p_tkhd->data.p_tkhd->f_rotation;
2708 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2711 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2712 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2714 if( ( !p_mdhd )||( !p_hdlr ) )
2719 p_track->i_timescale = p_mdhd->data.p_mdhd->i_timescale;
2720 if( p_track->i_timescale == 0 )
2723 if( p_mdhd->data.p_mdhd->i_language_code < 0x400 )
2725 strcpy( language, MP4_ConvertMacCode( p_mdhd->data.p_mdhd->i_language_code ) );
2726 p_track->b_mac_encoding = true;
2728 else if( p_mdhd->data.p_mdhd->i_language_code == 0x7fff )
2729 p_track->b_mac_encoding = true;
2732 for( unsigned i = 0; i < 3; i++ )
2733 language[i] = p_mdhd->data.p_mdhd->i_language[i];
2737 switch( p_hdlr->data.p_hdlr->i_handler_type )
2740 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2744 p_track->fmt.i_cat = AUDIO_ES;
2748 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2752 p_track->fmt.i_cat = VIDEO_ES;
2759 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2760 p_track->fmt.i_cat = SPU_ES;
2767 p_track->i_elst = 0;
2768 p_track->i_elst_time = 0;
2769 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2771 MP4_Box_data_elst_t *elst = p_elst->data.p_elst;
2774 msg_Warn( p_demux, "elst box found" );
2775 for( i = 0; i < elst->i_entry_count; i++ )
2777 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2778 "ms) rate=%d.%d", i,
2779 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2780 elst->i_media_time[i] >= 0 ?
2781 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2783 elst->i_media_rate_integer[i],
2784 elst->i_media_rate_fraction[i] );
2791 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2793 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2794 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2800 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2802 p_track->fmt.psz_language = strdup( language );
2805 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2808 MP4_Box_t *p_box_iter;
2809 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2810 p_box_iter = p_box_iter->p_next )
2812 switch( p_box_iter->i_type )
2815 p_track->fmt.psz_description =
2816 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
2819 p_track->fmt.psz_description =
2820 strdup( p_box_iter->data.p_name->psz_text );
2826 /* Create chunk index table and sample index table */
2827 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2828 TrackCreateSamplesIndex( p_demux, p_track ) )
2830 return; /* cannot create chunks index */
2833 p_track->i_chunk = 0;
2834 p_track->i_sample = 0;
2836 /* Mark chapter only track */
2837 if( p_sys->p_tref_chap )
2839 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2842 for( i = 0; i < p_chap->i_entry_count; i++ )
2844 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2845 p_track->fmt.i_cat == UNKNOWN_ES )
2847 p_track->b_chapter = true;
2848 p_track->b_enable = false;
2855 if( b_force_enable &&
2856 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2858 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2859 p_track->i_track_ID );
2860 p_track->b_enable = true;
2861 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2864 p_track->p_es = NULL;
2865 if( TrackCreateES( p_demux,
2866 p_track, p_track->i_chunk,
2867 p_track->b_chapter ? NULL : &p_track->p_es ) )
2869 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2870 p_track->i_track_ID );
2873 p_track->b_ok = true;
2877 for( i = 0; i < p_track->i_chunk_count; i++ )
2879 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2880 i, p_track->chunk[i].i_sample_count,
2881 p_track->chunk[i].i_first_dts );
2888 static void FreeAndResetChunk( mp4_chunk_t *ck )
2890 free( ck->p_sample_count_dts );
2891 free( ck->p_sample_delta_dts );
2892 free( ck->p_sample_count_pts );
2893 free( ck->p_sample_offset_pts );
2894 free( ck->p_sample_size );
2895 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2896 free( ck->p_sample_data[i] );
2897 free( ck->p_sample_data );
2898 memset( ck, 0, sizeof( mp4_chunk_t ) );
2901 /****************************************************************************
2903 ****************************************************************************
2904 * Destroy a track created by MP4_TrackCreate.
2905 ****************************************************************************/
2906 static void MP4_TrackDestroy( mp4_track_t *p_track )
2908 unsigned int i_chunk;
2910 p_track->b_ok = false;
2911 p_track->b_enable = false;
2912 p_track->b_selected = false;
2914 es_format_Clean( &p_track->fmt );
2916 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2918 if( p_track->chunk )
2920 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2921 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2923 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2924 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2927 FREENULL( p_track->chunk );
2928 if( p_track->cchunk ) {
2929 FreeAndResetChunk( p_track->cchunk );
2930 FREENULL( p_track->cchunk );
2933 if( !p_track->i_sample_size )
2935 FREENULL( p_track->p_sample_size );
2939 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2942 if( !p_track->b_ok || p_track->b_chapter )
2944 return VLC_EGENERIC;
2947 if( p_track->b_selected )
2949 msg_Warn( p_demux, "track[Id 0x%x] already selected",
2950 p_track->i_track_ID );
2954 return MP4_TrackSeek( p_demux, p_track, i_start );
2957 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2959 if( !p_track->b_ok || p_track->b_chapter )
2964 if( !p_track->b_selected )
2966 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2967 p_track->i_track_ID );
2972 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2973 p_track->p_es, false );
2976 p_track->b_selected = false;
2979 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2985 if( !p_track->b_ok || p_track->b_chapter )
2986 return VLC_EGENERIC;
2988 p_track->b_selected = false;
2990 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2991 &i_chunk, &i_sample ) )
2993 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2994 p_track->i_track_ID );
2995 return VLC_EGENERIC;
2998 p_track->b_selected = true;
3000 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3001 p_track->b_selected = true;
3003 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3008 * 3 types: for audio
3011 #define QT_V0_MAX_SAMPLES 1024
3012 static int MP4_TrackSampleSize( mp4_track_t *p_track, int *pi_nb_samples )
3015 MP4_Box_data_sample_soun_t *p_soun;
3017 if( p_track->i_sample_size == 0 )
3019 /* most simple case */
3020 return p_track->p_sample_size[p_track->i_sample];
3022 if( p_track->fmt.i_cat != AUDIO_ES )
3024 return p_track->i_sample_size;
3027 p_soun = p_track->p_sample->data.p_sample_soun;
3029 if( p_soun->i_qt_version == 1 )
3031 int i_samples = p_track->chunk[p_track->i_chunk].i_sample_count;
3032 if( p_track->fmt.audio.i_blockalign > 1 )
3033 i_samples = p_soun->i_sample_per_packet;
3035 i_size = i_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3037 else if( p_track->i_sample_size > 256 )
3039 /* We do that so we don't read too much data
3040 * (in this case we are likely dealing with compressed data) */
3041 i_size = p_track->i_sample_size;
3045 mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3046 int64_t i_length = CLOCK_FREQ / 10;
3048 int64_t i_maxsamples = 1;
3049 for( uint32_t i=p_track->i_sample; i<p_chunk->i_sample_count; i++ )
3051 i_length -= CLOCK_FREQ * p_chunk->p_sample_delta_dts[i] / p_track->i_timescale;
3052 if ( i_length < 0 ) break;
3056 i_samples = __MIN( QT_V0_MAX_SAMPLES, i_samples );
3057 i_samples = __MIN( i_maxsamples, i_samples );
3058 i_size = i_samples * p_track->i_sample_size;
3059 *pi_nb_samples = i_samples;
3062 //fprintf( stderr, "size=%d\n", i_size );
3066 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3068 unsigned int i_sample;
3071 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3073 if( p_track->i_sample_size )
3075 MP4_Box_data_sample_soun_t *p_soun =
3076 p_track->p_sample->data.p_sample_soun;
3078 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3080 i_pos += ( p_track->i_sample -
3081 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3082 p_track->i_sample_size;
3086 /* we read chunk by chunk unless a blockalign is requested */
3087 if( p_track->fmt.audio.i_blockalign > 1 )
3088 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3089 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3094 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3095 i_sample < p_track->i_sample; i_sample++ )
3097 i_pos += p_track->p_sample_size[i_sample];
3104 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, int i_samples )
3106 if( p_track->fmt.i_cat == AUDIO_ES && p_track->i_sample_size != 0 )
3108 MP4_Box_data_sample_soun_t *p_soun;
3110 p_soun = p_track->p_sample->data.p_sample_soun;
3112 if( p_soun->i_qt_version == 1 )
3114 /* we read chunk by chunk unless a blockalign is requested */
3115 if( p_track->fmt.audio.i_blockalign > 1 )
3116 p_track->i_sample += p_soun->i_sample_per_packet;
3118 p_track->i_sample += p_track->chunk[p_track->i_chunk].i_sample_count;
3120 else if( p_track->i_sample_size > 256 )
3122 /* We do that so we don't read too much data
3123 * (in this case we are likely dealing with compressed data) */
3124 p_track->i_sample += 1;
3129 p_track->i_sample += i_samples;
3130 if( p_track->i_sample >
3131 p_track->chunk[p_track->i_chunk].i_sample_first +
3132 p_track->chunk[p_track->i_chunk].i_sample_count )
3135 p_track->chunk[p_track->i_chunk].i_sample_first +
3136 p_track->chunk[p_track->i_chunk].i_sample_count;
3142 p_track->i_sample++;
3145 if( p_track->i_sample >= p_track->i_sample_count )
3146 return VLC_EGENERIC;
3148 /* Have we changed chunk ? */
3149 if( p_track->i_sample >=
3150 p_track->chunk[p_track->i_chunk].i_sample_first +
3151 p_track->chunk[p_track->i_chunk].i_sample_count )
3153 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3154 p_track->i_sample ) )
3156 msg_Warn( p_demux, "track[0x%x] will be disabled "
3157 "(cannot restart decoder)", p_track->i_track_ID );
3158 MP4_TrackUnselect( p_demux, p_track );
3159 return VLC_EGENERIC;
3163 /* Have we changed elst */
3164 if( p_track->p_elst && p_track->p_elst->data.p_elst->i_entry_count > 0 )
3166 demux_sys_t *p_sys = p_demux->p_sys;
3167 MP4_Box_data_elst_t *elst = p_track->p_elst->data.p_elst;
3168 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3169 p_sys->i_timescale / CLOCK_FREQ;
3171 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3172 i_mvt >= p_track->i_elst_time +
3173 elst->i_segment_duration[p_track->i_elst] )
3175 MP4_TrackSetELST( p_demux, p_track,
3176 MP4_TrackGetDTS( p_demux, p_track ) );
3183 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3186 demux_sys_t *p_sys = p_demux->p_sys;
3187 int i_elst_last = tk->i_elst;
3189 /* handle elst (find the correct one) */
3191 tk->i_elst_time = 0;
3192 if( tk->p_elst && tk->p_elst->data.p_elst->i_entry_count > 0 )
3194 MP4_Box_data_elst_t *elst = tk->p_elst->data.p_elst;
3195 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3197 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3199 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3201 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3205 tk->i_elst_time += i_dur;
3208 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3210 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3211 tk->i_elst = elst->i_entry_count - 1;
3212 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3215 if( elst->i_media_time[tk->i_elst] < 0 )
3218 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3221 if( i_elst_last != tk->i_elst )
3223 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3228 static const char *MP4_ConvertMacCode( uint16_t i_code )
3230 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3231 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3232 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3233 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3234 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3235 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3236 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3237 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3238 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3239 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3240 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3241 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3242 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3243 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3244 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3245 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3246 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3247 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3248 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3249 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3251 { "cy", 128 }, { "eu", 129 },
3252 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3253 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3254 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3255 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3260 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3262 if( p_cvt[i].i_code == i_code )
3263 return p_cvt[i].psz_iso639_1;
3268 /******************************************************************************
3269 * Here are the functions used for fragmented MP4
3270 *****************************************************************************/
3273 * It computes the sample rate for a video track using current video chunk
3275 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3276 const mp4_track_t *p_track )
3278 if( p_track->cchunk->i_last_dts == 0 )
3285 const mp4_chunk_t *p_chunk = p_track->cchunk;
3287 uint32_t i_sample = p_chunk->i_sample_count;
3288 uint64_t i_first_dts = p_chunk->i_first_dts;
3289 uint64_t i_last_dts = p_chunk->i_last_dts;
3291 if( i_sample > 1 && i_first_dts < i_last_dts )
3292 vlc_ureduce( pi_num, pi_den,
3293 ( i_sample - 1) * p_track->i_timescale,
3294 i_last_dts - i_first_dts,
3299 * Build raw avcC box (without the 8 bytes header)
3300 * \return The size of the box.
3302 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3303 const unsigned cpd_len )
3306 unsigned sps_len = 0, pps_len = 0;
3307 const uint32_t mark = 0x00000001;
3309 assert( CodecPrivateData[0] == 0 );
3310 assert( CodecPrivateData[1] == 0 );
3311 assert( CodecPrivateData[2] == 0 );
3312 assert( CodecPrivateData[3] == 1 );
3314 uint32_t length = cpd_len + 3;
3315 avcC = calloc( length, 1 );
3316 if( unlikely( avcC == NULL ) )
3319 uint8_t *sps = avcC + 8;
3321 uint32_t candidate = ~mark;
3322 CodecPrivateData += 4;
3323 for( unsigned i = 0; i < cpd_len - 4; i++ )
3325 sps[i] = CodecPrivateData[i];
3326 candidate = (candidate << 8) | CodecPrivateData[i];
3327 if( candidate == mark )
3338 uint8_t *pps = sps + sps_len + 3;
3339 pps_len = cpd_len - sps_len - 4 * 2;
3340 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3343 uint8_t AVCProfileIndication = 0x64;
3344 uint8_t profile_compatibility = 0x40;
3345 uint8_t AVCLevelIndication = 0x1f;
3346 uint8_t lengthSizeMinusOne = 0x03;
3349 avcC[1] = AVCProfileIndication;
3350 avcC[2] = profile_compatibility;
3351 avcC[3] = AVCLevelIndication;
3352 avcC[4] = 0xfc + lengthSizeMinusOne;
3354 avcC[6] = (sps_len & 0xff00)>>8;
3355 avcC[7] = sps_len & 0xff;
3357 avcC[8+sps_len] = 1;
3358 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3359 avcC[10+sps_len] = pps_len & 0xff;
3366 * Build a mp4_track_t from a StraBox
3369 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3371 fmt->i_extra = p_data->cpd_len;
3372 fmt->p_extra = malloc( p_data->cpd_len );
3373 if( unlikely( !fmt->p_extra ) )
3375 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3379 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3381 demux_sys_t *p_sys = p_demux->p_sys;
3383 MP4_Box_data_stra_t *p_data = p_stra->data.p_stra;
3385 return VLC_EGENERIC;
3387 p_track->b_ok = true;
3388 p_track->b_selected = false;
3389 p_track->i_sample_count = UINT32_MAX;
3391 p_track->i_timescale = p_sys->i_timescale;
3392 p_track->i_width = p_data->MaxWidth;
3393 p_track->i_height = p_data->MaxHeight;
3394 p_track->i_track_ID = p_data->i_track_ID;
3396 es_format_t *fmt = &p_track->fmt;
3398 return VLC_EGENERIC;
3400 es_format_Init( fmt, p_data->i_es_cat, 0 );
3402 /* Set language FIXME */
3403 fmt->psz_language = strdup( "en" );
3405 fmt->i_original_fourcc = p_data->FourCC;
3406 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3408 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3409 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3410 * for MS weird use of FourCC*/
3411 switch( fmt->i_cat )
3414 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3415 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3416 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3418 fmt->i_extra = build_raw_avcC( p_extra,
3419 p_data->CodecPrivateData, p_data->cpd_len );
3423 ret = MP4_SetCodecExtraData( fmt, p_data );
3424 if( ret != VLC_SUCCESS )
3428 fmt->video.i_width = p_data->MaxWidth;
3429 fmt->video.i_height = p_data->MaxHeight;
3430 fmt->video.i_bits_per_pixel = 0x18;
3431 fmt->video.i_visible_width = p_data->MaxWidth;
3432 fmt->video.i_visible_height = p_data->MaxHeight;
3435 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3436 &fmt->video.i_frame_rate_base, p_track );
3438 if( fmt->video.i_frame_rate_base != 0 )
3440 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3441 (float)fmt->video.i_frame_rate_base;
3444 p_demux->p_sys->f_fps = 24;
3449 fmt->audio.i_channels = p_data->Channels;
3450 fmt->audio.i_rate = p_data->SamplingRate;
3451 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3452 fmt->audio.i_blockalign = p_data->nBlockAlign;
3454 fmt->i_bitrate = p_data->Bitrate;
3456 ret = MP4_SetCodecExtraData( fmt, p_data );
3457 if( ret != VLC_SUCCESS )
3470 * Return the track identified by tid
3472 static mp4_track_t *MP4_frg_GetTrack( demux_t *p_demux, const uint32_t tid )
3474 demux_sys_t *p_sys = p_demux->p_sys;
3476 mp4_track_t *ret = NULL;
3477 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3479 ret = &p_sys->track[i];
3482 if( ret->i_track_ID == tid )
3485 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3489 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3491 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3492 mp4_chunk_t *ck = tk->cchunk;
3493 while( ck->i_sample < ck->i_sample_count )
3498 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3501 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3502 assert( sample_size > 0 );
3503 p_block = block_Alloc( sample_size );
3504 if( unlikely( !p_block ) )
3507 uint8_t *src = ck->p_sample_data[ck->i_sample];
3508 memcpy( p_block->p_buffer, src, sample_size );
3512 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3514 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3516 p_block->i_pts = p_block->i_dts + i_delta;
3517 else if( tk->fmt.i_cat != VIDEO_ES )
3518 p_block->i_pts = p_block->i_dts;
3520 p_block->i_pts = VLC_TS_INVALID;
3522 es_out_Send( p_demux->out, tk->p_es, p_block );
3530 * \Note If we call that function too soon,
3531 * before the track has been selected by MP4_TrackSelect
3532 * (during the first execution of Demux), then the track gets disabled
3534 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3536 demux_sys_t *p_sys = p_demux->p_sys;
3538 uint32_t i_sample = 0;
3539 bool b_smooth = false;
3540 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3542 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3547 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3548 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3549 return VLC_EGENERIC;
3553 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3555 return VLC_EGENERIC;
3558 i_sample = p_track->i_sample;
3559 es_out_Del( p_demux->out, p_track->p_es );
3560 es_format_Clean( &p_track->fmt );
3563 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3565 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3567 p_track->i_sample = i_sample;
3569 /* Temporary hack until we support track selection */
3570 p_track->b_selected = true;
3571 p_track->b_ok = true;
3572 p_track->b_enable = true;
3574 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3575 p_track->b_codec_need_restart = false;
3581 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3582 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3583 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3584 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3586 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3588 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
3589 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
3592 msg_Warn( p_demux, "no moof box found!" );
3593 return VLC_EGENERIC;
3596 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
3599 msg_Warn( p_demux, "no traf box found!" );
3600 return VLC_EGENERIC;
3603 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3606 msg_Warn( p_demux, "no tfhd box found!" );
3607 return VLC_EGENERIC;
3610 uint32_t i_track_ID = p_tfhd->data.p_tfhd->i_track_ID;
3611 *i_tk_id = i_track_ID;
3612 assert( i_track_ID > 0 );
3613 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3615 mp4_track_t *p_track = MP4_frg_GetTrack( p_demux, i_track_ID );
3617 return VLC_EGENERIC;
3619 mp4_chunk_t *ret = p_track->cchunk;
3621 if( p_tfhd->data.p_tfhd->b_empty )
3622 msg_Warn( p_demux, "No samples in this chunk!" );
3624 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3625 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3626 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3627 * and so on. Finally, suppose that we get the chunks the other way around,
3628 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3629 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3630 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3631 * flush it, i.e. send to the decoder the samples not yet sent.
3632 * Note that all the samples to be flushed should worth less than 100 ms,
3633 * (though I did not do the formal proof) and thus this flushing mechanism
3634 * should not cause A/V sync issues, or delays or whatever.
3636 if( ret->i_sample < ret->i_sample_count )
3637 FlushChunk( p_demux, p_track );
3639 if( ret->i_sample_count )
3640 FreeAndResetChunk( ret );
3642 uint32_t default_duration = 0;
3643 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
3644 default_duration = p_tfhd->data.p_tfhd->i_default_sample_duration;
3646 uint32_t default_size = 0;
3647 if( p_tfhd->data.p_tfhd->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
3648 default_size = p_tfhd->data.p_tfhd->i_default_sample_size;
3650 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3653 msg_Warn( p_demux, "no trun box found!" );
3654 return VLC_EGENERIC;
3656 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3658 ret->i_sample_count = p_trun_data->i_sample_count;
3659 assert( ret->i_sample_count > 0 );
3660 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3661 ret->i_sample_first = p_track->i_sample_first;
3662 p_track->i_sample_first += ret->i_sample_count;
3664 ret->i_first_dts = p_track->i_first_dts;
3666 /* XXX I already saw DASH content with no default_duration and no
3667 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
3668 * This chunk of code might be buggy with segments having
3669 * more than one subsegment. */
3670 if( !default_duration )
3674 MP4_Box_data_sidx_t *p_sidx_data = p_sidx->data.p_sidx;
3675 assert( p_sidx_data->i_reference_count == 1 );
3677 if( p_sidx_data->i_timescale == 0 )
3678 return VLC_EGENERIC;
3680 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
3681 p_sidx_data->i_timescale;
3682 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
3687 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
3689 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3690 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3692 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3695 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3696 if( !ret->p_sample_count_pts )
3699 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3701 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3702 if( !ret->p_sample_offset_pts )
3706 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3707 if( !ret->p_sample_size )
3710 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3711 if( !ret->p_sample_data )
3714 uint32_t dur = 0, len;
3715 uint32_t chunk_duration = 0, chunk_size = 0;
3717 /* Skip header of mdat */
3718 stream_Read( p_demux->s, NULL, 8 );
3720 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3722 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3723 dur = p_trun_data->p_samples[i].i_duration;
3725 dur = default_duration;
3726 ret->p_sample_delta_dts[i] = dur;
3727 chunk_duration += dur;
3729 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3731 if( ret->p_sample_offset_pts )
3733 ret->p_sample_offset_pts[i] =
3734 p_trun_data->p_samples[i].i_composition_time_offset;
3737 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3738 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3740 len = ret->p_sample_size[i] = default_size;
3742 ret->p_sample_data[i] = malloc( len );
3743 if( ret->p_sample_data[i] == NULL )
3745 int read = stream_Read( p_demux->s, ret->p_sample_data[i], len );
3746 if( read < (int)len )
3747 return VLC_EGENERIC;
3750 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3751 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3753 if( p_track->b_codec_need_restart &&
3754 p_track->fmt.i_cat == VIDEO_ES )
3755 ReInitDecoder( p_demux, p_track );
3757 p_track->b_has_non_empty_cchunk = true;
3762 * Get the next chunk of the track identified by i_tk_id.
3763 * \Note We don't want to seek all the time, so if the first chunk given by the
3764 * input method doesn't belong to the right track, we don't throw it away,
3765 * and so, in general, this function fetch more than one chunk.
3766 * Not to mention that a new init segment might be put everywhere
3767 * between two chunks by the input method.
3769 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3771 demux_sys_t *p_sys = p_demux->p_sys;
3772 mp4_track_t *p_track;
3774 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3776 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3778 return VLC_EGENERIC;
3780 if( !p_chunk->p_first )
3781 goto MP4_frg_GetChunks_Error;
3782 uint32_t i_type = p_chunk->p_first->i_type;
3784 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3786 MP4_BoxFree( p_demux->s, p_sys->p_root );
3787 p_sys->p_root = p_chunk;
3789 if( i_type == ATOM_ftyp ) /* DASH */
3791 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3794 msg_Warn( p_demux, "No tkhd found!" );
3795 goto MP4_frg_GetChunks_Error;
3797 tid = p_tkhd->data.p_tkhd->i_track_ID;
3799 else /* Smooth Streaming */
3801 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3802 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3803 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3805 msg_Warn( p_demux, "No StraBox found!" );
3806 goto MP4_frg_GetChunks_Error;
3808 tid = p_stra->data.p_stra->i_track_ID;
3811 p_track = MP4_frg_GetTrack( p_demux, tid );
3813 goto MP4_frg_GetChunks_Error;
3814 p_track->b_codec_need_restart = true;
3816 return MP4_frg_GetChunks( p_demux, i_tk_id );
3819 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3820 goto MP4_frg_GetChunks_Error;
3822 MP4_BoxFree( p_demux->s, p_chunk );
3824 if( tid == i_tk_id )
3829 MP4_frg_GetChunks_Error:
3830 MP4_BoxFree( p_demux->s, p_chunk );
3831 return VLC_EGENERIC;
3837 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3839 if( !p_track->b_ok || p_track->b_chapter )
3841 return VLC_EGENERIC;
3844 if( p_track->b_selected )
3846 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3850 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3851 p_track->b_selected = true;
3856 * DemuxFrg: read packet and send them to decoders
3857 * \return 1 on success, 0 on error.
3858 * TODO check for newly selected track
3860 int DemuxFrg( demux_t *p_demux )
3862 demux_sys_t *p_sys = p_demux->p_sys;
3864 unsigned i_track_selected;
3866 /* check for newly selected/unselected track */
3867 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3869 mp4_track_t *tk = &p_sys->track[i_track];
3872 if( !tk->b_ok || tk->b_chapter )
3875 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3876 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3878 if( tk->b_selected && !b )
3880 MP4_TrackUnselect( p_demux, tk );
3882 else if( !tk->b_selected && b)
3884 MP4_frg_TrackSelect( p_demux, tk );
3887 if( tk->b_selected )
3891 if( i_track_selected <= 0 )
3893 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3894 if( p_sys->i_timescale > 0 )
3896 int64_t i_length = CLOCK_FREQ *
3897 (mtime_t)p_sys->i_duration /
3898 (mtime_t)p_sys->i_timescale;
3899 if( MP4_GetMoviePTS( p_sys ) >= i_length )
3904 msg_Warn( p_demux, "no track selected, exiting..." );
3908 /* first wait for the good time to read a packet */
3909 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3911 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3913 /* we will read 100ms for each stream so ...*/
3914 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3916 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3918 mp4_track_t *tk = &p_sys->track[i_track];
3920 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3922 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3926 if( !tk->b_has_non_empty_cchunk )
3928 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
3930 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
3935 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
3940 mp4_chunk_t *ck = tk->cchunk;
3941 if( ck->i_sample >= ck->i_sample_count )
3943 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
3944 ck->i_sample, ck->i_sample_count );
3948 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3949 p_block = block_Alloc( sample_size );
3950 uint8_t *src = ck->p_sample_data[ck->i_sample];
3951 memcpy( p_block->p_buffer, src, sample_size );
3954 if( ck->i_sample == ck->i_sample_count )
3955 tk->b_has_non_empty_cchunk = false;
3958 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3960 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3962 p_block->i_pts = p_block->i_dts + i_delta;
3963 else if( tk->fmt.i_cat != VIDEO_ES )
3964 p_block->i_pts = p_block->i_dts;
3966 p_block->i_pts = VLC_TS_INVALID;
3968 es_out_Send( p_demux->out, tk->p_es, p_block );
3972 if( !tk->b_has_non_empty_cchunk )