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 *****************************************************************************/
33 #include <vlc_plugin.h>
35 #include <vlc_demux.h>
36 #include <vlc_charset.h> /* EnsureUTF8 */
37 #include <vlc_input.h>
42 /*****************************************************************************
44 *****************************************************************************/
45 static int Open ( vlc_object_t * );
46 static void Close( vlc_object_t * );
49 set_category( CAT_INPUT )
50 set_subcategory( SUBCAT_INPUT_DEMUX )
51 set_description( N_("MP4 stream demuxer") )
52 set_shortname( N_("MP4") )
53 set_capability( "demux", 240 )
54 set_callbacks( Open, Close )
57 /*****************************************************************************
59 *****************************************************************************/
60 static int Demux ( demux_t * );
61 static int DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
62 static int DemuxFrg( demux_t * );
63 static int DemuxAsLeaf( 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_overall_duration; /* Full duration, including all fragments */
74 uint64_t i_time; /* time position of the presentation
75 * in movie timescale */
76 uint32_t i_timescale; /* movie time scale */
77 uint64_t i_duration; /* movie duration */
78 unsigned int i_tracks; /* number of tracks */
79 mp4_track_t *track; /* array of track */
80 float f_fps; /* number of frame per seconds */
82 bool b_fragmented; /* fMP4 */
86 bool b_smooth; /* Is it Smooth Streaming? */
90 bool b_fragments_probed;
91 mp4_fragment_t moovfragment; /* moov */
92 mp4_fragment_t *p_fragments; /* known fragments (moof following moov) */
96 mp4_fragment_t *p_fragment;
97 uint32_t i_current_box_type;
98 uint32_t i_mdatbytesleft;
99 uint32_t i_lastseqnumber;
103 MP4_Box_t *p_tref_chap;
106 input_title_t *p_title;
109 asf_packet_sys_t asfpacketsys;
110 uint64_t i_preroll; /* foobar */
111 int64_t i_preroll_start;
112 mp4_track_t *p_current_track; /* avoids matching stream_number */
115 /*****************************************************************************
116 * Declaration of local function
117 *****************************************************************************/
118 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
119 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
120 static void MP4_TrackDestroy( mp4_track_t * );
122 static block_t * MP4_Block_Read( demux_t *, const mp4_track_t *, int );
123 static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
125 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
126 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
128 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
130 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
131 static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
132 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
133 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
135 static void MP4_UpdateSeekpoint( demux_t * );
137 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
138 static void MP4_GetDefaultSizeAndDuration( demux_t *p_demux,
139 const MP4_Box_data_tfhd_t *p_tfhd_data,
140 uint32_t *pi_default_size,
141 uint32_t *pi_default_duration );
143 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox );
144 static int ProbeFragments( demux_t *p_demux, bool b_force );
145 static int ProbeIndex( demux_t *p_demux );
146 static mp4_fragment_t *GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact );
147 static mp4_fragment_t *GetFragmentByTime( demux_t *p_demux, const mtime_t i_time );
149 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
150 uint64_t *pi_pos, mtime_t *pi_mooftime );
151 static mtime_t LeafGetTrackFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *, unsigned int );
152 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
153 mp4_track_t **pp_tk, unsigned int *pi_chunk );
154 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof );
157 static asf_track_info_t * MP4ASF_GetTrackInfo( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number );
158 static void MP4ASF_Send(asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame);
159 static void MP4ASF_ResetFrames( demux_sys_t *p_sys );
163 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
165 uint32_t i_return = 0;
166 if ( i_toread > INT32_MAX )
168 i_return = stream_Read( s, p_read, INT32_MAX );
169 if ( i_return < INT32_MAX )
172 i_toread -= INT32_MAX;
174 i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
178 static bool MP4_stream_Tell( stream_t *s, uint64_t *pi_pos )
180 int64_t i_pos = stream_Tell( s );
185 *pi_pos = (uint64_t) i_pos;
190 static mtime_t GetTrackDurationInFragment( const mp4_fragment_t *p_fragment,
191 unsigned int i_track_ID )
193 for( unsigned int i=0; i<p_fragment->i_durations; i++ )
195 if( i_track_ID == p_fragment->p_durations[i].i_track_ID )
196 return p_fragment->p_durations[i].i_duration;
201 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
205 MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
208 if ( p_trex->i_type == ATOM_trex &&
209 BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
212 p_trex = p_trex->p_next;
217 static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
219 MP4_Box_t *p_trak = MP4_BoxGet( p_moov, "trak" );
223 if( p_trak->i_type == ATOM_trak &&
224 (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
225 BOXDATA(p_tkhd)->i_track_ID == i_id )
228 p_trak = p_trak->p_next;
233 /* Return time in microsecond of a track */
234 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
236 demux_sys_t *p_sys = p_demux->p_sys;
237 const mp4_chunk_t *p_chunk;
238 if( p_sys->b_fragmented )
239 p_chunk = p_track->cchunk;
241 p_chunk = &p_track->chunk[p_track->i_chunk];
243 unsigned int i_index = 0;
244 unsigned int i_sample = p_track->i_sample - p_chunk->i_sample_first;
245 int64_t i_dts = p_chunk->i_first_dts;
247 while( i_sample > 0 )
249 if( i_sample > p_chunk->p_sample_count_dts[i_index] )
251 i_dts += p_chunk->p_sample_count_dts[i_index] *
252 p_chunk->p_sample_delta_dts[i_index];
253 i_sample -= p_chunk->p_sample_count_dts[i_index];
258 i_dts += i_sample * p_chunk->p_sample_delta_dts[i_index];
263 /* now handle elst */
264 if( p_track->p_elst )
266 demux_sys_t *p_sys = p_demux->p_sys;
267 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
269 /* convert to offset */
270 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
271 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
272 elst->i_media_time[p_track->i_elst] > 0 )
274 i_dts -= elst->i_media_time[p_track->i_elst];
277 /* add i_elst_time */
278 i_dts += p_track->i_elst_time * p_track->i_timescale /
281 if( i_dts < 0 ) i_dts = 0;
284 return CLOCK_FREQ * i_dts / p_track->i_timescale;
287 static inline bool MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track,
290 demux_sys_t *p_sys = p_demux->p_sys;
292 if( p_sys->b_fragmented )
293 ck = p_track->cchunk;
295 ck = &p_track->chunk[p_track->i_chunk];
297 unsigned int i_index = 0;
298 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
300 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
303 for( i_index = 0;; i_index++ )
305 if( i_sample < ck->p_sample_count_pts[i_index] )
307 *pi_delta = ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
308 (int64_t)p_track->i_timescale;
312 i_sample -= ck->p_sample_count_pts[i_index];
317 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
319 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
322 static void LoadChapter( demux_t *p_demux );
324 static int LoadInitFrag( demux_t *p_demux )
326 demux_sys_t *p_sys = p_demux->p_sys;
328 if( p_sys->b_smooth ) /* Smooth Streaming */
330 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
332 goto LoadInitFragError;
336 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
337 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
338 goto LoadInitFragError;
339 /* Get number of tracks */
341 for( int i = 0; i < 3; i++ )
343 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
344 if( p_stra && BOXDATA(p_stra) && BOXDATA(p_stra)->i_track_ID )
346 /* Get timescale and duration of the video track; */
347 if( p_sys->i_timescale == 0 )
349 if ( p_stra && BOXDATA(p_stra) )
351 p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
352 p_sys->i_duration = BOXDATA(p_stra)->i_duration;
353 p_sys->i_overall_duration = BOXDATA(p_stra)->i_duration;
355 if( p_sys->i_timescale == 0 )
357 msg_Err( p_demux, "bad timescale" );
358 goto LoadInitFragError;
366 /* Load all boxes ( except raw data ) */
367 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
369 goto LoadInitFragError;
375 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
379 static int InitTracks( demux_t *p_demux )
381 demux_sys_t *p_sys = p_demux->p_sys;
383 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
384 if( p_sys->track == NULL )
387 if( p_sys->b_fragmented )
389 mp4_track_t *p_track;
390 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
392 p_track = &p_sys->track[i];
393 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
394 if( unlikely( !p_track->cchunk ) )
396 free( p_sys->track );
404 static void CreateTracksFromSmooBox( demux_t *p_demux )
406 demux_sys_t *p_sys = p_demux->p_sys;
408 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
409 mp4_track_t *p_track;
411 for( int i = 0; i < 3; i++ )
413 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
414 if( !p_stra || !BOXDATA(p_stra) || BOXDATA(p_stra)->i_track_ID == 0 )
418 p_track = &p_sys->track[j]; j++;
419 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
420 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
425 static block_t * MP4_EIA608_Convert( block_t * p_block )
427 /* Rebuild codec data from encap */
429 size_t i_remaining = p_block->i_buffer;
430 uint32_t i_bytes = 0;
433 if ( i_remaining < 10 ||
434 !(i_bytes = GetDWBE(p_block->p_buffer)) ||
435 (i_bytes + 8 > i_remaining) ||
436 memcmp("cdat", &p_block->p_buffer[4], 4) ||
437 !(p_newblock = block_Alloc( i_remaining * 3 - 8 )) )
439 p_block->i_buffer = 0;
443 uint8_t *p_write = p_newblock->p_buffer;
444 uint8_t *p_read = &p_block->p_buffer[8];
450 p_write[i_copied++] = 0; /* cc1 == field 0 */
451 p_write[i_copied++] = p_read[0];
452 p_write[i_copied++] = p_read[1];
456 } while( i_bytes >= 2 );
458 if ( i_remaining >= 10 &&
459 (i_bytes = GetDWBE(p_read)) &&
460 (i_bytes + 8 <= i_remaining) &&
461 !memcmp("cdt2", &p_read[4], 4) )
468 p_write[i_copied++] = 0; /* cc1 == field 0 */
469 p_write[i_copied++] = p_read[0];
470 p_write[i_copied++] = p_read[1];
473 } while( i_bytes >= 2 );
476 block_Release( p_block );
477 p_newblock->i_buffer = i_copied;
481 static block_t * MP4_Block_Read( demux_t *p_demux, const mp4_track_t *p_track, int i_size )
483 block_t *p_block = stream_Block( p_demux->s, i_size );
487 /* might have some encap */
488 if( p_track->fmt.i_cat == SPU_ES )
490 switch( p_track->fmt.i_codec )
496 case VLC_CODEC_EIA608_1:
497 p_block = MP4_EIA608_Convert( p_block );
500 p_block->i_buffer = 0;
508 static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
510 if ( p_track->b_chans_reorder && aout_BitsPerSample( p_track->fmt.i_codec ) )
512 aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
513 p_track->fmt.audio.i_channels,
514 p_track->rgi_chans_reordering,
515 p_track->fmt.i_codec );
518 p_block->i_flags |= p_track->i_block_flags;
520 /* ASF packets in mov */
523 /* Fake a new stream from MP4 block */
524 stream_t *p_stream = p_demux->s;
525 p_demux->s = stream_MemoryNew( p_demux, p_block->p_buffer, p_block->i_buffer, true );
528 p_track->i_dts_backup = p_block->i_dts;
529 p_track->i_pts_backup = p_block->i_pts;
530 /* And demux it as ASF packet */
531 DemuxASFPacket( &p_demux->p_sys->asfpacketsys, p_block->i_buffer, p_block->i_buffer );
532 stream_Delete(p_demux->s);
534 block_Release(p_block);
535 p_demux->s = p_stream;
538 es_out_Send( p_demux->out, p_track->p_es, p_block );
541 /*****************************************************************************
542 * Open: check file and initializes MP4 structures
543 *****************************************************************************/
544 static int Open( vlc_object_t * p_this )
546 demux_t *p_demux = (demux_t *)p_this;
549 const uint8_t *p_peek;
559 /* A little test to see if it could be a mp4 */
560 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
562 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
573 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
576 /* We don't yet support f4v, but avformat does. */
577 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
584 /* create our structure that will contains all data */
585 p_sys = calloc( 1, sizeof( demux_sys_t ) );
590 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
591 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
592 p_sys->b_seekmode = p_sys->b_fastseekable;
594 /*Set exported functions */
595 p_demux->pf_demux = Demux;
596 p_demux->pf_control = Control;
598 p_sys->context.i_lastseqnumber = 1;
600 p_demux->p_sys = p_sys;
602 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
603 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
605 p_sys->b_smooth = true;
606 p_sys->b_fragmented = true;
609 if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
613 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
615 switch( BOXDATA(p_ftyp)->i_major_brand )
619 "ISO Media file (isom) version %d.",
620 BOXDATA(p_ftyp)->i_minor_version );
626 msg_Dbg( p_demux, "3GPP Media file Release: %c",
627 #ifdef WORDS_BIGENDIAN
628 BOXDATA(p_ftyp)->i_major_brand
630 BOXDATA(p_ftyp)->i_major_brand >> 24
635 msg_Dbg( p_demux, "Apple QuickTime file" );
638 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
641 msg_Dbg( p_demux, "DASH Stream file" );
642 p_sys->b_dash = true;
646 "unrecognized major file specification (%4.4s).",
647 (char*)&BOXDATA(p_ftyp)->i_major_brand );
650 /* also lookup in compatibility list */
651 for(uint32_t i=0; i<BOXDATA(p_ftyp)->i_compatible_brands_count; i++)
653 if (BOXDATA(p_ftyp)->i_compatible_brands[i] == MAJOR_dash)
655 msg_Dbg( p_demux, "DASH Stream file" );
656 p_sys->b_dash = true;
662 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
665 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
667 if ( p_sys->b_seekable && !p_sys->b_smooth && !p_sys->b_dash )
669 /* Probe remaining to check if there's really fragments
670 or if that file is just ready to append fragments */
671 ProbeFragments( p_demux, false );
672 p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
674 if ( p_sys->b_fragmented && !p_sys->i_overall_duration )
675 ProbeFragments( p_demux, true );
678 p_sys->b_fragmented = true;
681 if ( !p_sys->moovfragment.p_moox )
682 AddFragment( p_demux, MP4_BoxGet( p_sys->p_root, "/moov" ) );
684 /* we always need a moov entry, but smooth has a workaround */
685 if ( !p_sys->moovfragment.p_moox && !p_sys->b_smooth )
688 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
690 if( p_sys->b_smooth )
692 if( InitTracks( p_demux ) != VLC_SUCCESS )
694 CreateTracksFromSmooBox( p_demux );
695 p_demux->pf_demux = DemuxFrg;
696 msg_Dbg( p_demux, "Set DemuxFrg mode" );
699 else if( p_sys->b_fragmented )
701 p_demux->pf_demux = DemuxAsLeaf;
702 msg_Dbg( p_demux, "Set experimental DemuxLeaf mode" );
705 if( !p_sys->b_seekable && p_demux->pf_demux == Demux )
707 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
711 /* the file need to have one moov box */
712 p_sys->moovfragment.p_moox = MP4_BoxGet( p_sys->p_root, "/moov", 0 );
713 if( !p_sys->moovfragment.p_moox )
715 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
719 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
722 /* we have a free box as a moov, rename it */
723 p_foov->i_type = ATOM_moov;
724 p_sys->moovfragment.p_moox = p_foov;
727 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
729 int i_count = MP4_BoxCount( p_rmra, "rmda" );
732 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
734 input_thread_t *p_input = demux_GetParentInput( p_demux );
735 input_item_t *p_current = input_GetItem( p_input );
737 input_item_node_t *p_subitems = input_item_node_Create( p_current );
739 for( i = 0; i < i_count; i++ )
741 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
745 if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
749 i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
751 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
752 psz_ref, (char*)&i_ref_type );
754 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
756 if( strstr( psz_ref, "qt5gateQT" ) )
758 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
761 if( !strncmp( psz_ref, "http://", 7 ) ||
762 !strncmp( psz_ref, "rtsp://", 7 ) )
769 char *psz_path = strdup( p_demux->psz_location );
770 char *end = strrchr( psz_path, '/' );
771 if( end ) end[1] = '\0';
772 else *psz_path = '\0';
774 if( asprintf( &psz_absolute, "%s://%s%s",
775 p_demux->psz_access, psz_path, psz_ref ) < 0 )
779 input_item_node_Delete( p_subitems );
780 vlc_object_release( p_input) ;
785 psz_ref = psz_absolute;
788 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
789 input_item_t *p_item = input_item_New( psz_ref, NULL );
790 input_item_CopyOptions( p_current, p_item );
791 input_item_node_AppendItem( p_subitems, p_item );
792 vlc_gc_decref( p_item );
796 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
797 (char*)&BOXDATA(p_rdrf)->i_ref_type );
801 input_item_node_PostAndDelete( p_subitems );
802 vlc_object_release( p_input );
805 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
809 msg_Err( p_demux, "cannot find /moov/mvhd" );
814 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
815 p_demux->pf_demux = DemuxRef;
821 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
822 if( p_sys->i_timescale == 0 )
824 msg_Err( p_this, "bad timescale" );
829 if ( p_sys->i_overall_duration == 0 )
831 /* Try in mehd if fragmented */
832 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
833 if ( p_mehd && p_mehd->data.p_mehd )
834 p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
837 for( i = 0; i < p_sys->i_tracks; i++ )
839 mtime_t i_duration = GetTrackDurationInFragment( &p_sys->moovfragment,
840 p_sys->track[i].i_track_ID );
841 p_sys->i_overall_duration = __MAX( p_sys->i_overall_duration, (uint64_t)i_duration );
846 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
848 msg_Err( p_demux, "cannot find any /moov/trak" );
851 msg_Dbg( p_demux, "found %d track%c",
853 p_sys->i_tracks ? 's':' ' );
855 if( InitTracks( p_demux ) != VLC_SUCCESS )
858 /* Search the first chap reference (like quicktime) and
859 * check that at least 1 stream is enabled */
860 p_sys->p_tref_chap = NULL;
861 b_enabled_es = false;
862 for( i = 0; i < p_sys->i_tracks; i++ )
864 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
867 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
868 if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
871 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
872 if( p_chap && p_chap->data.p_tref_generic &&
873 p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
874 p_sys->p_tref_chap = p_chap;
877 /* now process each track and extract all useful information */
878 for( i = 0; i < p_sys->i_tracks; i++ )
880 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
881 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
883 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
886 switch( p_sys->track[i].fmt.i_cat )
895 psz_cat = "subtitle";
903 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
904 p_sys->track[i].i_track_ID, psz_cat,
905 p_sys->track[i].b_enable ? "enable":"disable",
906 p_sys->track[i].fmt.psz_language ?
907 p_sys->track[i].fmt.psz_language : "undef" );
909 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
911 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
912 p_sys->track[i].i_track_ID,
913 p_sys->track[i].fmt.psz_language ?
914 p_sys->track[i].fmt.psz_language : "undef" );
918 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
919 p_sys->track[i].i_track_ID );
924 mtime_t i_total_duration = 0;
925 mp4_fragment_t *p_fragment = &p_sys->moovfragment;
926 while ( p_fragment && p_sys->i_tracks )
928 if ( (p_fragment != &p_sys->moovfragment || p_fragment->i_chunk_range_max_offset) &&
929 p_fragment->i_durations && p_fragment->p_durations[0].i_track_ID == p_sys->track[0].i_track_ID )
930 i_total_duration += CLOCK_FREQ * p_fragment->p_durations[0].i_duration / p_sys->i_timescale;
931 msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRIu64"<->%"PRIu64", "
932 "duration %"PRId64" @%"PRId64,
933 p_fragment->p_moox->i_pos, p_fragment->i_chunk_range_min_offset,
934 p_fragment->i_chunk_range_max_offset,
935 ( p_fragment->i_durations && p_fragment->p_durations[0].i_track_ID == p_sys->track[0].i_track_ID )?
936 CLOCK_FREQ * p_fragment->p_durations[0].i_duration / p_sys->i_timescale : 0, i_total_duration );
937 p_fragment = p_fragment->p_next;
942 LoadChapter( p_demux );
944 p_sys->asfpacketsys.p_demux = p_demux;
945 p_sys->asfpacketsys.pi_preroll = &p_sys->i_preroll;
946 p_sys->asfpacketsys.pi_preroll_start = &p_sys->i_preroll_start;
947 p_sys->asfpacketsys.pf_doskip = NULL;
948 p_sys->asfpacketsys.pf_send = MP4ASF_Send;
949 p_sys->asfpacketsys.pf_gettrackinfo = MP4ASF_GetTrackInfo;
950 p_sys->asfpacketsys.pf_updatetime = NULL;
951 p_sys->asfpacketsys.pf_setaspectratio = NULL;
958 MP4_BoxFree( p_demux->s, p_sys->p_root );
964 /*****************************************************************************
965 * Demux: read packet and send them to decoders
966 *****************************************************************************
967 * TODO check for newly selected track (ie audio upt to now )
968 *****************************************************************************/
969 static int Demux( demux_t *p_demux )
971 demux_sys_t *p_sys = p_demux->p_sys;
972 unsigned int i_track;
975 unsigned int i_track_selected;
977 /* check for newly selected/unselected track */
978 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
981 mp4_track_t *tk = &p_sys->track[i_track];
984 if( !tk->b_ok || tk->b_chapter ||
985 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
990 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
992 if( tk->b_selected && !b )
994 MP4_TrackUnselect( p_demux, tk );
996 else if( !tk->b_selected && b)
998 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
1001 if( tk->b_selected )
1007 if( i_track_selected <= 0 )
1009 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
1010 if( p_sys->i_timescale > 0 )
1012 int64_t i_length = CLOCK_FREQ *
1013 (mtime_t)p_sys->i_overall_duration /
1014 (mtime_t)p_sys->i_timescale;
1015 if( MP4_GetMoviePTS( p_sys ) >= i_length )
1020 msg_Warn( p_demux, "no track selected, exiting..." );
1025 MP4_UpdateSeekpoint( p_demux );
1027 /* first wait for the good time to read a packet */
1028 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
1030 bool b_data_sent = false;
1032 /* Find next track matching contiguous data */
1033 mp4_track_t *tk = NULL;
1034 uint64_t i_candidate_pos = UINT64_MAX;
1035 mtime_t i_candidate_dts = INT64_MAX;
1036 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1038 mp4_track_t *tk_tmp = &p_sys->track[i_track];
1039 if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
1042 if ( p_sys->b_seekmode )
1044 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk_tmp );
1045 if ( i_dts <= i_candidate_dts )
1048 i_candidate_dts = i_dts;
1049 i_candidate_pos = MP4_TrackGetPos( tk_tmp );
1054 /* Try to avoid seeking on non fastseekable. Will fail with non interleaved content */
1055 uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
1056 if ( i_pos <= i_candidate_pos )
1058 i_candidate_pos = i_pos;
1066 msg_Dbg( p_demux, "Could not select track by data position" );
1069 else if ( p_sys->b_seekmode )
1071 if( stream_Seek( p_demux->s, i_candidate_pos ) )
1073 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
1075 MP4_TrackUnselect( p_demux, tk );
1081 msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, tk->i_track_ID,
1082 MP4_TrackGetDTS( p_demux, tk ),
1083 MP4_GetMoviePTS( p_sys ), i_candidate_pos );
1086 uint32_t i_nb_samples = 0;
1087 uint32_t i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
1088 if( i_samplessize > 0 )
1092 uint64_t i_current_pos;
1095 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
1098 if( i_current_pos != i_candidate_pos )
1100 if( stream_Seek( p_demux->s, i_candidate_pos ) )
1102 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1103 ": Failed to seek to %"PRIu64,
1104 tk->i_track_ID, i_candidate_pos );
1105 MP4_TrackUnselect( p_demux, tk );
1108 i_current_pos = i_candidate_pos;
1112 if( !(p_block = MP4_Block_Read( p_demux, tk, i_samplessize )) )
1114 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1115 ": Failed to read %d bytes sample at %"PRIu64,
1116 tk->i_track_ID, i_samplessize, i_current_pos );
1117 MP4_TrackUnselect( p_demux, tk );
1122 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
1124 if( MP4_TrackGetPTSDelta( p_demux, tk, &i_delta ) )
1125 p_block->i_pts = p_block->i_dts + i_delta;
1126 else if( tk->fmt.i_cat != VIDEO_ES )
1127 p_block->i_pts = p_block->i_dts;
1129 p_block->i_pts = VLC_TS_INVALID;
1133 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1136 MP4_Block_Send( p_demux, tk, p_block );
1140 if ( i_nb_samples ) /* sample size could be 0, need to go fwd. see return */
1141 MP4_TrackNextSample( p_demux, tk, i_nb_samples );
1146 p_sys->i_pcr = INT64_MAX;
1147 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1149 mp4_track_t *tk = &p_sys->track[i_track];
1150 if ( !tk->b_ok || !tk->b_selected ||
1151 (tk->fmt.i_cat != AUDIO_ES && tk->fmt.i_cat != VIDEO_ES) )
1154 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1155 p_sys->i_pcr = __MIN( i_dts, p_sys->i_pcr );
1157 if ( !p_sys->b_seekmode && i_dts > p_sys->i_pcr + 2*CLOCK_FREQ )
1159 msg_Dbg( p_demux, "that media doesn't look interleaved, will need to seek");
1160 p_sys->b_seekmode = true;
1163 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
1167 return b_data_sent || ( i_samplessize == 0 && i_nb_samples );
1170 static void MP4_UpdateSeekpoint( demux_t *p_demux )
1172 demux_sys_t *p_sys = p_demux->p_sys;
1175 if( !p_sys->p_title )
1177 i_time = MP4_GetMoviePTS( p_sys );
1178 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
1180 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
1185 if( i != p_demux->info.i_seekpoint && i >= 0 )
1187 p_demux->info.i_seekpoint = i;
1188 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1191 /*****************************************************************************
1192 * Seek: Go to i_date
1193 ******************************************************************************/
1194 static int Seek( demux_t *p_demux, mtime_t i_date )
1196 demux_sys_t *p_sys = p_demux->p_sys;
1197 unsigned int i_track;
1199 /* First update global time */
1200 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
1201 p_sys->i_pcr = VLC_TS_INVALID;
1203 /* Now for each stream try to go to this time */
1204 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1206 mp4_track_t *tk = &p_sys->track[i_track];
1207 MP4_TrackSeek( p_demux, tk, i_date );
1209 MP4_UpdateSeekpoint( p_demux );
1211 MP4ASF_ResetFrames( p_sys );
1212 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1217 static int LeafSeekIntoFragment( demux_t *p_demux, mp4_fragment_t *p_fragment )
1219 demux_sys_t *p_sys = p_demux->p_sys;
1220 uint64_t i64 = p_fragment->i_chunk_range_min_offset;
1222 if ( p_fragment->p_moox->i_type == ATOM_moov )
1224 mp4_track_t *p_track;
1225 unsigned int i_chunk;
1226 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i64, &p_track, &i_chunk );
1227 if ( i_ret == VLC_EGENERIC )
1229 msg_Dbg( p_demux, "moov seek failed to identify %"PRIu64, i64 );
1232 msg_Dbg( p_demux, "moov seeking to %"PRIu64, i64 );
1236 i64 = p_fragment->i_chunk_range_min_offset;
1237 msg_Dbg( p_demux, "moof seeking to %"PRIu64, i64 );
1240 if( stream_Seek( p_demux->s, i64 ) )
1242 msg_Err( p_demux, "seek failed to %"PRIu64, i64 );
1243 return VLC_EGENERIC;
1247 p_sys->context.p_fragment = p_fragment;
1248 p_sys->context.i_current_box_type = ATOM_mdat;
1249 LeafMapTrafTrunContextes( p_demux, p_fragment->p_moox );
1250 p_sys->context.i_mdatbytesleft = p_fragment->i_chunk_range_max_offset - i64;
1252 mtime_t i_time_base = 0;
1253 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1255 mtime_t i_tracktime = LeafGetTrackFragmentTimeOffset( p_demux, p_fragment,
1256 p_sys->track[i_track].i_track_ID );
1257 p_sys->track[i_track].i_time = i_tracktime * p_sys->track[i_track].i_timescale / p_sys->i_timescale;
1258 i_time_base = __MIN( i_time_base, i_tracktime );
1260 p_sys->i_time = i_time_base;
1261 p_sys->i_pcr = VLC_TS_INVALID;
1266 static int LeafSeekToTime( demux_t *p_demux, mtime_t i_nztime )
1268 demux_sys_t *p_sys = p_demux->p_sys;
1269 mp4_fragment_t *p_fragment;
1271 if ( !p_sys->i_timescale || !p_sys->i_overall_duration || !p_sys->b_seekable )
1272 return VLC_EGENERIC;
1274 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1276 ProbeIndex( p_demux );
1277 p_sys->b_index_probed = true;
1280 p_fragment = GetFragmentByTime( p_demux, i_nztime );
1284 msg_Dbg( p_demux, "seek can't find matching fragment for %"PRId64", trying index", i_nztime );
1285 if ( LeafIndexGetMoofPosByTime( p_demux, i_nztime, &i64, &i_mooftime ) == VLC_SUCCESS )
1287 msg_Dbg( p_demux, "seek trying to go to unknown but indexed fragment at %"PRId64, i64 );
1288 if( stream_Seek( p_demux->s, i64 ) )
1290 msg_Err( p_demux, "seek to moof failed %"PRId64, i64 );
1291 return VLC_EGENERIC;
1293 p_sys->context.i_current_box_type = 0;
1294 p_sys->context.i_mdatbytesleft = 0;
1295 p_sys->context.p_fragment = NULL;
1296 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1298 p_sys->track[i_track].i_time = i_mooftime / CLOCK_FREQ * p_sys->track[i_track].i_timescale;
1300 p_sys->i_time = i_mooftime / CLOCK_FREQ * p_sys->i_timescale;
1301 p_sys->i_pcr = VLC_TS_INVALID;
1305 msg_Warn( p_demux, "seek by index failed" );
1306 return VLC_EGENERIC;
1311 msg_Dbg( p_demux, "seeking to fragment data starting at %"PRIu64" for time %"PRId64,
1312 p_fragment->i_chunk_range_min_offset, i_nztime );
1313 if ( LeafSeekIntoFragment( p_demux, p_fragment ) != VLC_SUCCESS )
1314 return VLC_EGENERIC;
1317 MP4ASF_ResetFrames( p_sys );
1318 /* And set next display time in that trun/fragment */
1319 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + i_nztime );
1323 static int LeafSeekToPos( demux_t *p_demux, double f )
1325 demux_sys_t *p_sys = p_demux->p_sys;
1326 if ( !p_sys->b_seekable )
1327 return VLC_EGENERIC;
1329 if ( p_sys->i_timescale && p_sys->i_overall_duration )
1331 return LeafSeekToTime( p_demux,
1332 (mtime_t)( f * CLOCK_FREQ * p_sys->i_overall_duration /
1333 p_sys->i_timescale ) );
1336 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1338 ProbeIndex( p_demux );
1339 p_sys->b_index_probed = true;
1342 /* Blind seek to pos only */
1343 uint64_t i64 = (uint64_t) stream_Size( p_demux->s ) * f;
1344 mp4_fragment_t *p_fragment = GetFragmentByPos( p_demux, i64, false );
1347 msg_Dbg( p_demux, "Seeking to fragment data starting at %"PRIu64" for pos %"PRIu64,
1348 p_fragment->i_chunk_range_min_offset, i64 );
1349 return LeafSeekIntoFragment( p_demux, p_fragment );
1353 msg_Dbg( p_demux, "Cant get fragment for data starting at %"PRIu64, i64 );
1354 return VLC_EGENERIC;
1358 static int MP4_frg_Seek( demux_t *p_demux, double f )
1360 demux_sys_t *p_sys = p_demux->p_sys;
1362 int64_t i64 = stream_Size( p_demux->s );
1363 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1365 return VLC_EGENERIC;
1369 /* update global time */
1370 p_sys->i_time = (uint64_t)(f * (double)p_sys->i_overall_duration);
1371 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
1373 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1375 mp4_track_t *tk = &p_sys->track[i_track];
1377 /* We don't want the current chunk to be flushed */
1378 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
1380 /* reset/update some values */
1381 tk->i_sample = tk->i_sample_first = 0;
1382 tk->i_first_dts = p_sys->i_time;
1384 /* We want to discard the current chunk and get the next one at once */
1385 tk->b_has_non_empty_cchunk = false;
1387 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
1392 static bool imageTypeCompatible( const MP4_Box_data_data_t *p_data )
1395 p_data->e_wellknowntype == DATA_WKT_PNG ||
1396 p_data->e_wellknowntype == DATA_WKT_JPEG ||
1397 p_data->e_wellknowntype == DATA_WKT_BMP );
1400 /*****************************************************************************
1402 *****************************************************************************/
1403 static int Control( demux_t *p_demux, int i_query, va_list args )
1405 demux_sys_t *p_sys = p_demux->p_sys;
1410 const char *psz_roots[] = { "/moov/udta/meta/ilst",
1417 const uint32_t rgi_pict_atoms[2] = { ATOM_PICT, ATOM_pict };
1421 case DEMUX_GET_POSITION:
1422 pf = (double*)va_arg( args, double * );
1423 if( p_sys->i_overall_duration > 0 )
1425 *pf = (double)p_sys->i_time / (double)p_sys->i_overall_duration;
1433 case DEMUX_SET_POSITION:
1434 f = (double)va_arg( args, double );
1435 if ( p_demux->pf_demux == DemuxAsLeaf )
1436 return LeafSeekToPos( p_demux, f );
1437 else if ( p_demux->pf_demux == DemuxFrg )
1438 return MP4_frg_Seek( p_demux, f );
1439 else if( p_sys->i_timescale > 0 )
1441 i64 = (int64_t)( f * CLOCK_FREQ *
1442 (double)p_sys->i_overall_duration /
1443 (double)p_sys->i_timescale );
1444 return Seek( p_demux, i64 );
1446 else return VLC_EGENERIC;
1448 case DEMUX_GET_TIME:
1449 pi64 = (int64_t*)va_arg( args, int64_t * );
1450 if( p_sys->i_timescale > 0 )
1452 *pi64 = CLOCK_FREQ *
1453 (mtime_t)p_sys->i_time /
1454 (mtime_t)p_sys->i_timescale;
1459 case DEMUX_SET_TIME:
1460 i64 = (int64_t)va_arg( args, int64_t );
1461 if ( p_demux->pf_demux == DemuxAsLeaf )
1462 return LeafSeekToTime( p_demux, i64 );
1464 return Seek( p_demux, i64 );
1466 case DEMUX_GET_LENGTH:
1467 pi64 = (int64_t*)va_arg( args, int64_t * );
1468 if( p_sys->i_timescale > 0 )
1470 *pi64 = CLOCK_FREQ *
1471 (mtime_t)p_sys->i_overall_duration /
1472 (mtime_t)p_sys->i_timescale;
1478 pf = (double*)va_arg( args, double* );
1482 case DEMUX_GET_ATTACHMENTS:
1484 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1485 int *pi_int = va_arg( args, int * );
1487 MP4_Box_t *p_udta = NULL;
1491 /* Count number of total attachments */
1492 for( ; psz_roots[i_index] && !p_udta; i_index++ )
1494 p_udta = MP4_BoxGet( p_sys->p_root, psz_roots[i_index] );
1496 i_count += MP4_BoxCount( p_udta, "covr/data" );
1499 for ( size_t i=0; i< ARRAY_SIZE(rgi_pict_atoms); i++ )
1502 snprintf( rgsz_path, 5, "%4.4s", (char*)&rgi_pict_atoms[i] );
1503 i_count += MP4_BoxCount( p_sys->p_root, rgsz_path );
1507 return VLC_EGENERIC;
1509 *ppp_attach = (input_attachment_t**)
1510 malloc( sizeof(input_attachment_t*) * i_count );
1511 if( !(*ppp_attach) ) return VLC_ENOMEM;
1513 /* First add cover attachments */
1515 size_t i_box_count = 0;
1518 const MP4_Box_t *p_data = MP4_BoxGet( p_udta, "covr/data" );
1519 for( ; p_data; p_data = p_data->p_next )
1525 if ( p_data->i_type != ATOM_data || !imageTypeCompatible( BOXDATA(p_data) ) )
1528 switch( BOXDATA(p_data)->e_wellknowntype )
1531 psz_mime = strdup( "image/png" );
1534 psz_mime = strdup( "image/jpeg" );
1537 psz_mime = strdup( "image/bmp" );
1543 if ( asprintf( &psz_filename, "%s/covr/data[%"PRIu64"]", psz_roots[i_index - 1],
1544 i_box_count - 1 ) >= 0 )
1546 (*ppp_attach)[i_count++] =
1547 vlc_input_attachment_New( psz_filename, psz_mime, "Cover picture",
1548 BOXDATA(p_data)->p_blob, BOXDATA(p_data)->i_blob );
1549 msg_Dbg( p_demux, "adding attachment %s", psz_filename );
1550 free( psz_filename );
1557 /* Then quickdraw pict ones */
1558 for ( size_t i=0; i< ARRAY_SIZE(rgi_pict_atoms); i++ )
1561 snprintf( rgsz_path, 5, "%4.4s", (char*)&rgi_pict_atoms[i] );
1562 const MP4_Box_t *p_pict = MP4_BoxGet( p_sys->p_root, rgsz_path );
1564 for( ; p_pict; p_pict = p_pict->p_next )
1566 if ( i_box_count++ == UINT16_MAX ) /* pnot only handles 2^16 */
1568 if ( p_pict->i_type != rgi_pict_atoms[i] )
1570 char rgsz_location[12];
1571 snprintf( rgsz_location, 12, "%4.4s[%"PRIu16"]", (char*)&rgi_pict_atoms[i],
1572 (uint16_t) i_box_count - 1 );
1573 (*ppp_attach)[i_count++] = vlc_input_attachment_New( rgsz_location, "image/x-pict",
1574 "Quickdraw image", p_pict->data.p_binary->p_blob, p_pict->data.p_binary->i_blob );
1575 msg_Dbg( p_demux, "adding attachment %s", rgsz_location );
1581 free( *ppp_attach );
1582 return VLC_EGENERIC;
1590 case DEMUX_GET_META:
1592 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1594 MP4_Box_t *p_data = NULL;
1595 MP4_Box_t *p_udta = NULL;
1596 bool b_attachment_set = false;
1598 for( int i_index = 0; psz_roots[i_index] && !p_udta; i_index++ )
1600 p_udta = MP4_BoxGet( p_sys->p_root, psz_roots[i_index] );
1603 p_data = MP4_BoxGet( p_udta, "covr/data" );
1604 if ( p_data && imageTypeCompatible( BOXDATA(p_data) ) )
1606 char *psz_attachment;
1607 if ( -1 != asprintf( &psz_attachment, "attachment://%s/covr/data[0]",
1608 psz_roots[i_index] ) )
1610 vlc_meta_SetArtURL( p_meta, psz_attachment );
1611 b_attachment_set = true;
1612 free( psz_attachment );
1618 const MP4_Box_t *p_pnot;
1619 if ( !b_attachment_set && (p_pnot = MP4_BoxGet( p_sys->p_root, "pnot" )) )
1621 for ( size_t i=0; i< ARRAY_SIZE(rgi_pict_atoms) && !b_attachment_set; i++ )
1623 if ( rgi_pict_atoms[i] == BOXDATA(p_pnot)->i_type )
1626 snprintf( rgsz_path, 26, "attachment://%4.4s[%"PRIu16"]",
1627 (char*)&rgi_pict_atoms[i], BOXDATA(p_pnot)->i_index - 1 );
1628 vlc_meta_SetArtURL( p_meta, rgsz_path );
1629 b_attachment_set = true;
1634 if( p_udta == NULL && !b_attachment_set )
1635 return VLC_EGENERIC;
1637 SetupMeta( p_meta, p_udta );
1642 case DEMUX_GET_TITLE_INFO:
1644 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1645 int *pi_int = (int*)va_arg( args, int* );
1646 int *pi_title_offset = (int*)va_arg( args, int* );
1647 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1649 if( !p_sys->p_title )
1650 return VLC_EGENERIC;
1653 *ppp_title = malloc( sizeof( input_title_t*) );
1654 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1655 *pi_title_offset = 0;
1656 *pi_seekpoint_offset = 0;
1659 case DEMUX_SET_TITLE:
1661 const int i_title = (int)va_arg( args, int );
1662 if( !p_sys->p_title || i_title != 0 )
1663 return VLC_EGENERIC;
1666 case DEMUX_SET_SEEKPOINT:
1668 const int i_seekpoint = (int)va_arg( args, int );
1669 if( !p_sys->p_title )
1670 return VLC_EGENERIC;
1671 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1673 case DEMUX_GET_PTS_DELAY:
1675 for( unsigned int i = 0; i < p_sys->i_tracks; i++ )
1677 const MP4_Box_t *p_load;
1678 if ( (p_load = MP4_BoxGet( p_sys->track[i].p_track, "load" )) &&
1679 BOXDATA(p_load)->i_duration > 0 )
1681 *va_arg(args, int64_t *) = BOXDATA(p_load)->i_duration *
1682 CLOCK_FREQ / p_sys->track[i].i_timescale;
1686 return VLC_EGENERIC;
1688 case DEMUX_SET_NEXT_DEMUX_TIME:
1689 case DEMUX_SET_GROUP:
1690 case DEMUX_HAS_UNSUPPORTED_META:
1691 case DEMUX_CAN_RECORD:
1692 return VLC_EGENERIC;
1695 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1696 return VLC_EGENERIC;
1700 /*****************************************************************************
1701 * Close: frees unused data
1702 *****************************************************************************/
1703 static void Close ( vlc_object_t * p_this )
1705 demux_t * p_demux = (demux_t *)p_this;
1706 demux_sys_t *p_sys = p_demux->p_sys;
1707 unsigned int i_track;
1709 msg_Dbg( p_demux, "freeing all memory" );
1711 MP4_BoxFree( p_demux->s, p_sys->p_root );
1712 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1714 MP4_TrackDestroy( &p_sys->track[i_track] );
1716 FREENULL( p_sys->track );
1718 if( p_sys->p_title )
1719 vlc_input_title_Delete( p_sys->p_title );
1721 while( p_sys->moovfragment.p_next )
1723 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next->p_next;
1724 free( p_sys->moovfragment.p_next->p_durations );
1725 free( p_sys->moovfragment.p_next );
1726 p_sys->moovfragment.p_next = p_fragment;
1728 free( p_sys->moovfragment.p_durations );
1735 /****************************************************************************
1736 * Local functions, specific to vlc
1737 ****************************************************************************/
1739 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1741 demux_sys_t *p_sys = p_demux->p_sys;
1744 p_sys->p_title = vlc_input_title_New();
1745 for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
1747 seekpoint_t *s = vlc_seekpoint_New();
1749 s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
1750 EnsureUTF8( s->psz_name );
1751 s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
1752 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1755 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1757 demux_sys_t *p_sys = p_demux->p_sys;
1759 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1761 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1762 int64_t i_pts_delta;
1763 if ( !MP4_TrackGetPTSDelta( p_demux, tk, &i_pts_delta ) )
1765 uint32_t i_nb_samples = 0;
1766 const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
1768 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1771 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1772 __MIN( sizeof(p_buffer), i_size ) );
1773 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1777 seekpoint_t *s = vlc_seekpoint_New();
1779 s->psz_name = strndup( &p_buffer[2], i_len );
1780 EnsureUTF8( s->psz_name );
1782 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1784 if( !p_sys->p_title )
1785 p_sys->p_title = vlc_input_title_New();
1786 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1789 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1790 tk->chunk[tk->i_chunk].i_sample_count )
1794 static void LoadChapter( demux_t *p_demux )
1796 demux_sys_t *p_sys = p_demux->p_sys;
1799 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
1800 BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
1802 LoadChapterGpac( p_demux, p_chpl );
1804 else if( p_sys->p_tref_chap )
1806 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1809 /* Load the first subtitle track like quicktime */
1810 for( i = 0; i < p_chap->i_entry_count; i++ )
1812 for( j = 0; j < p_sys->i_tracks; j++ )
1814 mp4_track_t *tk = &p_sys->track[j];
1815 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1816 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_TX3G )
1819 if( j < p_sys->i_tracks )
1821 LoadChapterApple( p_demux, &p_sys->track[j] );
1827 /* Add duration if titles are enabled */
1828 if( p_sys->p_title )
1830 p_sys->p_title->i_length = CLOCK_FREQ *
1831 (uint64_t)p_sys->i_overall_duration / (uint64_t)p_sys->i_timescale;
1835 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1836 static int TrackCreateChunksIndex( demux_t *p_demux,
1837 mp4_track_t *p_demux_track )
1839 demux_sys_t *p_sys = p_demux->p_sys;
1841 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1844 unsigned int i_chunk;
1845 unsigned int i_index, i_last;
1847 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1848 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1849 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1851 return( VLC_EGENERIC );
1854 p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
1855 if( !p_demux_track->i_chunk_count )
1857 msg_Warn( p_demux, "no chunk defined" );
1859 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1860 sizeof( mp4_chunk_t ) );
1861 if( p_demux_track->chunk == NULL )
1866 /* first we read chunk offset */
1867 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1869 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1871 ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
1873 ck->i_first_dts = 0;
1874 ck->p_sample_count_dts = NULL;
1875 ck->p_sample_delta_dts = NULL;
1876 ck->p_sample_count_pts = NULL;
1877 ck->p_sample_offset_pts = NULL;
1880 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1881 to be used for the sample XXX begin to 1
1882 We construct it begining at the end */
1883 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1884 i_index = BOXDATA(p_stsc)->i_entry_count;
1886 while( i_index-- > 0 )
1888 for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1889 i_chunk < i_last; i_chunk++ )
1891 if( i_chunk >= p_demux_track->i_chunk_count )
1893 msg_Warn( p_demux, "corrupted chunk table" );
1894 return VLC_EGENERIC;
1897 p_demux_track->chunk[i_chunk].i_sample_description_index =
1898 BOXDATA(p_stsc)->i_sample_description_index[i_index];
1899 p_demux_track->chunk[i_chunk].i_sample_count =
1900 BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
1902 i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1905 if ( p_demux_track->i_chunk_count )
1907 p_demux_track->chunk[0].i_sample_first = 0;
1908 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1910 p_demux_track->chunk[i_chunk].i_sample_first =
1911 p_demux_track->chunk[i_chunk-1].i_sample_first +
1912 p_demux_track->chunk[i_chunk-1].i_sample_count;
1916 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1917 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1919 if ( p_demux_track->i_chunk_count && (
1920 p_sys->moovfragment.i_chunk_range_min_offset == 0 ||
1921 p_sys->moovfragment.i_chunk_range_min_offset > p_demux_track->chunk[0].i_offset
1923 p_sys->moovfragment.i_chunk_range_min_offset = p_demux_track->chunk[0].i_offset;
1928 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1929 const uint32_t i_index,
1930 uint32_t i_index_samples_left,
1931 uint32_t i_sample_count,
1932 const uint32_t *pi_index_sample_count,
1933 const uint32_t i_table_count )
1935 uint32_t i_array_offset;
1936 while( i_sample_count > 0 )
1938 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1939 i_array_offset = i_index + *pi_entry;
1941 return VLC_EGENERIC;
1943 if ( i_array_offset >= i_table_count )
1945 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1946 return VLC_EGENERIC;
1949 if ( i_index_samples_left )
1951 if ( i_index_samples_left > i_sample_count )
1953 i_index_samples_left -= i_sample_count;
1955 *pi_entry +=1; /* No samples left, go copy */
1960 i_sample_count -= i_index_samples_left;
1961 i_index_samples_left = 0;
1968 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1976 static int TrackCreateSamplesIndex( demux_t *p_demux,
1977 mp4_track_t *p_demux_track )
1979 demux_sys_t *p_sys = p_demux->p_sys;
1982 MP4_Box_data_stsz_t *stsz;
1983 /* TODO use also stss and stsh table for seeking */
1984 /* FIXME use edit table */
1987 * Gives the sample size for each samples. There is also a stz2 table
1988 * (compressed form) that we need to implement TODO */
1989 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1992 /* FIXME and stz2 */
1993 msg_Warn( p_demux, "cannot find STSZ box" );
1994 return VLC_EGENERIC;
1996 stsz = p_box->data.p_stsz;
1998 /* Use stsz table to create a sample number -> sample size table */
1999 p_demux_track->i_sample_count = stsz->i_sample_count;
2000 if( stsz->i_sample_size )
2002 /* 1: all sample have the same size, so no need to construct a table */
2003 p_demux_track->i_sample_size = stsz->i_sample_size;
2004 p_demux_track->p_sample_size = NULL;
2008 /* 2: each sample can have a different size */
2009 p_demux_track->i_sample_size = 0;
2010 p_demux_track->p_sample_size =
2011 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
2012 if( p_demux_track->p_sample_size == NULL )
2015 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
2017 p_demux_track->p_sample_size[i_sample] =
2018 stsz->i_entry_size[i_sample];
2022 if ( p_demux_track->i_chunk_count )
2024 mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
2025 uint64_t i_total_size = lastchunk->i_offset;
2027 if ( p_demux_track->i_sample_size != 0 ) /* all samples have same size */
2029 i_total_size += (uint64_t)p_demux_track->i_sample_size * lastchunk->i_sample_count;
2033 if( (uint64_t)lastchunk->i_sample_count + p_demux_track->i_chunk_count - 1 > stsz->i_sample_count )
2035 msg_Err( p_demux, "invalid samples table: stsz table is too small" );
2036 return VLC_EGENERIC;
2039 for( uint32_t i=stsz->i_sample_count - lastchunk->i_sample_count;
2040 i<stsz->i_sample_count; i++)
2042 i_total_size += stsz->i_entry_size[i];
2046 if ( i_total_size > p_sys->moovfragment.i_chunk_range_max_offset )
2047 p_sys->moovfragment.i_chunk_range_max_offset = i_total_size;
2050 /* Use stts table to create a sample number -> dts table.
2051 * XXX: if we don't want to waste too much memory, we can't expand
2052 * the box! so each chunk will contain an "extract" of this table
2053 * for fast research (problem with raw stream where a sample is sometime
2054 * just channels*bits_per_sample/8 */
2056 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
2057 * differing in 2/2 fields and 1 signedness */
2059 mtime_t i_next_dts = 0;
2061 * Gives mapping between sample and decoding time
2063 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
2066 msg_Warn( p_demux, "cannot find STTS box" );
2067 return VLC_EGENERIC;
2071 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
2073 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
2075 /* Create sample -> dts table per chunk */
2076 uint32_t i_index = 0;
2077 uint32_t i_current_index_samples_left = 0;
2079 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2081 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2082 uint32_t i_entry, i_sample_count;
2084 /* save first dts */
2085 ck->i_first_dts = i_next_dts;
2086 ck->i_last_dts = i_next_dts;
2088 /* count how many entries are needed for this chunk
2089 * for p_sample_delta_dts and p_sample_count_dts */
2092 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2093 i_current_index_samples_left,
2095 stts->pi_sample_count,
2096 stts->i_entry_count );
2097 if ( i_ret != VLC_SUCCESS )
2101 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
2102 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
2103 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
2105 free( ck->p_sample_count_dts );
2106 free( ck->p_sample_delta_dts );
2107 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2112 i_sample_count = ck->i_sample_count;
2114 for( uint32_t i = 0; i < i_entry; i++ )
2116 if ( i_current_index_samples_left )
2118 if ( i_current_index_samples_left > i_sample_count )
2120 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2121 ck->p_sample_count_dts[i] = i_sample_count;
2122 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2123 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2124 i_current_index_samples_left -= i_sample_count;
2126 assert( i == i_entry - 1 );
2131 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
2132 ck->p_sample_count_dts[i] = i_current_index_samples_left;
2133 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2134 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2135 i_sample_count -= i_current_index_samples_left;
2136 i_current_index_samples_left = 0;
2142 if ( stts->pi_sample_count[i_index] > i_sample_count )
2144 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2145 ck->p_sample_count_dts[i] = i_sample_count;
2146 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2147 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2148 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
2150 assert( i == i_entry - 1 );
2151 // keep building from same index
2155 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
2156 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
2157 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2158 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2159 i_sample_count -= stts->pi_sample_count[i_index];
2170 * Gives the delta between decoding time (dts) and composition table (pts)
2172 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
2173 if( p_box && p_box->data.p_ctts )
2175 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
2177 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
2179 /* Create pts-dts table per chunk */
2180 uint32_t i_index = 0;
2181 uint32_t i_current_index_samples_left = 0;
2183 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2185 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2186 uint32_t i_entry, i_sample_count;
2188 /* count how many entries are needed for this chunk
2189 * for p_sample_offset_pts and p_sample_count_pts */
2191 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2192 i_current_index_samples_left,
2194 ctts->pi_sample_count,
2195 ctts->i_entry_count );
2196 if ( i_ret != VLC_SUCCESS )
2200 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
2201 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
2202 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
2204 free( ck->p_sample_count_pts );
2205 free( ck->p_sample_offset_pts );
2206 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2211 i_sample_count = ck->i_sample_count;
2213 for( uint32_t i = 0; i < i_entry; i++ )
2215 if ( i_current_index_samples_left )
2217 if ( i_current_index_samples_left > i_sample_count )
2219 ck->p_sample_count_pts[i] = i_sample_count;
2220 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2221 i_current_index_samples_left -= i_sample_count;
2223 assert( i == i_entry - 1 );
2228 ck->p_sample_count_pts[i] = i_current_index_samples_left;
2229 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2230 i_sample_count -= i_current_index_samples_left;
2231 i_current_index_samples_left = 0;
2237 if ( ctts->pi_sample_count[i_index] > i_sample_count )
2239 ck->p_sample_count_pts[i] = i_sample_count;
2240 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2241 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
2243 assert( i == i_entry - 1 );
2244 // keep building from same index
2248 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
2249 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2250 i_sample_count -= ctts->pi_sample_count[i_index];
2260 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
2261 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
2262 i_next_dts / p_demux_track->i_timescale );
2269 * It computes the sample rate for a video track using the given sample
2272 static void TrackGetESSampleRate( demux_t *p_demux,
2273 unsigned *pi_num, unsigned *pi_den,
2274 const mp4_track_t *p_track,
2275 unsigned i_sd_index,
2281 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_demux->p_sys->p_root, "/moov" ),
2282 p_track->i_track_ID );
2283 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
2284 if ( p_mdhd && BOXDATA(p_mdhd) )
2286 vlc_ureduce( pi_num, pi_den,
2287 (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
2288 (uint64_t) BOXDATA(p_mdhd)->i_duration,
2293 if( p_track->i_chunk_count == 0 )
2297 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
2298 while( p_chunk > &p_track->chunk[0] &&
2299 p_chunk[-1].i_sample_description_index == i_sd_index )
2304 uint64_t i_sample = 0;
2305 uint64_t i_first_dts = p_chunk->i_first_dts;
2306 uint64_t i_last_dts;
2309 i_sample += p_chunk->i_sample_count;
2310 i_last_dts = p_chunk->i_last_dts;
2313 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
2314 p_chunk->i_sample_description_index == i_sd_index );
2316 if( i_sample > 1 && i_first_dts < i_last_dts )
2317 vlc_ureduce( pi_num, pi_den,
2318 ( i_sample - 1) * p_track->i_timescale,
2319 i_last_dts - i_first_dts,
2325 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
2327 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
2328 unsigned int i_chunk, es_out_id_t **pp_es )
2330 demux_sys_t *p_sys = p_demux->p_sys;
2331 unsigned int i_sample_description_index;
2333 if( p_sys->b_fragmented || p_track->i_chunk_count == 0 )
2334 i_sample_description_index = 1; /* XXX */
2336 i_sample_description_index =
2337 p_track->chunk[i_chunk].i_sample_description_index;
2342 if( !i_sample_description_index )
2344 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
2345 p_track->i_track_ID );
2346 return VLC_EGENERIC;
2349 MP4_Box_t *p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
2350 i_sample_description_index - 1 );
2353 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
2355 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
2356 p_track->i_track_ID );
2357 return VLC_EGENERIC;
2360 p_track->p_sample = p_sample;
2363 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) && p_frma->data.p_frma )
2365 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
2367 p_sample->i_type = p_frma->data.p_frma->i_type;
2371 switch( p_track->fmt.i_cat )
2374 if ( !p_sample->data.p_sample_vide || p_sample->i_handler != ATOM_vide )
2376 SetupVideoES( p_demux, p_track, p_sample );
2378 /* Set frame rate */
2379 TrackGetESSampleRate( p_demux,
2380 &p_track->fmt.video.i_frame_rate,
2381 &p_track->fmt.video.i_frame_rate_base,
2382 p_track, i_sample_description_index, i_chunk );
2384 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
2385 (float)p_track->fmt.video.i_frame_rate_base;
2390 if ( !p_sample->data.p_sample_soun || p_sample->i_handler != ATOM_soun )
2392 SetupAudioES( p_demux, p_track, p_sample );
2396 if ( !p_sample->data.p_sample_text || p_sample->i_handler != ATOM_text )
2398 SetupSpuES( p_demux, p_track, p_sample );
2405 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2410 /* given a time it return sample/chunk
2411 * it also update elst field of the track
2413 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2414 int64_t i_start, uint32_t *pi_chunk,
2415 uint32_t *pi_sample )
2417 demux_sys_t *p_sys = p_demux->p_sys;
2418 MP4_Box_t *p_box_stss;
2420 unsigned int i_sample;
2421 unsigned int i_chunk;
2424 /* FIXME see if it's needed to check p_track->i_chunk_count */
2425 if( p_track->i_chunk_count == 0 )
2426 return( VLC_EGENERIC );
2428 /* handle elst (find the correct one) */
2429 MP4_TrackSetELST( p_demux, p_track, i_start );
2430 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
2432 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
2433 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2435 /* now calculate i_start for this elst */
2437 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2445 /* to track time scale */
2446 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2447 /* add elst offset */
2448 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2449 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2450 elst->i_media_time[p_track->i_elst] > 0 )
2452 i_start += elst->i_media_time[p_track->i_elst];
2455 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2456 "ms (track)", p_track->i_elst,
2457 i_mvt * 1000 / p_sys->i_timescale,
2458 i_start * 1000 / p_track->i_timescale );
2462 /* convert absolute time to in timescale unit */
2463 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2466 /* we start from sample 0/chunk 0, hope it won't take too much time */
2467 /* *** find good chunk *** */
2468 for( i_chunk = 0; ; i_chunk++ )
2470 if( i_chunk + 1 >= p_track->i_chunk_count )
2472 /* at the end and can't check if i_start in this chunk,
2473 it will be check while searching i_sample */
2474 i_chunk = p_track->i_chunk_count - 1;
2478 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2479 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2485 /* *** find sample in the chunk *** */
2486 i_sample = p_track->chunk[i_chunk].i_sample_first;
2487 i_dts = p_track->chunk[i_chunk].i_first_dts;
2488 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2491 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2492 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2495 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2496 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2498 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2503 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2507 i_sample += ( i_start - i_dts ) /
2508 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2513 if( i_sample >= p_track->i_sample_count )
2515 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2516 "(seeking too far) chunk=%d sample=%d",
2517 p_track->i_track_ID, i_chunk, i_sample );
2518 return( VLC_EGENERIC );
2522 /* *** Try to find nearest sync points *** */
2523 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2525 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2526 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2527 p_track->i_track_ID );
2528 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2530 if( i_index >= p_stss->i_entry_count - 1 ||
2531 i_sample < p_stss->i_sample_number[i_index+1] )
2533 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
2534 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
2535 i_sample, i_sync_sample );
2537 if( i_sync_sample <= i_sample )
2539 while( i_chunk > 0 &&
2540 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
2545 while( i_chunk < p_track->i_chunk_count - 1 &&
2546 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
2547 p_track->chunk[i_chunk].i_sample_count )
2550 i_sample = i_sync_sample;
2557 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
2558 "Sample Box (stss)", p_track->i_track_ID );
2561 *pi_chunk = i_chunk;
2562 *pi_sample = i_sample;
2567 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
2568 unsigned int i_chunk, unsigned int i_sample )
2570 bool b_reselect = false;
2572 /* now see if actual es is ok */
2573 if( p_track->i_chunk >= p_track->i_chunk_count ||
2574 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
2575 p_track->chunk[i_chunk].i_sample_description_index )
2577 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
2578 p_track->i_track_ID );
2580 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
2581 p_track->p_es, &b_reselect );
2583 es_out_Del( p_demux->out, p_track->p_es );
2585 p_track->p_es = NULL;
2587 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
2589 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2590 p_track->i_track_ID );
2592 p_track->b_ok = false;
2593 p_track->b_selected = false;
2594 return VLC_EGENERIC;
2598 /* select again the new decoder */
2601 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
2604 p_track->i_chunk = i_chunk;
2605 p_track->chunk[i_chunk].i_sample = i_sample - p_track->chunk[i_chunk].i_sample_first;
2606 p_track->i_sample = i_sample;
2608 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
2611 /****************************************************************************
2613 ****************************************************************************
2614 * Parse track information and create all needed data to run a track
2615 * If it succeed b_ok is set to 1 else to 0
2616 ****************************************************************************/
2617 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
2618 MP4_Box_t *p_box_trak,
2619 bool b_force_enable )
2621 demux_sys_t *p_sys = p_demux->p_sys;
2623 p_track->p_track = p_box_trak;
2625 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
2626 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
2636 char language[4] = { '\0' };
2638 /* hint track unsupported */
2640 /* set default value (-> track unusable) */
2641 p_track->b_ok = false;
2642 p_track->b_enable = false;
2643 p_track->b_selected = false;
2644 p_track->b_chapter = false;
2645 p_track->b_mac_encoding = false;
2647 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
2654 /* do we launch this track by default ? */
2656 ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
2657 if( !p_track->b_enable )
2658 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2660 p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
2662 p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
2663 p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
2664 p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
2668 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
2671 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
2672 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
2674 if( ( !p_mdhd )||( !p_hdlr ) )
2679 p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
2680 if( p_track->i_timescale == 0 )
2683 memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
2684 p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
2686 switch( p_hdlr->data.p_hdlr->i_handler_type )
2689 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
2693 p_track->fmt.i_cat = AUDIO_ES;
2697 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
2701 p_track->fmt.i_cat = VIDEO_ES;
2708 p_track->fmt.i_cat = SPU_ES;
2711 /* closed captions */
2713 p_track->fmt.i_cat = SPU_ES;
2720 p_track->i_elst = 0;
2721 p_track->i_elst_time = 0;
2722 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
2724 MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
2727 msg_Warn( p_demux, "elst box found" );
2728 for( i = 0; i < elst->i_entry_count; i++ )
2730 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
2731 "ms) rate=%d.%d", i,
2732 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
2733 elst->i_media_time[i] >= 0 ?
2734 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
2736 elst->i_media_rate_integer[i],
2737 elst->i_media_rate_fraction[i] );
2744 p_dinf = MP4_BoxGet( p_minf, "dinf" );
2746 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
2747 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
2753 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
2755 p_track->fmt.psz_language = strdup( language );
2758 p_udta = MP4_BoxGet( p_box_trak, "udta" );
2761 MP4_Box_t *p_box_iter;
2762 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
2763 p_box_iter = p_box_iter->p_next )
2765 switch( p_box_iter->i_type )
2769 p_track->fmt.psz_description =
2770 strdup( p_box_iter->data.p_string->psz_text );
2777 /* Create chunk index table and sample index table */
2778 if( TrackCreateChunksIndex( p_demux,p_track ) ||
2779 TrackCreateSamplesIndex( p_demux, p_track ) )
2781 msg_Err( p_demux, "cannot create chunks index" );
2782 return; /* cannot create chunks index */
2785 p_track->i_chunk = 0;
2786 p_track->i_sample = 0;
2788 /* Mark chapter only track */
2789 if( p_sys->p_tref_chap )
2791 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
2794 for( i = 0; i < p_chap->i_entry_count; i++ )
2796 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
2797 p_track->fmt.i_cat == UNKNOWN_ES )
2799 p_track->b_chapter = true;
2800 p_track->b_enable = false;
2806 const MP4_Box_t *p_tsel;
2808 if( b_force_enable &&
2809 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
2811 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
2812 p_track->i_track_ID );
2813 p_track->b_enable = true;
2814 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
2816 else if ( (p_tsel = MP4_BoxGet( p_box_trak, "udta/tsel" )) )
2818 if ( BOXDATA(p_tsel) && BOXDATA(p_tsel)->i_switch_group )
2820 p_track->i_switch_group = BOXDATA(p_tsel)->i_switch_group;
2821 int i_priority = ES_PRIORITY_SELECTABLE_MIN;
2822 for ( unsigned int i = 0; i < p_sys->i_tracks; i++ )
2824 const mp4_track_t *p_other = &p_sys->track[i];
2825 if( p_other && p_other != p_track &&
2826 p_other->fmt.i_cat == p_track->fmt.i_cat &&
2827 p_track->i_switch_group == p_other->i_switch_group )
2828 i_priority = __MAX( i_priority, p_other->fmt.i_priority + 1 );
2830 /* VLC only support ES priority for AUDIO_ES and SPU_ES.
2831 If there's another VIDEO_ES in the same group, we need to unselect it then */
2832 if ( p_track->fmt.i_cat == VIDEO_ES && i_priority > ES_PRIORITY_SELECTABLE_MIN )
2833 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
2835 p_track->fmt.i_priority = i_priority;
2838 /* If there's no tsel, try to enable the track coming first in edit list */
2839 else if ( p_track->p_elst && p_track->fmt.i_priority == ES_PRIORITY_SELECTABLE_MIN )
2841 #define MAX_SELECTABLE (INT_MAX - ES_PRIORITY_SELECTABLE_MIN)
2842 for ( uint32_t i=0; i<p_track->BOXDATA(p_elst)->i_entry_count; i++ )
2844 if ( p_track->BOXDATA(p_elst)->i_media_time[i] >= 0 &&
2845 p_track->BOXDATA(p_elst)->i_segment_duration[i] )
2847 /* We do selection by inverting start time into priority.
2848 The track with earliest edit will have the highest prio */
2849 const int i_time = __MIN( MAX_SELECTABLE, p_track->BOXDATA(p_elst)->i_media_time[i] );
2850 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + MAX_SELECTABLE - i_time;
2856 p_track->p_es = NULL;
2857 if( TrackCreateES( p_demux,
2858 p_track, p_track->i_chunk,
2859 p_track->b_chapter ? NULL : &p_track->p_es ) )
2861 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
2862 p_track->i_track_ID );
2865 p_track->b_ok = true;
2869 for( i = 0; i < p_track->i_chunk_count; i++ )
2871 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
2872 i, p_track->chunk[i].i_sample_count,
2873 p_track->chunk[i].i_first_dts );
2880 static void FreeAndResetChunk( mp4_chunk_t *ck )
2882 free( ck->p_sample_count_dts );
2883 free( ck->p_sample_delta_dts );
2884 free( ck->p_sample_count_pts );
2885 free( ck->p_sample_offset_pts );
2886 free( ck->p_sample_size );
2887 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
2888 free( ck->p_sample_data[i] );
2889 free( ck->p_sample_data );
2890 memset( ck, 0, sizeof( mp4_chunk_t ) );
2893 /****************************************************************************
2895 ****************************************************************************
2896 * Destroy a track created by MP4_TrackCreate.
2897 ****************************************************************************/
2898 static void MP4_TrackDestroy( mp4_track_t *p_track )
2900 unsigned int i_chunk;
2902 p_track->b_ok = false;
2903 p_track->b_enable = false;
2904 p_track->b_selected = false;
2906 es_format_Clean( &p_track->fmt );
2908 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
2910 if( p_track->chunk )
2912 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
2913 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
2915 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
2916 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
2919 FREENULL( p_track->chunk );
2920 if( p_track->cchunk ) {
2921 FreeAndResetChunk( p_track->cchunk );
2922 FREENULL( p_track->cchunk );
2925 if( !p_track->i_sample_size )
2927 FREENULL( p_track->p_sample_size );
2930 if ( p_track->asfinfo.p_frame )
2931 block_ChainRelease( p_track->asfinfo.p_frame );
2934 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
2937 if( !p_track->b_ok || p_track->b_chapter )
2939 return VLC_EGENERIC;
2942 if( p_track->b_selected )
2944 msg_Warn( p_demux, "track[Id 0x%x] already selected",
2945 p_track->i_track_ID );
2949 return MP4_TrackSeek( p_demux, p_track, i_start );
2952 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
2954 if( !p_track->b_ok || p_track->b_chapter )
2959 if( !p_track->b_selected )
2961 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
2962 p_track->i_track_ID );
2967 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
2968 p_track->p_es, false );
2971 p_track->b_selected = false;
2974 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
2980 if( !p_track->b_ok || p_track->b_chapter )
2981 return VLC_EGENERIC;
2983 p_track->b_selected = false;
2985 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
2986 &i_chunk, &i_sample ) )
2988 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
2989 p_track->i_track_ID );
2990 return VLC_EGENERIC;
2993 p_track->b_selected = true;
2994 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
2995 p_track->b_selected = true;
2997 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3002 * 3 types: for audio
3005 #define QT_V0_MAX_SAMPLES 1024
3006 static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3008 uint32_t i_size = 0;
3011 if ( p_track->i_sample == p_track->i_sample_count )
3014 if ( p_track->fmt.i_cat != AUDIO_ES )
3018 if( p_track->i_sample_size == 0 ) /* all sizes are different */
3019 return p_track->p_sample_size[p_track->i_sample];
3021 return p_track->i_sample_size;
3025 const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
3026 const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3027 uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample;
3029 /* Group audio packets so we don't call demux for single sample unit */
3030 if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
3031 p_soun->i_constLPCMframesperaudiopacket &&
3032 p_soun->i_constbytesperaudiopacket )
3034 /* uncompressed case */
3035 uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
3036 if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
3037 i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
3038 *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
3039 return i_packets * p_soun->i_constbytesperaudiopacket;
3042 /* all samples have a different size */
3043 if( p_track->i_sample_size == 0 )
3046 return p_track->p_sample_size[p_track->i_sample];
3049 if( p_soun->i_qt_version == 1 )
3051 if ( p_soun->i_compressionid == 0xFFFE )
3053 *pi_nb_samples = 1; /* != number of audio samples */
3054 if ( p_track->i_sample_size )
3055 return p_track->i_sample_size;
3057 return p_track->p_sample_size[p_track->i_sample];
3059 else if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
3061 /* in this case we are dealing with compressed data
3062 -2 in V1: additional fields are meaningless (VBR and such) */
3063 *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
3064 if( p_track->fmt.audio.i_blockalign > 1 )
3065 *pi_nb_samples = p_soun->i_sample_per_packet;
3066 i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3069 else /* uncompressed case */
3072 if( p_track->fmt.audio.i_blockalign > 1 )
3075 i_packets = i_max_samples / p_soun->i_sample_per_packet;
3077 if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
3078 i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
3080 *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
3081 i_size = i_packets * p_soun->i_bytes_per_frame;
3086 /* uncompressed v0 (qt) or... not (ISO) */
3088 for( uint32_t i=p_track->i_sample;
3089 i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
3090 i<p_track->i_sample_count;
3094 if ( p_track->i_sample_size == 0 )
3095 i_size += p_track->p_sample_size[i];
3097 i_size += p_track->i_sample_size;
3099 /* Try to detect compression in ISO */
3100 if(p_soun->i_compressionid != 0)
3102 /* Return only 1 sample */
3106 if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
3111 //fprintf( stderr, "size=%d\n", i_size );
3115 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3117 unsigned int i_sample;
3120 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3122 if( p_track->i_sample_size )
3124 MP4_Box_data_sample_soun_t *p_soun =
3125 p_track->p_sample->data.p_sample_soun;
3127 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 ||
3128 p_track->fmt.audio.i_blockalign <= 1 ||
3129 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame == 0 )
3131 i_pos += ( p_track->i_sample -
3132 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3133 p_track->i_sample_size;
3137 /* we read chunk by chunk unless a blockalign is requested */
3138 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3139 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3144 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3145 i_sample < p_track->i_sample; i_sample++ )
3147 i_pos += p_track->p_sample_size[i_sample];
3154 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3156 if ( UINT32_MAX - p_track->i_sample < i_samples )
3158 p_track->i_sample = UINT32_MAX;
3159 return VLC_EGENERIC;
3162 p_track->i_sample += i_samples;
3164 if( p_track->i_sample >= p_track->i_sample_count )
3165 return VLC_EGENERIC;
3167 /* Have we changed chunk ? */
3168 if( p_track->i_sample >=
3169 p_track->chunk[p_track->i_chunk].i_sample_first +
3170 p_track->chunk[p_track->i_chunk].i_sample_count )
3172 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3173 p_track->i_sample ) )
3175 msg_Warn( p_demux, "track[0x%x] will be disabled "
3176 "(cannot restart decoder)", p_track->i_track_ID );
3177 MP4_TrackUnselect( p_demux, p_track );
3178 return VLC_EGENERIC;
3182 /* Have we changed elst */
3183 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3185 demux_sys_t *p_sys = p_demux->p_sys;
3186 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3187 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3188 p_sys->i_timescale / CLOCK_FREQ;
3190 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3191 i_mvt >= p_track->i_elst_time +
3192 elst->i_segment_duration[p_track->i_elst] )
3194 MP4_TrackSetELST( p_demux, p_track,
3195 MP4_TrackGetDTS( p_demux, p_track ) );
3202 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3205 demux_sys_t *p_sys = p_demux->p_sys;
3206 int i_elst_last = tk->i_elst;
3208 /* handle elst (find the correct one) */
3210 tk->i_elst_time = 0;
3211 if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3213 MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3214 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3216 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3218 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3220 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3224 tk->i_elst_time += i_dur;
3227 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3229 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3230 tk->i_elst = elst->i_entry_count - 1;
3231 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3234 if( elst->i_media_time[tk->i_elst] < 0 )
3237 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3240 if( i_elst_last != tk->i_elst )
3242 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3246 /******************************************************************************
3247 * Here are the functions used for fragmented MP4
3248 *****************************************************************************/
3251 * It computes the sample rate for a video track using current video chunk
3253 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3254 const mp4_track_t *p_track )
3256 if( p_track->cchunk->i_last_dts == 0 )
3263 const mp4_chunk_t *p_chunk = p_track->cchunk;
3265 uint32_t i_sample = p_chunk->i_sample_count;
3266 uint64_t i_first_dts = p_chunk->i_first_dts;
3267 uint64_t i_last_dts = p_chunk->i_last_dts;
3269 if( i_sample > 1 && i_first_dts < i_last_dts )
3270 vlc_ureduce( pi_num, pi_den,
3271 ( i_sample - 1) * p_track->i_timescale,
3272 i_last_dts - i_first_dts,
3277 * Build raw avcC box (without the 8 bytes header)
3278 * \return The size of the box.
3280 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3281 const unsigned cpd_len )
3284 unsigned sps_len = 0, pps_len = 0;
3285 const uint32_t mark = 0x00000001;
3287 assert( CodecPrivateData[0] == 0 );
3288 assert( CodecPrivateData[1] == 0 );
3289 assert( CodecPrivateData[2] == 0 );
3290 assert( CodecPrivateData[3] == 1 );
3292 uint32_t length = cpd_len + 3;
3293 avcC = calloc( length, 1 );
3294 if( unlikely( avcC == NULL ) )
3297 uint8_t *sps = avcC + 8;
3299 uint32_t candidate = ~mark;
3300 CodecPrivateData += 4;
3301 for( unsigned i = 0; i < cpd_len - 4; i++ )
3303 sps[i] = CodecPrivateData[i];
3304 candidate = (candidate << 8) | CodecPrivateData[i];
3305 if( candidate == mark )
3316 uint8_t *pps = sps + sps_len + 3;
3317 pps_len = cpd_len - sps_len - 4 * 2;
3318 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3321 uint8_t AVCProfileIndication = 0x64;
3322 uint8_t profile_compatibility = 0x40;
3323 uint8_t AVCLevelIndication = 0x1f;
3324 uint8_t lengthSizeMinusOne = 0x03;
3327 avcC[1] = AVCProfileIndication;
3328 avcC[2] = profile_compatibility;
3329 avcC[3] = AVCLevelIndication;
3330 avcC[4] = 0xfc + lengthSizeMinusOne;
3332 avcC[6] = (sps_len & 0xff00)>>8;
3333 avcC[7] = sps_len & 0xff;
3335 avcC[8+sps_len] = 1;
3336 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3337 avcC[10+sps_len] = pps_len & 0xff;
3344 * Build a mp4_track_t from a StraBox
3347 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3349 fmt->i_extra = p_data->cpd_len;
3350 fmt->p_extra = malloc( p_data->cpd_len );
3351 if( unlikely( !fmt->p_extra ) )
3353 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3357 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3359 demux_sys_t *p_sys = p_demux->p_sys;
3361 MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3363 return VLC_EGENERIC;
3365 p_track->b_ok = true;
3366 p_track->b_selected = false;
3367 p_track->i_sample_count = UINT32_MAX;
3369 p_track->i_timescale = p_sys->i_timescale;
3370 p_track->i_width = p_data->MaxWidth;
3371 p_track->i_height = p_data->MaxHeight;
3372 p_track->i_track_ID = p_data->i_track_ID;
3374 es_format_t *fmt = &p_track->fmt;
3376 return VLC_EGENERIC;
3378 es_format_Init( fmt, p_data->i_es_cat, 0 );
3380 /* Set language FIXME */
3381 fmt->psz_language = strdup( "en" );
3383 fmt->i_original_fourcc = p_data->FourCC;
3384 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3386 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3387 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3388 * for MS weird use of FourCC*/
3389 switch( fmt->i_cat )
3392 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3393 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3394 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3396 fmt->i_extra = build_raw_avcC( p_extra,
3397 p_data->CodecPrivateData, p_data->cpd_len );
3401 ret = MP4_SetCodecExtraData( fmt, p_data );
3402 if( ret != VLC_SUCCESS )
3406 fmt->video.i_width = p_data->MaxWidth;
3407 fmt->video.i_height = p_data->MaxHeight;
3408 fmt->video.i_bits_per_pixel = 0x18;
3409 fmt->video.i_visible_width = p_data->MaxWidth;
3410 fmt->video.i_visible_height = p_data->MaxHeight;
3413 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3414 &fmt->video.i_frame_rate_base, p_track );
3416 if( fmt->video.i_frame_rate_base != 0 )
3418 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3419 (float)fmt->video.i_frame_rate_base;
3422 p_demux->p_sys->f_fps = 24;
3427 fmt->audio.i_channels = p_data->Channels;
3428 fmt->audio.i_rate = p_data->SamplingRate;
3429 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3430 fmt->audio.i_blockalign = p_data->nBlockAlign;
3432 fmt->i_bitrate = p_data->Bitrate;
3434 ret = MP4_SetCodecExtraData( fmt, p_data );
3435 if( ret != VLC_SUCCESS )
3448 * Return the track identified by tid
3450 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3452 demux_sys_t *p_sys = p_demux->p_sys;
3454 mp4_track_t *ret = NULL;
3455 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3457 ret = &p_sys->track[i];
3458 if( ret->i_track_ID == tid )
3461 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3465 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3467 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3468 mp4_chunk_t *ck = tk->cchunk;
3469 while( ck->i_sample < ck->i_sample_count )
3474 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3477 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3478 assert( sample_size > 0 );
3479 p_block = block_Alloc( sample_size );
3480 if( unlikely( !p_block ) )
3483 uint8_t *src = ck->p_sample_data[ck->i_sample];
3484 memcpy( p_block->p_buffer, src, sample_size );
3488 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3490 if( MP4_TrackGetPTSDelta( p_demux, tk, &i_delta ) )
3491 p_block->i_pts = p_block->i_dts + i_delta;
3492 else if( tk->fmt.i_cat != VIDEO_ES )
3493 p_block->i_pts = p_block->i_dts;
3495 p_block->i_pts = VLC_TS_INVALID;
3497 MP4_Block_Send( p_demux, tk, p_block );
3505 * \Note If we call that function too soon,
3506 * before the track has been selected by MP4_TrackSelect
3507 * (during the first execution of Demux), then the track gets disabled
3509 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3511 demux_sys_t *p_sys = p_demux->p_sys;
3513 uint32_t i_sample = 0;
3514 bool b_smooth = false;
3515 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3517 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3522 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3523 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3524 return VLC_EGENERIC;
3528 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3530 return VLC_EGENERIC;
3533 i_sample = p_track->i_sample;
3534 es_out_Del( p_demux->out, p_track->p_es );
3535 es_format_Clean( &p_track->fmt );
3538 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3540 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3542 p_track->i_sample = i_sample;
3544 /* Temporary hack until we support track selection */
3545 p_track->b_selected = true;
3546 p_track->b_ok = true;
3547 p_track->b_enable = true;
3549 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
3550 p_track->b_codec_need_restart = false;
3556 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
3557 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
3558 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
3559 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
3561 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
3563 MP4_Box_t *p_traf = MP4_BoxGet( p_chunk, "moof/traf" );
3566 msg_Warn( p_demux, "no traf box found!" );
3567 return VLC_EGENERIC;
3570 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
3573 msg_Warn( p_demux, "no tfhd box found!" );
3574 return VLC_EGENERIC;
3577 uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
3578 *i_tk_id = i_track_ID;
3579 assert( i_track_ID > 0 );
3580 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
3582 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
3584 return VLC_EGENERIC;
3586 mp4_chunk_t *ret = p_track->cchunk;
3588 if( BOXDATA(p_tfhd)->b_empty )
3589 msg_Warn( p_demux, "No samples in this chunk!" );
3591 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
3592 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
3593 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
3594 * and so on. Finally, suppose that we get the chunks the other way around,
3595 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
3596 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
3597 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
3598 * flush it, i.e. send to the decoder the samples not yet sent.
3599 * Note that all the samples to be flushed should worth less than 100 ms,
3600 * (though I did not do the formal proof) and thus this flushing mechanism
3601 * should not cause A/V sync issues, or delays or whatever.
3603 if( ret->i_sample < ret->i_sample_count )
3604 FlushChunk( p_demux, p_track );
3606 if( ret->i_sample_count )
3607 FreeAndResetChunk( ret );
3609 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
3612 msg_Warn( p_demux, "no trun box found!" );
3613 return VLC_EGENERIC;
3615 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
3617 ret->i_sample_count = p_trun_data->i_sample_count;
3618 assert( ret->i_sample_count > 0 );
3619 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
3620 ret->i_sample_first = p_track->i_sample_first;
3621 p_track->i_sample_first += ret->i_sample_count;
3623 ret->i_first_dts = p_track->i_first_dts;
3625 uint32_t default_duration = 0;
3626 uint32_t default_size = 0;
3628 MP4_GetDefaultSizeAndDuration( p_demux, BOXDATA(p_tfhd),
3629 &default_size, &default_duration );
3631 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3632 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3634 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
3636 free( ret->p_sample_count_dts );
3637 free( ret->p_sample_delta_dts );
3641 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3642 if( !ret->p_sample_count_pts )
3645 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
3647 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
3648 if( !ret->p_sample_offset_pts )
3652 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
3653 if( !ret->p_sample_size )
3656 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
3657 if( !ret->p_sample_data )
3660 uint32_t dur = 0, i_mdatlen = 0, len;
3661 uint32_t chunk_duration = 0, chunk_size = 0;
3663 /* Skip header of mdat */
3665 int i_read = stream_Read( p_demux->s, &mdat, 8 );
3666 i_mdatlen = GetDWBE( mdat );
3667 if ( i_read < 8 || i_mdatlen < 8 ||
3668 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
3669 return VLC_EGENERIC;
3671 for( uint32_t i = 0; i < ret->i_sample_count; i++)
3673 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
3674 dur = p_trun_data->p_samples[i].i_duration;
3676 dur = default_duration;
3677 ret->p_sample_delta_dts[i] = dur;
3678 chunk_duration += dur;
3680 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
3682 if( ret->p_sample_offset_pts )
3684 if ( p_trun_data->i_version == 0 )
3685 ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
3687 ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
3690 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
3691 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
3693 len = ret->p_sample_size[i] = default_size;
3695 if ( chunk_size + len > ( i_mdatlen - 8 ) )
3696 return VLC_EGENERIC;
3698 ret->p_sample_data[i] = malloc( len );
3699 if( ret->p_sample_data[i] == NULL )
3701 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
3703 return VLC_EGENERIC;
3706 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
3707 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
3709 if( p_track->b_codec_need_restart &&
3710 p_track->fmt.i_cat == VIDEO_ES )
3711 ReInitDecoder( p_demux, p_track );
3713 /* Skip if we didn't reach the end of mdat box */
3714 if ( chunk_size < (i_mdatlen - 8) )
3715 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
3717 p_track->b_has_non_empty_cchunk = true;
3723 * Get the next chunk of the track identified by i_tk_id.
3724 * \Note We don't want to seek all the time, so if the first chunk given by the
3725 * input method doesn't belong to the right track, we don't throw it away,
3726 * and so, in general, this function fetch more than one chunk.
3727 * Not to mention that a new init fragment might be put everywhere
3728 * between two chunks by the input method.
3730 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
3732 demux_sys_t *p_sys = p_demux->p_sys;
3733 mp4_track_t *p_track;
3735 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3737 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3739 return VLC_EGENERIC;
3741 if( !p_chunk->p_first )
3742 goto MP4_frg_GetChunks_Error;
3743 uint32_t i_type = p_chunk->p_first->i_type;
3745 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
3747 MP4_BoxFree( p_demux->s, p_sys->p_root );
3748 p_sys->p_root = p_chunk;
3750 if( i_type == ATOM_ftyp ) /* DASH */
3752 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
3755 msg_Warn( p_demux, "No tkhd found!" );
3756 goto MP4_frg_GetChunks_Error;
3758 tid = p_tkhd->data.p_tkhd->i_track_ID;
3760 else /* Smooth Streaming */
3762 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
3763 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
3764 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3766 msg_Warn( p_demux, "No StraBox found!" );
3767 goto MP4_frg_GetChunks_Error;
3769 tid = p_stra->data.p_stra->i_track_ID;
3772 p_track = MP4_frg_GetTrackByID( p_demux, tid );
3774 goto MP4_frg_GetChunks_Error;
3775 p_track->b_codec_need_restart = true;
3777 return MP4_frg_GetChunks( p_demux, i_tk_id );
3780 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
3781 goto MP4_frg_GetChunks_Error;
3783 MP4_BoxFree( p_demux->s, p_chunk );
3785 if( tid == i_tk_id )
3790 MP4_frg_GetChunks_Error:
3791 MP4_BoxFree( p_demux->s, p_chunk );
3792 return VLC_EGENERIC;
3798 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
3800 if( !p_track->b_ok || p_track->b_chapter )
3802 return VLC_EGENERIC;
3805 if( p_track->b_selected )
3807 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
3811 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
3812 p_track->b_selected = true;
3817 * DemuxFrg: read packet and send them to decoders
3818 * \return 1 on success, 0 on error.
3819 * TODO check for newly selected track
3821 int DemuxFrg( demux_t *p_demux )
3823 demux_sys_t *p_sys = p_demux->p_sys;
3825 unsigned i_track_selected;
3827 /* check for newly selected/unselected track */
3828 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
3830 mp4_track_t *tk = &p_sys->track[i_track];
3833 if( !tk->b_ok || tk->b_chapter )
3836 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
3837 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
3839 if( tk->b_selected && !b )
3841 MP4_TrackUnselect( p_demux, tk );
3843 else if( !tk->b_selected && b)
3845 MP4_frg_TrackSelect( p_demux, tk );
3848 if( tk->b_selected )
3852 if( i_track_selected <= 0 )
3854 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
3855 if( p_sys->i_timescale > 0 )
3857 int64_t i_length = CLOCK_FREQ *
3858 (mtime_t)p_sys->i_overall_duration /
3859 (mtime_t)p_sys->i_timescale;
3860 if( MP4_GetMoviePTS( p_sys ) >= i_length )
3865 msg_Warn( p_demux, "no track selected, exiting..." );
3869 /* first wait for the good time to read a packet */
3870 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
3872 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
3874 /* we will read 100ms for each stream so ...*/
3875 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
3877 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
3879 mp4_track_t *tk = &p_sys->track[i_track];
3881 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
3883 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
3887 if( !tk->b_has_non_empty_cchunk )
3889 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
3891 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
3896 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
3901 mp4_chunk_t *ck = tk->cchunk;
3902 if( ck->i_sample >= ck->i_sample_count )
3904 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
3905 ck->i_sample, ck->i_sample_count );
3909 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3910 p_block = block_Alloc( sample_size );
3911 uint8_t *src = ck->p_sample_data[ck->i_sample];
3912 memcpy( p_block->p_buffer, src, sample_size );
3915 if( ck->i_sample == ck->i_sample_count )
3916 tk->b_has_non_empty_cchunk = false;
3919 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3921 if( MP4_TrackGetPTSDelta( p_demux, tk, &i_delta ) )
3922 p_block->i_pts = p_block->i_dts + i_delta;
3923 else if( tk->fmt.i_cat != VIDEO_ES )
3924 p_block->i_pts = p_block->i_dts;
3926 p_block->i_pts = VLC_TS_INVALID;
3928 MP4_Block_Send( p_demux, tk, p_block );
3932 if( !tk->b_has_non_empty_cchunk )
3939 static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
3941 /* Read Next Chunk */
3942 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
3945 msg_Warn( p_demux, "no next chunk" );
3949 if( !p_chunk->p_first )
3951 msg_Warn( p_demux, "no next chunk child" );
3958 static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
3962 if ( p_root->i_pos == i_pos )
3964 assert( i_type == p_root->i_type );
3967 p_root = p_root->p_next;
3969 return (p_root != NULL);
3972 static mtime_t SumFragmentsDurations( demux_t *p_demux )
3974 demux_sys_t *p_sys = p_demux->p_sys;
3975 mtime_t i_max_duration = 0;
3977 for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
3979 mtime_t i_duration = 0;
3980 const mp4_fragment_t *p_fragment = &p_sys->moovfragment;
3981 while ( p_fragment && p_fragment->p_durations )
3983 i_duration += GetTrackDurationInFragment( p_fragment,
3984 p_sys->track[i].i_track_ID );
3985 p_fragment = p_fragment->p_next;
3987 i_max_duration = __MAX( i_duration, i_max_duration );
3990 return i_max_duration;
3993 /* Keeps an ordered chain of all fragments */
3994 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
3996 demux_sys_t *p_sys = p_demux->p_sys;
3997 mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
4001 if( p_moox->i_type == ATOM_moov )
4003 if ( !p_sys->moovfragment.p_moox )
4005 p_sys->moovfragment.p_moox = p_moox;
4007 if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
4009 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
4010 p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
4013 if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
4014 { /* duration might be wrong an be set to whole duration :/ */
4016 MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
4017 unsigned int i_trakcount = MP4_BoxCount( p_moox, "trak" );
4018 p_sys->moovfragment.p_durations = calloc( i_trakcount, sizeof(*p_sys->moovfragment.p_durations) );
4019 if ( i_trakcount && !p_sys->moovfragment.p_durations )
4021 p_sys->moovfragment.i_durations = i_trakcount;
4025 if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
4027 p_sys->moovfragment.p_durations[i_trakcount].i_duration = BOXDATA(p_tkhd)->i_duration;
4028 p_sys->moovfragment.p_durations[i_trakcount++].i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
4030 p_trak = p_trak->p_next;
4034 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4039 else // p_moox->i_type == ATOM_moof
4041 assert(p_moox->i_type == ATOM_moof);
4042 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
4043 while ( p_fragment )
4045 if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
4047 p_base_fragment = p_fragment;
4048 p_fragment = p_fragment->p_next;
4050 else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
4052 /* already exists */
4058 /* Add the moof fragment */
4059 mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
4060 if ( !p_new ) return false;
4061 p_new->p_moox = p_moox;
4062 p_new->i_durations = MP4_BoxCount( p_new->p_moox, "traf" );
4063 p_new->p_durations = calloc( p_new->i_durations, sizeof(*p_new->p_durations) );
4064 if ( p_new->i_durations && !p_new->p_durations )
4069 p_new->p_next = p_base_fragment->p_next;
4070 p_base_fragment->p_next = p_new;
4071 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4073 /* we have to probe all fragments :/ */
4074 uint64_t i_traf_base_data_offset = 0;
4075 uint64_t i_traf_min_offset = 0;
4076 uint32_t i_traf = 0;
4077 uint32_t i_traf_total_size = 0;
4078 uint32_t i_trafs_total_size = 0;
4080 MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
4081 unsigned int i_durationindex = 0;
4084 if ( p_traf->i_type != ATOM_traf )
4086 p_traf = p_traf->p_next;
4089 const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4090 const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4091 if ( !p_tfhd || !p_trun )
4093 p_traf = p_traf->p_next;
4097 uint32_t i_track_timescale = 0;
4098 uint32_t i_track_defaultsamplesize = 0;
4099 uint32_t i_track_defaultsampleduration = 0;
4100 if ( p_sys->b_smooth )
4102 /* stra sets identical timescales */
4103 i_track_timescale = p_sys->i_timescale;
4104 i_track_defaultsamplesize = 1;
4105 i_track_defaultsampleduration = 1;
4109 /* set trex for defaults */
4110 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4113 i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
4114 i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4117 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4120 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4121 if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4125 if ( !i_track_timescale )
4127 p_traf = p_traf->p_next;
4131 if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4133 i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
4135 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4137 i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
4142 i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
4144 i_traf_base_data_offset += i_traf_total_size;
4147 i_traf_total_size = 0;
4149 uint64_t i_trun_data_offset = i_traf_base_data_offset;
4150 uint64_t i_traf_duration = 0;
4151 uint32_t i_trun_size = 0;
4152 while ( p_trun && p_tfhd )
4154 if ( p_trun->i_type != ATOM_trun )
4156 p_trun = p_trun->p_next;
4159 const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4161 /* Get data offset */
4162 if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
4163 i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
4165 i_trun_data_offset += i_trun_size;
4169 /* Sum total time */
4170 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4172 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4173 i_traf_duration += p_trundata->p_samples[i].i_duration;
4175 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4177 i_traf_duration += p_trundata->i_sample_count *
4178 BOXDATA(p_tfhd)->i_default_sample_duration;
4182 i_traf_duration += p_trundata->i_sample_count *
4183 i_track_defaultsampleduration;
4186 /* Get total traf size */
4187 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
4189 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4190 i_trun_size += p_trundata->p_samples[i].i_size;
4192 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4194 i_trun_size += p_trundata->i_sample_count *
4195 BOXDATA(p_tfhd)->i_default_sample_size;
4199 i_trun_size += p_trundata->i_sample_count *
4200 i_track_defaultsamplesize;
4203 i_traf_total_size += i_trun_size;
4205 if ( i_traf_min_offset )
4206 i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
4208 i_traf_min_offset = i_trun_data_offset;
4210 p_trun = p_trun->p_next;
4213 i_trafs_total_size += i_traf_total_size;
4215 p_new->p_durations[i_durationindex].i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
4216 p_new->p_durations[i_durationindex++].i_duration = i_traf_duration * p_sys->i_timescale / i_track_timescale;
4218 p_traf = p_traf->p_next;
4222 p_new->i_chunk_range_min_offset = i_traf_min_offset;
4223 p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
4225 msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
4227 /* compute total duration with that new fragment if no overall provided */
4228 MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
4231 if ( p_sys->b_fragments_probed )
4232 p_sys->i_overall_duration = SumFragmentsDurations( p_demux );
4235 p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
4237 msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale );
4241 static int ProbeIndex( demux_t *p_demux )
4243 demux_sys_t *p_sys = p_demux->p_sys;
4244 uint64_t i_backup_pos, i_stream_size;
4245 uint8_t mfro[MP4_MFRO_BOXSIZE];
4246 assert( p_sys->b_seekable );
4248 if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4251 i_stream_size = stream_Size( p_demux->s );
4252 if ( ( i_stream_size >> 62 ) ||
4253 ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
4254 ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
4255 ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4258 msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4259 return VLC_EGENERIC;
4262 if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4263 VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4264 GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4266 uint32_t i_offset = GetDWBE( &mfro[12] );
4267 msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4268 if ( i_stream_size > i_offset &&
4269 stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4271 msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4272 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
4276 return stream_Seek( p_demux->s, i_backup_pos );
4279 static int ProbeFragments( demux_t *p_demux, bool b_force )
4281 demux_sys_t *p_sys = p_demux->p_sys;
4282 uint64_t i_current_pos;
4284 if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4285 msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
4287 assert( p_sys->p_root );
4289 if ( p_sys->b_fastseekable || b_force )
4291 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
4292 p_sys->b_fragments_probed = true;
4296 /* We stop at first moof, which validates our fragmentation condition
4297 * and we'll find others while reading. */
4298 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
4301 if ( !p_sys->moovfragment.p_moox )
4303 MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
4306 /* moov/mvex before probing should be present anyway */
4307 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
4308 return VLC_EGENERIC;
4310 AddFragment( p_demux, p_moov );
4313 MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
4316 if ( p_moof->i_type == ATOM_moof )
4317 AddFragment( p_demux, p_moof );
4318 p_moof = p_moof->p_next;
4321 MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
4324 stream_Seek( p_demux->s, p_mdat->i_pos );
4325 msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
4331 static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
4333 mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4334 while ( p_fragment )
4336 if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
4337 ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
4339 msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
4340 p_fragment->i_chunk_range_min_offset, i_pos,
4341 p_fragment->i_chunk_range_max_offset );
4346 p_fragment = p_fragment->p_next;
4352 /* Get a matching fragment data start by clock time */
4353 static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
4355 demux_sys_t *p_sys = p_demux->p_sys;
4356 mp4_fragment_t *p_fragment = &p_sys->moovfragment;
4357 mtime_t i_base_time = 0;
4358 mtime_t *pi_tracks_duration_total = calloc( p_sys->i_tracks, sizeof(mtime_t) );
4359 while ( p_fragment && pi_tracks_duration_total )
4361 if ( p_fragment == &p_sys->moovfragment &&
4362 p_fragment->i_chunk_range_max_offset == 0 )
4364 p_fragment = p_fragment->p_next;
4368 mtime_t i_length = 0;
4369 for( unsigned int i=0; i<p_sys->i_tracks; i++ )
4371 mtime_t i_track_duration = GetTrackDurationInFragment( p_fragment,
4372 p_sys->track[i].i_track_ID );
4373 pi_tracks_duration_total[i] += i_track_duration;
4374 i_length = __MAX(i_length, i_track_duration);
4377 i_length = i_length * CLOCK_FREQ / p_demux->p_sys->i_timescale; /* movie scale to time */
4378 if ( i_time >= i_base_time &&
4379 i_time <= i_base_time + i_length )
4385 i_base_time += i_length;
4386 p_fragment = p_fragment->p_next;
4389 if ( !p_demux->p_sys->b_fragments_probed )
4390 break; /* We have no way to guess missing fragments time */
4392 free( pi_tracks_duration_total );
4396 /* Returns fragment scaled time offset */
4397 static mtime_t LeafGetTrackFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment,
4398 unsigned int i_track_ID )
4400 mtime_t i_base_scaledtime = 0;
4401 mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
4402 while ( p_current != p_fragment )
4404 if ( p_current != &p_demux->p_sys->moovfragment ||
4405 p_current->i_chunk_range_max_offset )
4407 i_base_scaledtime += GetTrackDurationInFragment( p_current, i_track_ID );
4409 p_current = p_current->p_next;
4411 return i_base_scaledtime;
4414 static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
4415 const uint32_t i_defaultduration, const uint32_t i_defaultsize,
4416 const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
4418 assert( p_trun->i_sample_count );
4419 msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
4420 i_defaultduration, i_defaultsize, p_track->i_first_dts );
4422 uint32_t dur = 0, len;
4423 uint32_t chunk_size = 0;
4424 mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
4428 for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
4430 i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
4433 if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4434 dur = p_trun->p_samples[i].i_duration;
4436 dur = i_defaultduration;
4438 p_track->i_time += dur;
4440 if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4442 if ( p_trun->i_version == 1 )
4443 i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4445 i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4448 if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
4449 len = p_trun->p_samples[i].i_size;
4451 len = i_defaultsize;
4454 msg_Warn(p_demux, "Zero duration sample in trun.");
4457 msg_Warn(p_demux, "Zero length sample in trun.");
4459 if ( chunk_size + len > *pi_mdatlen )
4461 /* update data left in mdat */
4462 *pi_mdatlen -= chunk_size;
4463 return VLC_EGENERIC;
4466 block_t *p_block = MP4_Block_Read( p_demux, p_track, __MIN( len, INT32_MAX ) );
4467 uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
4470 /* update data left in mdat */
4471 *pi_mdatlen -= chunk_size;
4472 *pi_mdatlen -= i_read;
4474 return VLC_EGENERIC;
4477 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4479 p_demux->p_sys->i_pcr = i_nzdts;
4480 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
4483 if ( p_track->p_es )
4485 p_block->i_dts = VLC_TS_0 + i_nzdts;
4486 p_block->i_pts = VLC_TS_0 + i_nzpts;
4487 p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
4488 MP4_Block_Send( p_demux, p_track, p_block );
4490 else free( p_block );
4495 /* update data left in mdat */
4496 *pi_mdatlen -= chunk_size;
4500 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
4501 mp4_track_t **pp_tk, unsigned int *pi_chunk )
4503 const demux_sys_t *p_sys = p_demux->p_sys;
4505 mp4_track_t *p_tk_closest = NULL;
4506 uint64_t i_closest = UINT64_MAX;
4507 unsigned int i_chunk_closest;
4511 for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4513 for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
4515 if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
4517 i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
4518 p_tk_closest = &p_sys->track[i_track];
4519 i_chunk_closest = i_chunk;
4522 if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
4524 *pp_tk = &p_sys->track[i_track];
4525 *pi_chunk = i_chunk;
4531 if ( i_closest != UINT64_MAX )
4533 *pi_pos = i_closest;
4534 *pp_tk = p_tk_closest;
4535 *pi_chunk = i_chunk_closest;
4538 else return VLC_EGENERIC;
4541 static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
4542 uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
4543 const uint32_t i_maxbytes, const uint32_t i_maxsamples )
4545 MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
4547 return VLC_EGENERIC;
4549 if ( BOXDATA(p_stsz)->i_sample_size == 0 )
4551 uint32_t i_entry = i_sample;
4552 uint32_t i_totalbytes = 0;
4553 *pi_samplestoread = 1;
4555 if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
4556 return VLC_EGENERIC;
4558 *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
4559 i_totalbytes += *pi_samplessize;
4561 if ( *pi_samplessize > i_maxbytes )
4562 return VLC_EGENERIC;
4565 while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
4566 *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
4567 i_totalbytes + *pi_samplessize < i_maxbytes &&
4568 *pi_samplestoread < i_maxsamples
4571 i_totalbytes += *pi_samplessize;
4572 (*pi_samplestoread)++;
4575 *pi_samplessize = i_totalbytes;
4579 /* all samples have same size */
4580 *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
4581 *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
4582 *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
4583 *pi_samplessize = *pi_samplessize * *pi_samplestoread;
4589 static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
4592 uint32_t i_index = 0;
4594 while( i_sample > 0 )
4596 if( i_sample > p_chunk->p_sample_count_dts[i_index] )
4598 i_time += p_chunk->p_sample_count_dts[i_index] *
4599 p_chunk->p_sample_delta_dts[i_index];
4600 i_sample -= p_chunk->p_sample_count_dts[i_index];
4605 i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
4613 static int LeafParseMDATwithMOOV( demux_t *p_demux )
4615 demux_sys_t *p_sys = p_demux->p_sys;
4617 assert( p_sys->context.i_current_box_type == ATOM_mdat );
4618 assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
4620 uint64_t i_current_pos;
4621 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4622 return VLC_EGENERIC;
4624 if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
4626 /* Ready mdat section */
4628 int i_read = stream_Read( p_demux->s, &mdat, 8 );
4629 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
4630 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
4631 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4634 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
4635 msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
4636 return VLC_EGENERIC;
4639 p_sys->context.i_mdatbytesleft -= 8;
4642 while( p_sys->context.i_mdatbytesleft > 0 )
4644 mp4_track_t *p_track;
4645 unsigned int i_chunk;
4648 uint64_t i_pos = i_current_pos;
4649 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
4650 if ( i_ret == VLC_EGENERIC )
4652 msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
4655 else if( i_ret == VLC_ENOOBJ )
4657 assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
4658 int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
4659 i_current_pos += i_read;
4660 p_sys->context.i_mdatbytesleft -= i_read;
4661 if ( i_read == 0 ) goto error;
4666 mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
4668 uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
4669 uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
4671 assert(i_nb_samples_in_chunk);
4673 uint32_t i_nb_samples = 0;
4674 while ( i_nb_samples < i_nb_samples_in_chunk )
4676 uint32_t i_samplessize = 0;
4677 uint32_t i_samplescounttoread = 0;
4678 i_ret = LeafMOOVGetSamplesSize( p_track,
4679 i_nb_samples_at_chunk_start + i_nb_samples,
4680 &i_samplescounttoread, &i_samplessize,
4681 p_sys->context.i_mdatbytesleft,
4682 /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
4683 if ( i_ret != VLC_SUCCESS )
4686 if( p_sys->context.i_mdatbytesleft &&
4687 p_sys->context.i_mdatbytesleft >= i_samplessize )
4693 if( !(p_block = MP4_Block_Read( p_demux, p_track, i_samplessize )) )
4696 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
4698 p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
4699 msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
4704 i_nb_samples += i_samplescounttoread;
4705 i_current_pos += i_samplessize;
4706 p_sys->context.i_mdatbytesleft -= i_samplessize;
4709 mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
4710 i_time += p_chunk->i_first_dts;
4711 p_track->i_time = i_time;
4712 p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
4716 if( MP4_TrackGetPTSDelta( p_demux, p_track, &i_delta ) )
4717 p_block->i_pts = p_block->i_dts + i_delta;
4718 else if( p_track->fmt.i_cat != VIDEO_ES )
4719 p_block->i_pts = p_block->i_dts;
4721 p_block->i_pts = VLC_TS_INVALID;
4723 MP4_Block_Send( p_demux, p_track, p_block );
4725 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4727 p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
4728 p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
4729 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
4735 // sample size > left bytes
4739 p_track->i_sample += i_samplescounttoread;
4742 /* flag end of mdat section if needed */
4743 if ( p_sys->context.i_mdatbytesleft == 0 )
4744 p_sys->context.i_current_box_type = 0;
4751 /* Skip if we didn't reach the end of mdat box */
4752 if ( p_sys->context.i_mdatbytesleft > 0 )
4754 msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
4755 p_sys->context.i_mdatbytesleft );
4756 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
4758 p_sys->context.i_current_box_type = 0;
4763 static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
4765 demux_sys_t *p_sys = p_demux->p_sys;
4767 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
4769 mp4_track_t *p_track = &p_sys->track[i];
4770 if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
4772 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
4773 uint64_t i_offset = 0;
4775 if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4776 i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
4778 i_offset = i_moofpos;
4780 //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4781 // i_offset += i_moofpos;
4783 if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
4784 i_offset += p_trun_data->i_data_offset;
4788 if ( i_offset == i_pos )
4795 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
4797 demux_sys_t *p_sys = p_demux->p_sys;
4800 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
4802 mp4_track_t *p_track = &p_sys->track[i];
4803 p_track->context.p_tfhd = NULL;
4804 p_track->context.p_traf = NULL;
4805 p_track->context.p_trun = NULL;
4808 if ( p_moof->i_type == ATOM_moov )
4811 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4814 msg_Warn( p_demux, "no traf box found!" );
4815 return VLC_EGENERIC;
4821 if ( p_traf->i_type == ATOM_traf )
4823 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4824 for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
4826 mp4_track_t *p_track = &p_sys->track[i];
4827 if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
4829 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4832 p_track->context.p_tfhd = p_tfhd;
4833 p_track->context.p_traf = p_traf;
4834 p_track->context.p_trun = p_trun;
4836 p_tfhd = NULL; /* break loop */
4840 p_traf = p_traf->p_next;
4846 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
4847 uint64_t *pi_pos, mtime_t *pi_mooftime )
4849 MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
4852 if ( p_tfra->i_type == ATOM_tfra )
4855 const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
4856 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
4857 if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
4859 for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
4863 if ( p_data->i_version == 1 )
4865 i_time = *((uint64_t *)(p_data->p_time + i));
4866 i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
4870 i_time = p_data->p_time[i];
4871 i_offset = p_data->p_moof_offset[i];
4874 if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
4876 if ( i_pos == -1 ) /* Not in this traf */
4879 *pi_pos = (uint64_t) i_pos;
4880 *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
4881 if ( p_track->fmt.i_cat == AUDIO_ES )
4882 *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
4884 *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
4892 p_tfra = p_tfra->p_next;
4894 return VLC_EGENERIC;
4897 static void MP4_GetDefaultSizeAndDuration( demux_t *p_demux,
4898 const MP4_Box_data_tfhd_t *p_tfhd_data,
4899 uint32_t *pi_default_size,
4900 uint32_t *pi_default_duration )
4902 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4903 *pi_default_duration = p_tfhd_data->i_default_sample_duration;
4905 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4906 *pi_default_size = p_tfhd_data->i_default_sample_size;
4908 if( !*pi_default_duration || !*pi_default_size )
4910 const MP4_Box_t *p_trex = MP4_GetTrexByTrackID(
4911 MP4_BoxGet( p_demux->p_sys->p_root, "moov" ),
4912 p_tfhd_data->i_track_ID );
4915 if ( !*pi_default_duration )
4916 *pi_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
4917 if ( !*pi_default_size )
4918 *pi_default_size = BOXDATA(p_trex)->i_default_sample_size;
4923 static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
4925 demux_sys_t *p_sys = p_demux->p_sys;
4927 assert( p_moof->i_type == ATOM_moof );
4928 assert( p_sys->context.i_current_box_type == ATOM_mdat );
4930 if ( p_sys->context.i_mdatbytesleft == 0 )
4932 int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
4933 if ( i_ret != VLC_SUCCESS )
4936 /* Ready mdat section */
4938 int i_read = stream_Read( p_demux->s, &mdat, 8 );
4939 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
4940 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
4941 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4943 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
4944 msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
4945 return VLC_EGENERIC;
4947 p_sys->context.i_mdatbytesleft -= 8;
4950 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
4951 return VLC_EGENERIC;
4952 if ( p_sys->b_smooth )
4953 i_pos -= p_moof->i_pos;
4954 mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
4957 uint32_t i_trun_sample_default_duration = 0;
4958 uint32_t i_trun_sample_default_size = 0;
4960 if ( p_track->context.p_trun )
4962 /* Get defaults for this/these RUN */
4963 const MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
4964 MP4_GetDefaultSizeAndDuration( p_demux, p_tfhd_data,
4965 &i_trun_sample_default_size,
4966 &i_trun_sample_default_duration );
4968 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
4970 /* NOW PARSE TRUN WITH MDAT */
4971 int i_ret = LeafParseTRUN( p_demux, p_track,
4972 i_trun_sample_default_duration, i_trun_sample_default_size,
4973 p_trun_data, & p_sys->context.i_mdatbytesleft );
4974 if ( i_ret != VLC_SUCCESS )
4977 p_track->context.p_trun = p_track->context.p_trun->p_next;
4980 if ( p_sys->context.i_mdatbytesleft == 0 )
4981 p_sys->context.i_current_box_type = 0;
4986 /* Skip if we didn't reach the end of mdat box */
4987 if ( p_sys->context.i_mdatbytesleft > 0 )
4989 msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
4990 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
4993 p_sys->context.i_current_box_type = 0;
4998 static int DemuxAsLeaf( demux_t *p_demux )
5000 demux_sys_t *p_sys = p_demux->p_sys;
5001 unsigned i_track_selected = 0;
5003 /* check for newly selected/unselected track */
5004 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5006 mp4_track_t *tk = &p_sys->track[i_track];
5009 if( !tk->b_ok || tk->b_chapter )
5012 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5013 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5015 if( tk->b_selected && !b )
5016 MP4_TrackUnselect( p_demux, tk );
5017 else if( !tk->b_selected && b)
5018 MP4_frg_TrackSelect( p_demux, tk );
5020 if( tk->b_selected )
5024 if( i_track_selected <= 0 )
5026 msg_Warn( p_demux, "no track selected, exiting..." );
5030 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5032 /* Othewise mdat is skipped. FIXME: mdat reading ! */
5033 const uint8_t *p_peek;
5034 int i_read = stream_Peek( p_demux->s, &p_peek, 8 );
5038 p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5040 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5042 if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
5043 {// only if !b_probed ??
5044 MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
5046 MP4_Box_t *p_fragbox = MP4_BoxGet( p_vroot, "moof" );
5048 p_fragbox = MP4_BoxGet( p_vroot, "moov" );
5052 MP4_BoxFree( p_demux->s, p_vroot );
5053 msg_Err(p_demux, "no moof or moov in current chunk");
5057 MP4_Box_t *p_mfhd = MP4_BoxGet( p_fragbox, "mfhd" );
5058 if( p_mfhd && BOXDATA(p_mfhd) )
5060 /* Detect and Handle Passive Seek */
5061 if( p_sys->context.i_lastseqnumber + 1 != BOXDATA(p_mfhd)->i_sequence_number )
5063 msg_Info( p_demux, "Fragment sequence discontinuity detected %"PRIu32" != %"PRIu32,
5064 BOXDATA(p_mfhd)->i_sequence_number, p_sys->context.i_lastseqnumber + 1 );
5065 MP4_Box_t *p_sidx = MP4_BoxGet( p_vroot, "sidx" );
5066 if( p_sidx && BOXDATA(p_sidx) && BOXDATA(p_sidx)->i_timescale )
5068 mtime_t i_time_base = BOXDATA(p_sidx)->i_earliest_presentation_time;
5070 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5072 p_sys->track[i_track].i_time = i_time_base * p_sys->track[i_track].i_timescale
5073 / BOXDATA(p_sidx)->i_timescale;
5076 p_sys->i_time = i_time_base * p_sys->i_timescale / BOXDATA(p_sidx)->i_timescale;
5077 p_sys->i_pcr = VLC_TS_INVALID;
5080 p_sys->context.i_lastseqnumber = BOXDATA(p_mfhd)->i_sequence_number;
5084 while( p_vroot->p_first )
5086 if( p_vroot->p_first == p_fragbox )
5088 p_vroot->p_first = p_fragbox->p_next;
5092 MP4_Box_t *p_cur = p_vroot->p_first;
5093 p_vroot->p_first = p_cur->p_next;
5094 p_cur->p_next = NULL;
5095 msg_Dbg(p_demux, "ignoring box %4.4s", (char*)&p_cur->i_type);
5096 MP4_BoxFree( p_demux->s, p_cur );
5099 p_fragbox->p_next = NULL;
5101 /* create fragment */
5102 AddFragment( p_demux, p_fragbox );
5104 /* Append to root */
5105 p_sys->p_root->p_last->p_next = p_fragbox;
5106 p_sys->p_root->p_last = p_fragbox;
5107 MP4_BoxFree( p_demux->s, p_vroot );
5112 msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
5113 stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
5118 /* skip mdat header */
5119 p_sys->context.p_fragment = GetFragmentByPos( p_demux,
5120 stream_Tell( p_demux->s ) + 8, true );
5125 if ( p_sys->context.i_current_box_type == ATOM_mdat )
5127 assert(p_sys->context.p_fragment);
5128 if ( p_sys->context.p_fragment )
5129 switch( p_sys->context.p_fragment->p_moox->i_type )
5131 case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5132 LeafParseMDATwithMOOV( p_demux );
5135 LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
5138 msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
5143 /* Get current time */
5144 mtime_t i_lowest_dts = VLC_TS_INVALID;
5145 mtime_t i_lowest_time = INT64_MAX;
5146 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5148 const mp4_track_t *p_track = &p_sys->track[i_track];
5149 if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
5152 i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
5154 if ( i_lowest_dts == VLC_TS_INVALID )
5155 i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
5157 i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
5160 p_sys->i_time = i_lowest_time;
5161 p_sys->i_pcr = i_lowest_dts;
5162 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
5168 inline static mp4_track_t *MP4ASF_GetTrack( asf_packet_sys_t *p_packetsys,
5169 uint8_t i_stream_number )
5171 demux_sys_t *p_sys = p_packetsys->p_demux->p_sys;
5172 for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
5174 if ( p_sys->track[i].p_asf &&
5175 i_stream_number == p_sys->track[i].BOXDATA(p_asf)->i_stream_number )
5177 return &p_sys->track[i];
5183 static asf_track_info_t * MP4ASF_GetTrackInfo( asf_packet_sys_t *p_packetsys,
5184 uint8_t i_stream_number )
5186 mp4_track_t *p_track = MP4ASF_GetTrack( p_packetsys, i_stream_number );
5188 return &p_track->asfinfo;
5193 static void MP4ASF_Send( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
5194 block_t **pp_frame )
5196 mp4_track_t *p_track = MP4ASF_GetTrack( p_packetsys, i_stream_number );
5199 block_Release( *pp_frame );
5203 block_t *p_gather = block_ChainGather( *pp_frame );
5204 p_gather->i_dts = p_track->i_dts_backup;
5205 p_gather->i_pts = p_track->i_pts_backup;
5206 es_out_Send( p_packetsys->p_demux->out, p_track->p_es, p_gather );
5212 static void MP4ASF_ResetFrames( demux_sys_t *p_sys )
5214 for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
5216 mp4_track_t *p_track = &p_sys->track[i];
5217 if( p_track->asfinfo.p_frame )
5219 block_ChainRelease( p_track->asfinfo.p_frame );
5220 p_track->asfinfo.p_frame = NULL;